DNA SVN: r1340 - in trunk: dna-graph/src/main/java/org/jboss/dna/graph/property/basic and 23 other directories.
by dna-commits@lists.jboss.org
Author: rhauch
Date: 2009-11-24 12:46:37 -0500 (Tue, 24 Nov 2009)
New Revision: 1340
Added:
trunk/dna-graph/src/main/java/org/jboss/dna/graph/property/ValueTypeSystem.java
trunk/dna-graph/src/main/java/org/jboss/dna/graph/query/model/TypeSystem.java
Removed:
trunk/dna-graph/src/main/java/org/jboss/dna/graph/property/basic/DelegatingValueFactories.java
Modified:
trunk/dna-graph/src/main/java/org/jboss/dna/graph/property/ValueFactories.java
trunk/dna-graph/src/main/java/org/jboss/dna/graph/property/basic/StandardValueFactories.java
trunk/dna-graph/src/main/java/org/jboss/dna/graph/query/QueryBuilder.java
trunk/dna-graph/src/main/java/org/jboss/dna/graph/query/QueryContext.java
trunk/dna-graph/src/main/java/org/jboss/dna/graph/query/QueryResults.java
trunk/dna-graph/src/main/java/org/jboss/dna/graph/query/model/And.java
trunk/dna-graph/src/main/java/org/jboss/dna/graph/query/model/Between.java
trunk/dna-graph/src/main/java/org/jboss/dna/graph/query/model/ChildNode.java
trunk/dna-graph/src/main/java/org/jboss/dna/graph/query/model/ChildNodeJoinCondition.java
trunk/dna-graph/src/main/java/org/jboss/dna/graph/query/model/Column.java
trunk/dna-graph/src/main/java/org/jboss/dna/graph/query/model/Comparison.java
trunk/dna-graph/src/main/java/org/jboss/dna/graph/query/model/DescendantNode.java
trunk/dna-graph/src/main/java/org/jboss/dna/graph/query/model/DescendantNodeJoinCondition.java
trunk/dna-graph/src/main/java/org/jboss/dna/graph/query/model/EquiJoinCondition.java
trunk/dna-graph/src/main/java/org/jboss/dna/graph/query/model/FullTextSearch.java
trunk/dna-graph/src/main/java/org/jboss/dna/graph/query/model/Join.java
trunk/dna-graph/src/main/java/org/jboss/dna/graph/query/model/JoinType.java
trunk/dna-graph/src/main/java/org/jboss/dna/graph/query/model/Length.java
trunk/dna-graph/src/main/java/org/jboss/dna/graph/query/model/Limit.java
trunk/dna-graph/src/main/java/org/jboss/dna/graph/query/model/LowerCase.java
trunk/dna-graph/src/main/java/org/jboss/dna/graph/query/model/Operator.java
trunk/dna-graph/src/main/java/org/jboss/dna/graph/query/model/Order.java
trunk/dna-graph/src/main/java/org/jboss/dna/graph/query/model/PropertyExistence.java
trunk/dna-graph/src/main/java/org/jboss/dna/graph/query/model/PropertyValue.java
trunk/dna-graph/src/main/java/org/jboss/dna/graph/query/model/Query.java
trunk/dna-graph/src/main/java/org/jboss/dna/graph/query/model/Readable.java
trunk/dna-graph/src/main/java/org/jboss/dna/graph/query/model/SameNode.java
trunk/dna-graph/src/main/java/org/jboss/dna/graph/query/model/SameNodeJoinCondition.java
trunk/dna-graph/src/main/java/org/jboss/dna/graph/query/model/SelectorName.java
trunk/dna-graph/src/main/java/org/jboss/dna/graph/query/model/SetCriteria.java
trunk/dna-graph/src/main/java/org/jboss/dna/graph/query/model/SetQuery.java
trunk/dna-graph/src/main/java/org/jboss/dna/graph/query/model/Visitable.java
trunk/dna-graph/src/main/java/org/jboss/dna/graph/query/model/Visitors.java
trunk/dna-graph/src/main/java/org/jboss/dna/graph/query/optimize/ChooseJoinAlgorithm.java
trunk/dna-graph/src/main/java/org/jboss/dna/graph/query/optimize/CopyCriteria.java
trunk/dna-graph/src/main/java/org/jboss/dna/graph/query/optimize/RaiseSelectCriteria.java
trunk/dna-graph/src/main/java/org/jboss/dna/graph/query/optimize/RewriteIdentityJoins.java
trunk/dna-graph/src/main/java/org/jboss/dna/graph/query/parse/QueryParser.java
trunk/dna-graph/src/main/java/org/jboss/dna/graph/query/parse/QueryParsers.java
trunk/dna-graph/src/main/java/org/jboss/dna/graph/query/parse/SqlQueryParser.java
trunk/dna-graph/src/main/java/org/jboss/dna/graph/query/plan/CanonicalPlanner.java
trunk/dna-graph/src/main/java/org/jboss/dna/graph/query/plan/PlanNode.java
trunk/dna-graph/src/main/java/org/jboss/dna/graph/query/plan/PlanUtil.java
trunk/dna-graph/src/main/java/org/jboss/dna/graph/query/process/AbstractAccessComponent.java
trunk/dna-graph/src/main/java/org/jboss/dna/graph/query/process/JoinComponent.java
trunk/dna-graph/src/main/java/org/jboss/dna/graph/query/process/ProcessingComponent.java
trunk/dna-graph/src/main/java/org/jboss/dna/graph/query/process/QueryResultColumns.java
trunk/dna-graph/src/main/java/org/jboss/dna/graph/query/process/QueryResults.java
trunk/dna-graph/src/main/java/org/jboss/dna/graph/query/process/SelectComponent.java
trunk/dna-graph/src/main/java/org/jboss/dna/graph/query/process/SortValuesComponent.java
trunk/dna-graph/src/main/java/org/jboss/dna/graph/query/validate/ImmutableColumn.java
trunk/dna-graph/src/main/java/org/jboss/dna/graph/query/validate/ImmutableSchemata.java
trunk/dna-graph/src/main/java/org/jboss/dna/graph/query/validate/ImmutableTable.java
trunk/dna-graph/src/main/java/org/jboss/dna/graph/query/validate/Schemata.java
trunk/dna-graph/src/main/java/org/jboss/dna/graph/query/validate/Validator.java
trunk/dna-graph/src/main/java/org/jboss/dna/graph/search/SearchEngine.java
trunk/dna-graph/src/test/java/org/jboss/dna/graph/query/QueryBuilderTest.java
trunk/dna-graph/src/test/java/org/jboss/dna/graph/query/model/AbstractQueryObjectTest.java
trunk/dna-graph/src/test/java/org/jboss/dna/graph/query/model/QueryTest.java
trunk/dna-graph/src/test/java/org/jboss/dna/graph/query/model/SetQueryTest.java
trunk/dna-graph/src/test/java/org/jboss/dna/graph/query/optimize/AddAccessNodesTest.java
trunk/dna-graph/src/test/java/org/jboss/dna/graph/query/optimize/ChooseJoinAlgorithmTest.java
trunk/dna-graph/src/test/java/org/jboss/dna/graph/query/optimize/PushSelectCriteriaTest.java
trunk/dna-graph/src/test/java/org/jboss/dna/graph/query/optimize/ReplaceViewsTest.java
trunk/dna-graph/src/test/java/org/jboss/dna/graph/query/optimize/RewriteAsRangeCriteriaTest.java
trunk/dna-graph/src/test/java/org/jboss/dna/graph/query/optimize/RightOuterToLeftOuterJoinsTest.java
trunk/dna-graph/src/test/java/org/jboss/dna/graph/query/optimize/RuleBasedOptimizerTest.java
trunk/dna-graph/src/test/java/org/jboss/dna/graph/query/parse/QueryParsersTest.java
trunk/dna-graph/src/test/java/org/jboss/dna/graph/query/parse/SqlQueryParserTest.java
trunk/dna-graph/src/test/java/org/jboss/dna/graph/query/plan/CanonicalPlannerTest.java
trunk/dna-graph/src/test/java/org/jboss/dna/graph/query/process/AbstractQueryResultsTest.java
trunk/dna-graph/src/test/java/org/jboss/dna/graph/query/process/DistinctComponentTest.java
trunk/dna-graph/src/test/java/org/jboss/dna/graph/query/process/QueryResultColumnsTest.java
trunk/dna-graph/src/test/java/org/jboss/dna/graph/query/process/QueryResultsTest.java
trunk/dna-graph/src/test/java/org/jboss/dna/graph/query/process/SortLocationsComponentTest.java
trunk/dna-graph/src/test/java/org/jboss/dna/graph/query/process/SortValuesComponentTest.java
trunk/dna-graph/src/test/java/org/jboss/dna/graph/query/validate/ImmutableSchemataBuilderTest.java
trunk/dna-graph/src/test/java/org/jboss/dna/graph/search/SearchEngineTest.java
trunk/dna-jcr-tck/pom.xml
trunk/dna-jcr/src/main/java/org/jboss/dna/jcr/AbstractJcrNode.java
trunk/dna-jcr/src/main/java/org/jboss/dna/jcr/xpath/XPathParser.java
trunk/dna-jcr/src/main/java/org/jboss/dna/jcr/xpath/XPathQueryParser.java
trunk/dna-jcr/src/main/java/org/jboss/dna/jcr/xpath/XPathToQueryTranslator.java
trunk/dna-jcr/src/test/java/org/jboss/dna/jcr/JcrSessionTest.java
trunk/dna-jcr/src/test/java/org/jboss/dna/jcr/WorkspaceLockManagerTest.java
trunk/dna-jcr/src/test/java/org/jboss/dna/jcr/xpath/XPathParserTest.java
trunk/dna-jcr/src/test/java/org/jboss/dna/jcr/xpath/XPathToQueryTranslatorTest.java
trunk/dna-search/src/main/java/org/jboss/dna/search/LuceneQueryComponent.java
trunk/dna-search/src/test/java/org/jboss/dna/search/SearchEngineTest.java
Log:
DNA-467 Refactored the query functionality to minimize dependencies on the rest of 'dna-graph', meaning that we can probably extract it and that it would be useful for other projects. This impacted a fair bit of code, but it does clean up the assumptions and dependencies of the query engine. Search is still not very decoupled. But everything still works and all unit tests pass.
Modified: trunk/dna-graph/src/main/java/org/jboss/dna/graph/property/ValueFactories.java
===================================================================
--- trunk/dna-graph/src/main/java/org/jboss/dna/graph/property/ValueFactories.java 2009-11-24 17:44:29 UTC (rev 1339)
+++ trunk/dna-graph/src/main/java/org/jboss/dna/graph/property/ValueFactories.java 2009-11-24 17:46:37 UTC (rev 1340)
@@ -26,6 +26,7 @@
import java.math.BigDecimal;
import java.net.URI;
import net.jcip.annotations.ThreadSafe;
+import org.jboss.dna.graph.query.model.TypeSystem;
/**
* The set of standard {@link ValueFactory} instances.
@@ -34,6 +35,13 @@
public interface ValueFactories extends Iterable<ValueFactory<?>> {
/**
+ * Get the type system associated with these factories.
+ *
+ * @return the type system; never null
+ */
+ TypeSystem getTypeSystem();
+
+ /**
* Get the value factory that creates values of the supplied {@link PropertyType type}.
*
* @param type the type for the values
Added: trunk/dna-graph/src/main/java/org/jboss/dna/graph/property/ValueTypeSystem.java
===================================================================
--- trunk/dna-graph/src/main/java/org/jboss/dna/graph/property/ValueTypeSystem.java (rev 0)
+++ trunk/dna-graph/src/main/java/org/jboss/dna/graph/property/ValueTypeSystem.java 2009-11-24 17:46:37 UTC (rev 1340)
@@ -0,0 +1,353 @@
+/*
+ * JBoss DNA (http://www.jboss.org/dna)
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ * See the AUTHORS.txt file in the distribution for a full listing of
+ * individual contributors.
+ *
+ * JBoss DNA is free software. Unless otherwise indicated, all code in JBoss DNA
+ * is licensed to you under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation; either version 2.1 of
+ * the License, or (at your option) any later version.
+ *
+ * JBoss DNA is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this software; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+ */
+package org.jboss.dna.graph.property;
+
+import java.math.BigDecimal;
+import java.net.URI;
+import java.util.Collections;
+import java.util.Comparator;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Set;
+import java.util.UUID;
+import org.jboss.dna.common.util.Base64;
+import org.jboss.dna.graph.query.model.TypeSystem;
+
+/**
+ *
+ */
+public class ValueTypeSystem implements TypeSystem {
+
+ private final String defaultTypeName;
+ protected final ValueFactories valueFactories;
+ protected final ValueFactory<String> stringValueFactory;
+ private final Map<PropertyType, TypeFactory<?>> typeFactoriesByPropertyType;
+ private final Map<String, TypeFactory<?>> typeFactoriesByName;
+ private final TypeFactory<String> stringFactory;
+ private final TypeFactory<Boolean> booleanFactory;
+ private final TypeFactory<Long> longFactory;
+ private final TypeFactory<Double> doubleFactory;
+ private final TypeFactory<?> dateFactory;
+ private final TypeFactory<?> pathFactory;
+
+ /**
+ * Create a type system using the supplied value factories.
+ *
+ * @param valueFactories the value factories;
+ * @throws IllegalArgumentException if the value factories are null
+ */
+ public ValueTypeSystem( ValueFactories valueFactories ) {
+ this.valueFactories = valueFactories;
+ this.defaultTypeName = PropertyType.STRING.getName().toUpperCase();
+ Map<PropertyType, TypeFactory<?>> factories = new HashMap<PropertyType, TypeFactory<?>>();
+ this.stringValueFactory = valueFactories.getStringFactory();
+ this.stringFactory = new Factory<String>(stringValueFactory) {
+ /**
+ * {@inheritDoc}
+ *
+ * @see org.jboss.dna.graph.property.ValueTypeSystem.Factory#asString(java.lang.Object)
+ */
+ @Override
+ public String asString( Object value ) {
+ return stringValueFactory.create(value);
+ }
+
+ /**
+ * {@inheritDoc}
+ *
+ * @see org.jboss.dna.graph.property.ValueTypeSystem.Factory#asReadableString(java.lang.Object)
+ */
+ @Override
+ public String asReadableString( Object value ) {
+ return stringValueFactory.create(value);
+ }
+ };
+ this.booleanFactory = new Factory<Boolean>(valueFactories.getBooleanFactory());
+ this.longFactory = new Factory<Long>(valueFactories.getLongFactory());
+ this.doubleFactory = new Factory<Double>(valueFactories.getDoubleFactory());
+ this.dateFactory = new Factory<DateTime>(valueFactories.getDateFactory()) {
+
+ /**
+ * {@inheritDoc}
+ *
+ * @see org.jboss.dna.graph.property.ValueTypeSystem.Factory#create(java.lang.String)
+ */
+ @Override
+ public DateTime create( String value ) throws ValueFormatException {
+ DateTime result = valueFactory.create(value);
+ // Convert the timestamp to UTC, since that's how everything should be queried ...
+ return result.toUtcTimeZone();
+ }
+ };
+ this.pathFactory = new Factory<Path>(valueFactories.getPathFactory());
+ factories.put(PropertyType.STRING, this.stringFactory);
+ factories.put(PropertyType.BOOLEAN, this.booleanFactory);
+ factories.put(PropertyType.DATE, this.dateFactory);
+ factories.put(PropertyType.DECIMAL, new Factory<BigDecimal>(valueFactories.getDecimalFactory()));
+ factories.put(PropertyType.DOUBLE, this.doubleFactory);
+ factories.put(PropertyType.LONG, this.longFactory);
+ factories.put(PropertyType.NAME, new Factory<Name>(valueFactories.getNameFactory()));
+ factories.put(PropertyType.OBJECT, new Factory<Object>(valueFactories.getObjectFactory()));
+ factories.put(PropertyType.PATH, this.pathFactory);
+ factories.put(PropertyType.REFERENCE, new Factory<Reference>(valueFactories.getReferenceFactory()));
+ factories.put(PropertyType.URI, new Factory<URI>(valueFactories.getUriFactory()));
+ factories.put(PropertyType.UUID, new Factory<UUID>(valueFactories.getUuidFactory()));
+ factories.put(PropertyType.BINARY, new Factory<Binary>(valueFactories.getBinaryFactory()) {
+ /**
+ * {@inheritDoc}
+ *
+ * @see org.jboss.dna.graph.property.ValueTypeSystem.Factory#asReadableString(java.lang.Object)
+ */
+ @Override
+ public String asReadableString( Object value ) {
+ Binary binary = this.valueFactory.create(value);
+ // Just print out the SHA-1 hash in Base64, plus length
+ return "(Binary,length=" + binary.getSize() + ",SHA1=" + Base64.encodeBytes(binary.getHash()) + ")";
+ }
+
+ /**
+ * {@inheritDoc}
+ *
+ * @see org.jboss.dna.graph.property.ValueTypeSystem.Factory#length(java.lang.Object)
+ */
+ @Override
+ public long length( Object value ) {
+ Binary binary = this.valueFactory.create(value);
+ return binary != null ? binary.getSize() : 0;
+ }
+ });
+ this.typeFactoriesByPropertyType = Collections.unmodifiableMap(factories);
+ Map<String, TypeFactory<?>> byName = new HashMap<String, TypeFactory<?>>();
+ for (TypeFactory<?> factory : factories.values()) {
+ byName.put(factory.getTypeName(), factory);
+ }
+ this.typeFactoriesByName = Collections.unmodifiableMap(byName);
+ }
+
+ /**
+ * {@inheritDoc}
+ *
+ * @see org.jboss.dna.graph.query.model.TypeSystem#asString(java.lang.Object)
+ */
+ public String asString( Object value ) {
+ return stringValueFactory.create(value);
+ }
+
+ /**
+ * {@inheritDoc}
+ *
+ * @see org.jboss.dna.graph.query.model.TypeSystem#getBooleanFactory()
+ */
+ public TypeFactory<Boolean> getBooleanFactory() {
+ return booleanFactory;
+ }
+
+ /**
+ * {@inheritDoc}
+ *
+ * @see org.jboss.dna.graph.query.model.TypeSystem#getStringFactory()
+ */
+ public TypeFactory<String> getStringFactory() {
+ return this.stringFactory;
+ }
+
+ /**
+ * {@inheritDoc}
+ *
+ * @see org.jboss.dna.graph.query.model.TypeSystem#getDateTimeFactory()
+ */
+ public TypeFactory<?> getDateTimeFactory() {
+ return dateFactory;
+ }
+
+ /**
+ * {@inheritDoc}
+ *
+ * @see org.jboss.dna.graph.query.model.TypeSystem#getDefaultType()
+ */
+ public String getDefaultType() {
+ return defaultTypeName;
+ }
+
+ /**
+ * {@inheritDoc}
+ *
+ * @see org.jboss.dna.graph.query.model.TypeSystem#getDefaultComparator()
+ */
+ @SuppressWarnings( "unchecked" )
+ public Comparator<Object> getDefaultComparator() {
+ return (Comparator<Object>)PropertyType.OBJECT.getComparator();
+ }
+
+ /**
+ * {@inheritDoc}
+ *
+ * @see org.jboss.dna.graph.query.model.TypeSystem#getDoubleFactory()
+ */
+ public TypeFactory<Double> getDoubleFactory() {
+ return doubleFactory;
+ }
+
+ /**
+ * {@inheritDoc}
+ *
+ * @see org.jboss.dna.graph.query.model.TypeSystem#getLongFactory()
+ */
+ public TypeFactory<Long> getLongFactory() {
+ return longFactory;
+ }
+
+ /**
+ * {@inheritDoc}
+ *
+ * @see org.jboss.dna.graph.query.model.TypeSystem#getPathFactory()
+ */
+ public TypeFactory<?> getPathFactory() {
+ return pathFactory;
+ }
+
+ /**
+ * {@inheritDoc}
+ *
+ * @see org.jboss.dna.graph.query.model.TypeSystem#getTypeFactory(java.lang.String)
+ */
+ public TypeFactory<?> getTypeFactory( String typeName ) {
+ if (typeName == null) return null;
+ return typeFactoriesByName.get(typeName.toUpperCase()); // may be null
+ }
+
+ /**
+ * {@inheritDoc}
+ *
+ * @see org.jboss.dna.graph.query.model.TypeSystem#getTypeFactory(java.lang.Object)
+ */
+ public TypeFactory<?> getTypeFactory( Object prototype ) {
+ ValueFactory<?> valueFactory = valueFactories.getValueFactory(prototype);
+ if (valueFactory == null) return null;
+ PropertyType type = valueFactory.getPropertyType();
+ assert type != null;
+ return typeFactoriesByPropertyType.get(type);
+ }
+
+ /**
+ * {@inheritDoc}
+ *
+ * @see org.jboss.dna.graph.query.model.TypeSystem#getTypeNames()
+ */
+ public Set<String> getTypeNames() {
+ return typeFactoriesByName.keySet();
+ }
+
+ protected class Factory<T> implements TypeFactory<T> {
+ protected final PropertyType type;
+ protected final ValueFactory<T> valueFactory;
+ protected final String typeName;
+
+ protected Factory( ValueFactory<T> valueFactory ) {
+ this.valueFactory = valueFactory;
+ this.type = this.valueFactory.getPropertyType();
+ this.typeName = type.getName().toUpperCase();
+ }
+
+ /**
+ * {@inheritDoc}
+ *
+ * @see org.jboss.dna.graph.query.model.TypeSystem.TypeFactory#asReadableString(java.lang.Object)
+ */
+ public String asReadableString( Object value ) {
+ return asString(value);
+ }
+
+ /**
+ * {@inheritDoc}
+ *
+ * @see org.jboss.dna.graph.query.model.TypeSystem.TypeFactory#asString(java.lang.Object)
+ */
+ public String asString( Object value ) {
+ if (value instanceof String) {
+ // Convert to the typed value, then back to a string ...
+ value = valueFactory.create((String)value);
+ }
+ return stringValueFactory.create(value);
+ }
+
+ /**
+ * {@inheritDoc}
+ *
+ * @see org.jboss.dna.graph.query.model.TypeSystem.TypeFactory#create(java.lang.String)
+ */
+ public T create( String value ) throws ValueFormatException {
+ return valueFactory.create(value);
+ }
+
+ /**
+ * {@inheritDoc}
+ *
+ * @see org.jboss.dna.graph.query.model.TypeSystem.TypeFactory#create(java.lang.Object)
+ */
+ public T create( Object value ) throws ValueFormatException {
+ return valueFactory.create(value);
+ }
+
+ /**
+ * {@inheritDoc}
+ *
+ * @see org.jboss.dna.graph.query.model.TypeSystem.TypeFactory#getType()
+ */
+ @SuppressWarnings( "unchecked" )
+ public Class<T> getType() {
+ return (Class<T>)type.getValueClass();
+ }
+
+ /**
+ * {@inheritDoc}
+ *
+ * @see org.jboss.dna.graph.query.model.TypeSystem.TypeFactory#length(java.lang.Object)
+ */
+ public long length( Object value ) {
+ String str = asString(valueFactory.create(value));
+ return str != null ? str.length() : 0;
+ }
+
+ /**
+ * {@inheritDoc}
+ *
+ * @see org.jboss.dna.graph.query.model.TypeSystem.TypeFactory#getComparator()
+ */
+ @SuppressWarnings( "unchecked" )
+ public Comparator<T> getComparator() {
+ return (Comparator<T>)type.getComparator();
+ }
+
+ /**
+ * {@inheritDoc}
+ *
+ * @see org.jboss.dna.graph.query.model.TypeSystem.TypeFactory#getTypeName()
+ */
+ public String getTypeName() {
+ return typeName;
+ }
+
+ }
+}
Property changes on: trunk/dna-graph/src/main/java/org/jboss/dna/graph/property/ValueTypeSystem.java
___________________________________________________________________
Name: svn:keywords
+ Id Revision
Name: svn:eol-style
+ LF
Deleted: trunk/dna-graph/src/main/java/org/jboss/dna/graph/property/basic/DelegatingValueFactories.java
===================================================================
--- trunk/dna-graph/src/main/java/org/jboss/dna/graph/property/basic/DelegatingValueFactories.java 2009-11-24 17:44:29 UTC (rev 1339)
+++ trunk/dna-graph/src/main/java/org/jboss/dna/graph/property/basic/DelegatingValueFactories.java 2009-11-24 17:46:37 UTC (rev 1340)
@@ -1,103 +0,0 @@
-/*
- * JBoss DNA (http://www.jboss.org/dna)
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership. Some portions may be licensed
- * to Red Hat, Inc. under one or more contributor license agreements.
- * See the AUTHORS.txt file in the distribution for a full listing of
- * individual contributors.
- *
- * JBoss DNA is free software. Unless otherwise indicated, all code in JBoss DNA
- * is licensed to you under the terms of the GNU Lesser General Public License as
- * published by the Free Software Foundation; either version 2.1 of
- * the License, or (at your option) any later version.
- *
- * JBoss DNA is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with this software; if not, write to the Free
- * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
- * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
- */
-package org.jboss.dna.graph.property.basic;
-
-import java.math.BigDecimal;
-import java.net.URI;
-import net.jcip.annotations.Immutable;
-import org.jboss.dna.graph.property.BinaryFactory;
-import org.jboss.dna.graph.property.DateTimeFactory;
-import org.jboss.dna.graph.property.NameFactory;
-import org.jboss.dna.graph.property.PathFactory;
-import org.jboss.dna.graph.property.Reference;
-import org.jboss.dna.graph.property.UuidFactory;
-import org.jboss.dna.graph.property.ValueFactories;
-import org.jboss.dna.graph.property.ValueFactory;
-
-/**
- * A {@link ValueFactories} implementation that delegates to another instance, and that is often useful for subclassing.
- */
-@Immutable
-public class DelegatingValueFactories extends AbstractValueFactories {
-
- private final ValueFactories delegate;
-
- protected DelegatingValueFactories( ValueFactories delegate ) {
- assert delegate != null;
- this.delegate = delegate;
- }
-
- public BinaryFactory getBinaryFactory() {
- return delegate.getBinaryFactory();
- }
-
- public ValueFactory<Boolean> getBooleanFactory() {
- return delegate.getBooleanFactory();
- }
-
- public DateTimeFactory getDateFactory() {
- return delegate.getDateFactory();
- }
-
- public ValueFactory<BigDecimal> getDecimalFactory() {
- return delegate.getDecimalFactory();
- }
-
- public ValueFactory<Double> getDoubleFactory() {
- return delegate.getDoubleFactory();
- }
-
- public ValueFactory<Long> getLongFactory() {
- return delegate.getLongFactory();
- }
-
- public NameFactory getNameFactory() {
- return delegate.getNameFactory();
- }
-
- public ValueFactory<Object> getObjectFactory() {
- return delegate.getObjectFactory();
- }
-
- public PathFactory getPathFactory() {
- return delegate.getPathFactory();
- }
-
- public ValueFactory<Reference> getReferenceFactory() {
- return delegate.getReferenceFactory();
- }
-
- public ValueFactory<String> getStringFactory() {
- return delegate.getStringFactory();
- }
-
- public ValueFactory<URI> getUriFactory() {
- return delegate.getUriFactory();
- }
-
- public UuidFactory getUuidFactory() {
- return delegate.getUuidFactory();
- }
-
-}
Modified: trunk/dna-graph/src/main/java/org/jboss/dna/graph/property/basic/StandardValueFactories.java
===================================================================
--- trunk/dna-graph/src/main/java/org/jboss/dna/graph/property/basic/StandardValueFactories.java 2009-11-24 17:44:29 UTC (rev 1339)
+++ trunk/dna-graph/src/main/java/org/jboss/dna/graph/property/basic/StandardValueFactories.java 2009-11-24 17:46:37 UTC (rev 1340)
@@ -40,6 +40,8 @@
import org.jboss.dna.graph.property.Reference;
import org.jboss.dna.graph.property.UuidFactory;
import org.jboss.dna.graph.property.ValueFactory;
+import org.jboss.dna.graph.property.ValueTypeSystem;
+import org.jboss.dna.graph.query.model.TypeSystem;
/**
* The standard set of {@link ValueFactory value factories}.
@@ -66,6 +68,8 @@
private final TextDecoder decoder;
private final TextEncoder encoder;
+ private final TypeSystem typeSystem;
+
/**
* Create a standard set of value factories, using the {@link ValueFactory#DEFAULT_DECODER default decoder}.
*
@@ -122,6 +126,8 @@
this.uuidFactory = (UuidFactory)getFactory(factories, new UuidValueFactory(this.decoder, this.stringFactory));
this.uriFactory = getFactory(factories, new UriValueFactory(this.namespaceRegistry, this.decoder, this.stringFactory));
this.objectFactory = getFactory(factories, new ObjectValueFactory(this.decoder, this.stringFactory, this.binaryFactory));
+
+ this.typeSystem = new ValueTypeSystem(this);
}
@SuppressWarnings( "unchecked" )
@@ -137,6 +143,15 @@
}
/**
+ * {@inheritDoc}
+ *
+ * @see org.jboss.dna.graph.property.ValueFactories#getTypeSystem()
+ */
+ public TypeSystem getTypeSystem() {
+ return typeSystem;
+ }
+
+ /**
* @return decoder
*/
public TextDecoder getTextDecoder() {
Modified: trunk/dna-graph/src/main/java/org/jboss/dna/graph/query/QueryBuilder.java
===================================================================
--- trunk/dna-graph/src/main/java/org/jboss/dna/graph/query/QueryBuilder.java 2009-11-24 17:44:29 UTC (rev 1339)
+++ trunk/dna-graph/src/main/java/org/jboss/dna/graph/query/QueryBuilder.java 2009-11-24 17:46:37 UTC (rev 1340)
@@ -33,15 +33,12 @@
import java.util.concurrent.atomic.AtomicBoolean;
import net.jcip.annotations.NotThreadSafe;
import org.jboss.dna.common.util.CheckArg;
-import org.jboss.dna.graph.ExecutionContext;
import org.jboss.dna.graph.GraphI18n;
import org.jboss.dna.graph.property.Binary;
import org.jboss.dna.graph.property.DateTime;
import org.jboss.dna.graph.property.Name;
import org.jboss.dna.graph.property.Path;
import org.jboss.dna.graph.property.PropertyType;
-import org.jboss.dna.graph.property.ValueFactories;
-import org.jboss.dna.graph.property.ValueFormatException;
import org.jboss.dna.graph.query.model.AllNodes;
import org.jboss.dna.graph.query.model.And;
import org.jboss.dna.graph.query.model.Between;
@@ -85,6 +82,7 @@
import org.jboss.dna.graph.query.model.SetQuery;
import org.jboss.dna.graph.query.model.Source;
import org.jboss.dna.graph.query.model.StaticOperand;
+import org.jboss.dna.graph.query.model.TypeSystem;
import org.jboss.dna.graph.query.model.UpperCase;
import org.jboss.dna.graph.query.model.Visitors;
import org.jboss.dna.graph.query.model.SetQuery.Operation;
@@ -232,7 +230,7 @@
@NotThreadSafe
public class QueryBuilder {
- protected final ExecutionContext context;
+ protected final TypeSystem typeSystem;
protected Source source = new AllNodes();
protected Constraint constraint;
protected List<Column> columns = new LinkedList<Column>();
@@ -249,9 +247,9 @@
* @param context the execution context
* @throws IllegalArgumentException if the context is null
*/
- public QueryBuilder( ExecutionContext context ) {
+ public QueryBuilder( TypeSystem context ) {
CheckArg.isNotNull(context, "context");
- this.context = context;
+ this.typeSystem = context;
}
/**
@@ -312,38 +310,6 @@
}
/**
- * Convenience method that creates a {@link Name} object given the supplied string. Leading and trailing whitespace are
- * trimmed.
- *
- * @param name the name; may not be null
- * @return the name; never null
- * @throws IllegalArgumentException if the supplied name is not a valid {@link Name} object
- */
- protected Name name( String name ) {
- try {
- return context.getValueFactories().getNameFactory().create(name.trim());
- } catch (ValueFormatException e) {
- throw new IllegalArgumentException(GraphI18n.expectingValidName.text(name));
- }
- }
-
- /**
- * Convenience method that creates a {@link Path} object given the supplied string. Leading and trailing whitespace are
- * trimmed.
- *
- * @param path the path; may not be null
- * @return the path; never null
- * @throws IllegalArgumentException if the supplied string is not a valid {@link Path} object
- */
- protected Path path( String path ) {
- try {
- return context.getValueFactories().getPathFactory().create(path.trim());
- } catch (ValueFormatException e) {
- throw new IllegalArgumentException(GraphI18n.expectingValidPath.text(path));
- }
- }
-
- /**
* Create a {@link Column} given the supplied expression. The expression has the form "<code>[tableName.]columnName</code>",
* where "<code>tableName</code>" must be a valid table name or alias. If the table name/alias is not specified, then there is
* expected to be a single FROM clause with a single named selector.
@@ -358,17 +324,17 @@
parts[i] = parts[i].trim();
}
SelectorName name = null;
- Name propertyName = null;
+ String propertyName = null;
String columnName = null;
if (parts.length == 2) {
name = selector(parts[0]);
- propertyName = name(parts[1]);
+ propertyName = parts[1];
columnName = parts[1];
} else {
if (source instanceof Selector) {
Selector selector = (Selector)source;
name = selector.hasAlias() ? selector.getAlias() : selector.getName();
- propertyName = name(parts[0]);
+ propertyName = parts[0];
columnName = parts[0];
} else {
throw new IllegalArgumentException(GraphI18n.columnMustBeScoped.text(parts[0]));
@@ -1087,7 +1053,7 @@
*/
public ConstraintBuilder isSameNode( String table,
String asNodeAtPath ) {
- return setConstraint(new SameNode(selector(table), QueryBuilder.this.path(asNodeAtPath)));
+ return setConstraint(new SameNode(selector(table), asNodeAtPath));
}
/**
@@ -1100,7 +1066,7 @@
*/
public ConstraintBuilder isChild( String childTable,
String parentPath ) {
- return setConstraint(new ChildNode(selector(childTable), QueryBuilder.this.path(parentPath)));
+ return setConstraint(new ChildNode(selector(childTable), parentPath));
}
/**
@@ -1113,7 +1079,7 @@
*/
public ConstraintBuilder isBelowPath( String descendantTable,
String ancestorPath ) {
- return setConstraint(new DescendantNode(selector(descendantTable), QueryBuilder.this.path(ancestorPath)));
+ return setConstraint(new DescendantNode(selector(descendantTable), ancestorPath));
}
/**
@@ -1126,7 +1092,7 @@
*/
public ConstraintBuilder hasProperty( String table,
String propertyName ) {
- return setConstraint(new PropertyExistence(selector(table), name(propertyName)));
+ return setConstraint(new PropertyExistence(selector(table), propertyName));
}
/**
@@ -1156,7 +1122,7 @@
public ConstraintBuilder search( String table,
String propertyName,
String searchExpression ) {
- return setConstraint(new FullTextSearch(selector(table), name(propertyName), searchExpression));
+ return setConstraint(new FullTextSearch(selector(table), propertyName, searchExpression));
}
/**
@@ -1166,7 +1132,7 @@
*/
public ComparisonBuilder length( String table,
String property ) {
- return new ComparisonBuilder(this, new Length(new PropertyValue(selector(table), name(property))));
+ return new ComparisonBuilder(this, new Length(new PropertyValue(selector(table), property)));
}
/**
@@ -1176,7 +1142,7 @@
*/
public ComparisonBuilder propertyValue( String table,
String property ) {
- return new ComparisonBuilder(this, new PropertyValue(selector(table), name(property)));
+ return new ComparisonBuilder(this, new PropertyValue(selector(table), property));
}
/**
@@ -1304,7 +1270,7 @@
* @param type the property type; may not be null
* @return the constraint builder; never null
*/
- public abstract ReturnType as( PropertyType type );
+ public abstract ReturnType as( String type );
/**
* Define the right-hand side literal value cast as a {@link PropertyType#STRING}.
@@ -1312,7 +1278,7 @@
* @return the constraint builder; never null
*/
public ReturnType asString() {
- return as(PropertyType.STRING);
+ return as(typeSystem.getStringFactory().getTypeName());
}
/**
@@ -1321,7 +1287,7 @@
* @return the constraint builder; never null
*/
public ReturnType asBoolean() {
- return as(PropertyType.BOOLEAN);
+ return as(typeSystem.getBooleanFactory().getTypeName());
}
/**
@@ -1330,7 +1296,7 @@
* @return the constraint builder; never null
*/
public ReturnType asLong() {
- return as(PropertyType.LONG);
+ return as(typeSystem.getLongFactory().getTypeName());
}
/**
@@ -1339,80 +1305,26 @@
* @return the constraint builder; never null
*/
public ReturnType asDouble() {
- return as(PropertyType.DOUBLE);
+ return as(typeSystem.getDoubleFactory().getTypeName());
}
/**
- * Define the right-hand side literal value cast as a {@link PropertyType#DECIMAL}.
- *
- * @return the constraint builder; never null
- */
- public ReturnType asDecimal() {
- return as(PropertyType.DECIMAL);
- }
-
- /**
* Define the right-hand side literal value cast as a {@link PropertyType#DATE}.
*
* @return the constraint builder; never null
*/
public ReturnType asDate() {
- return as(PropertyType.DATE);
+ return as(typeSystem.getDateTimeFactory().getTypeName());
}
/**
- * Define the right-hand side literal value cast as a {@link PropertyType#NAME}.
- *
- * @return the constraint builder; never null
- */
- public ReturnType asName() {
- return as(PropertyType.NAME);
- }
-
- /**
* Define the right-hand side literal value cast as a {@link PropertyType#PATH}.
*
* @return the constraint builder; never null
*/
public ReturnType asPath() {
- return as(PropertyType.PATH);
+ return as(typeSystem.getPathFactory().getTypeName());
}
-
- /**
- * Define the right-hand side literal value cast as a {@link PropertyType#BINARY}.
- *
- * @return the constraint builder; never null
- */
- public ReturnType asBinary() {
- return as(PropertyType.BINARY);
- }
-
- /**
- * Define the right-hand side literal value cast as a {@link PropertyType#REFERENCE}.
- *
- * @return the constraint builder; never null
- */
- public ReturnType asReference() {
- return as(PropertyType.REFERENCE);
- }
-
- /**
- * Define the right-hand side literal value cast as a {@link PropertyType#URI}.
- *
- * @return the constraint builder; never null
- */
- public ReturnType asUri() {
- return as(PropertyType.URI);
- }
-
- /**
- * Define the right-hand side literal value cast as a {@link PropertyType#UUID}.
- *
- * @return the constraint builder; never null
- */
- public ReturnType asUuid() {
- return as(PropertyType.UUID);
- }
}
public class CastAsRightHandSide extends CastAs<ConstraintBuilder> {
@@ -1424,10 +1336,6 @@
this.rhs = rhs;
}
- private ValueFactories factories() {
- return QueryBuilder.this.context.getValueFactories();
- }
-
/**
* Define the right-hand side literal value cast as the specified type.
*
@@ -1435,8 +1343,8 @@
* @return the constraint builder; never null
*/
@Override
- public ConstraintBuilder as( PropertyType type ) {
- return rhs.comparisonBuilder.is(rhs.operator, factories().getValueFactory(type).create(value));
+ public ConstraintBuilder as( String type ) {
+ return rhs.comparisonBuilder.is(rhs.operator, typeSystem.getTypeFactory(type).create(value));
}
}
@@ -1449,10 +1357,6 @@
this.upperBoundary = upperBoundary;
}
- private ValueFactories factories() {
- return QueryBuilder.this.context.getValueFactories();
- }
-
/**
* Define the right-hand side literal value cast as the specified type.
*
@@ -1460,9 +1364,8 @@
* @return the constraint builder; never null
*/
@Override
- public ConstraintBuilder as( PropertyType type ) {
- return upperBoundary.comparisonBuilder.isBetween(upperBoundary.lowerBound, factories().getValueFactory(type)
- .create(value));
+ public ConstraintBuilder as( String type ) {
+ return upperBoundary.comparisonBuilder.isBetween(upperBoundary.lowerBound, typeSystem.getTypeFactory(type).create(value));
}
}
@@ -1475,10 +1378,6 @@
this.builder = builder;
}
- private ValueFactories factories() {
- return QueryBuilder.this.context.getValueFactories();
- }
-
/**
* Define the left-hand side literal value cast as the specified type.
*
@@ -1486,8 +1385,8 @@
* @return the builder to complete the constraint; never null
*/
@Override
- public AndBuilder<UpperBoundary> as( PropertyType type ) {
- Object literal = factories().getValueFactory(type).create(value);
+ public AndBuilder<UpperBoundary> as( String type ) {
+ Object literal = typeSystem.getTypeFactory(type).create(value);
return new AndBuilder<UpperBoundary>(new UpperBoundary(builder, new Literal(literal)));
}
}
Modified: trunk/dna-graph/src/main/java/org/jboss/dna/graph/query/QueryContext.java
===================================================================
--- trunk/dna-graph/src/main/java/org/jboss/dna/graph/query/QueryContext.java 2009-11-24 17:44:29 UTC (rev 1339)
+++ trunk/dna-graph/src/main/java/org/jboss/dna/graph/query/QueryContext.java 2009-11-24 17:46:37 UTC (rev 1340)
@@ -30,8 +30,8 @@
import org.jboss.dna.common.collection.Problems;
import org.jboss.dna.common.collection.SimpleProblems;
import org.jboss.dna.common.util.CheckArg;
-import org.jboss.dna.graph.ExecutionContext;
import org.jboss.dna.graph.query.model.BindVariableName;
+import org.jboss.dna.graph.query.model.TypeSystem;
import org.jboss.dna.graph.query.plan.PlanHints;
import org.jboss.dna.graph.query.validate.Schemata;
@@ -41,7 +41,7 @@
*/
@Immutable
public class QueryContext {
- private final ExecutionContext context;
+ private final TypeSystem typeSystem;
private final PlanHints hints;
private final Schemata schemata;
private final Problems problems;
@@ -50,26 +50,26 @@
/**
* Create a new context for query execution.
*
- * @param context the execution context
* @param schemata the schemata
+ * @param typeSystem the types system
* @param hints the hints, or null if there are no hints
* @param problems the problems container, or null if a new problems container should be created
* @param variables the mapping of variables and values, or null if there are no such variables
- * @throws IllegalArgumentException if the context or schmata are null
+ * @throws IllegalArgumentException if the values or schmata are null
*/
- public QueryContext( ExecutionContext context,
- Schemata schemata,
+ public QueryContext( Schemata schemata,
+ TypeSystem typeSystem,
PlanHints hints,
Problems problems,
Map<String, Object> variables ) {
- CheckArg.isNotNull(context, "context");
+ CheckArg.isNotNull(typeSystem, "typeSystem");
CheckArg.isNotNull(schemata, "schemata");
- this.context = context;
+ this.typeSystem = typeSystem;
this.hints = hints != null ? hints : new PlanHints();
this.schemata = schemata;
this.problems = problems != null ? problems : new SimpleProblems();
this.variables = variables != null ? Collections.<String, Object>unmodifiableMap(new HashMap<String, Object>(variables)) : Collections.<String, Object>emptyMap();
- assert this.context != null;
+ assert this.typeSystem != null;
assert this.hints != null;
assert this.schemata != null;
assert this.problems != null;
@@ -79,52 +79,52 @@
/**
* Create a new context for query execution.
*
- * @param context the execution context
* @param schemata the schemata
+ * @param typeSystem the types system
* @param hints the hints, or null if there are no hints
* @param problems the problems container, or null if a new problems container should be created
- * @throws IllegalArgumentException if the context or schmata are null
+ * @throws IllegalArgumentException if the values or schmata are null
*/
- public QueryContext( ExecutionContext context,
- Schemata schemata,
+ public QueryContext( Schemata schemata,
+ TypeSystem typeSystem,
PlanHints hints,
Problems problems ) {
- this(context, schemata, hints, problems, null);
+ this(schemata, typeSystem, hints, problems, null);
}
/**
* Create a new context for query execution.
*
- * @param context the execution context
* @param schemata the schemata
+ * @param typeSystem the types system
* @param hints the hints, or null if there are no hints
* @throws IllegalArgumentException if the context or schmata are null
*/
- public QueryContext( ExecutionContext context,
- Schemata schemata,
+ public QueryContext( Schemata schemata,
+ TypeSystem typeSystem,
PlanHints hints ) {
- this(context, schemata, hints, null, null);
+ this(schemata, typeSystem, hints, null, null);
}
/**
* Create a new context for query execution.
*
- * @param context the execution context
* @param schemata the schemata
- * @throws IllegalArgumentException if the context or schmata are null
+ * @param typeSystem the types system
+ * @throws IllegalArgumentException if the values or schmata are null
*/
- public QueryContext( ExecutionContext context,
- Schemata schemata ) {
- this(context, schemata, null, null, null);
+ public QueryContext( Schemata schemata,
+ TypeSystem typeSystem ) {
+ this(schemata, typeSystem, null, null, null);
}
/**
- * Get the execution context available to this query context.
+ * Get the interface for working with literal values and types.
*
- * @return the execution context; never null
+ * @return the type system; never null
*/
- public final ExecutionContext getExecutionContext() {
- return context;
+ public TypeSystem getTypeSystem() {
+ return typeSystem;
}
/**
@@ -174,7 +174,7 @@
if (obj == this) return true;
if (obj instanceof QueryContext) {
QueryContext that = (QueryContext)obj;
- if (!this.context.equals(that.getExecutionContext())) return false;
+ if (!this.typeSystem.equals(that.getTypeSystem())) return false;
if (!this.schemata.equals(that.getSchemata())) return false;
if (!this.variables.equals(that.getVariables())) return false;
return true;
@@ -183,15 +183,15 @@
}
/**
- * Obtain a copy of this context, except that the copy uses the supplied execution context.
+ * Obtain a copy of this context, except that the copy uses the supplied type system.
*
- * @param context the execution context that should be used in the new query context
+ * @param typeSystem the type system that should be used in the new query context
* @return the new context; never null
* @throws IllegalArgumentException if the execution context reference is null
*/
- public QueryContext with( ExecutionContext context ) {
- CheckArg.isNotNull(context, "context");
- return new QueryContext(context, schemata, hints, problems, variables);
+ public QueryContext with( TypeSystem typeSystem ) {
+ CheckArg.isNotNull(typeSystem, "typeSystem");
+ return new QueryContext(schemata, typeSystem, hints, problems, variables);
}
/**
@@ -203,7 +203,7 @@
*/
public QueryContext with( Schemata schemata ) {
CheckArg.isNotNull(schemata, "schemata");
- return new QueryContext(context, schemata, hints, problems, variables);
+ return new QueryContext(schemata, typeSystem, hints, problems, variables);
}
/**
@@ -215,7 +215,7 @@
*/
public QueryContext with( PlanHints hints ) {
CheckArg.isNotNull(hints, "hints");
- return new QueryContext(context, schemata, hints, problems, variables);
+ return new QueryContext(schemata, typeSystem, hints, problems, variables);
}
/**
@@ -225,7 +225,7 @@
* @return the new context; never null
*/
public QueryContext with( Problems problems ) {
- return new QueryContext(context, schemata, hints, problems, variables);
+ return new QueryContext(schemata, typeSystem, hints, problems, variables);
}
/**
@@ -235,7 +235,7 @@
* @return the new context; never null
*/
public QueryContext with( Map<String, Object> variables ) {
- return new QueryContext(context, schemata, hints, problems, variables);
+ return new QueryContext(schemata, typeSystem, hints, problems, variables);
}
}
Modified: trunk/dna-graph/src/main/java/org/jboss/dna/graph/query/QueryResults.java
===================================================================
--- trunk/dna-graph/src/main/java/org/jboss/dna/graph/query/QueryResults.java 2009-11-24 17:44:29 UTC (rev 1339)
+++ trunk/dna-graph/src/main/java/org/jboss/dna/graph/query/QueryResults.java 2009-11-24 17:46:37 UTC (rev 1340)
@@ -30,11 +30,10 @@
import net.jcip.annotations.Immutable;
import org.jboss.dna.common.collection.Problems;
import org.jboss.dna.common.util.CheckArg;
-import org.jboss.dna.graph.ExecutionContext;
import org.jboss.dna.graph.Location;
-import org.jboss.dna.graph.property.Name;
import org.jboss.dna.graph.query.model.Column;
import org.jboss.dna.graph.query.model.QueryCommand;
+import org.jboss.dna.graph.query.model.TypeSystem;
/**
* The resulting output of a query.
@@ -43,11 +42,11 @@
public interface QueryResults {
/**
- * Get the execution context in which the query was evaluated.
+ * Get the type system used to evaluate the query.
*
- * @return the execution context; never null
+ * @return the type system; never null
*/
- public ExecutionContext getContext();
+ public TypeSystem getTypeSystem();
/**
* Get the original query command.
@@ -280,7 +279,7 @@
* @return the property name; never null
* @throws IndexOutOfBoundsException if the column index is invalid
*/
- public Name getPropertyNameForColumn( int columnIndex );
+ public String getPropertyNameForColumn( int columnIndex );
/**
* Get the name of the property that corresponds to the supplied column in each tuple.
@@ -289,7 +288,7 @@
* @return the property name; never null
* @throws NoSuchElementException if the column name is invalid or doesn't match an existing column
*/
- public Name getPropertyNameForColumn( String columnName );
+ public String getPropertyNameForColumn( String columnName );
/**
* Get the index of the column given the column name.
@@ -310,7 +309,7 @@
* @throws NoSuchElementException if the selector name or the property name are invalid
*/
public int getColumnIndexForProperty( String selectorName,
- Name propertyName );
+ String propertyName );
/**
* Get the index of the tuple value containing the full-text search score for the node taken from the named selector.
Modified: trunk/dna-graph/src/main/java/org/jboss/dna/graph/query/model/And.java
===================================================================
--- trunk/dna-graph/src/main/java/org/jboss/dna/graph/query/model/And.java 2009-11-24 17:44:29 UTC (rev 1339)
+++ trunk/dna-graph/src/main/java/org/jboss/dna/graph/query/model/And.java 2009-11-24 17:46:37 UTC (rev 1340)
@@ -47,14 +47,18 @@
}
/**
- * @return left
+ * Get the constraint that is on the left-hand-side of the AND operation.
+ *
+ * @return the left-hand-side constraint
*/
public final Constraint getLeft() {
return left;
}
/**
- * @return right
+ * Get the constraint that is on the right-hand-side of the AND operation.
+ *
+ * @return the right-hand-side constraint
*/
public final Constraint getRight() {
return right;
Modified: trunk/dna-graph/src/main/java/org/jboss/dna/graph/query/model/Between.java
===================================================================
--- trunk/dna-graph/src/main/java/org/jboss/dna/graph/query/model/Between.java 2009-11-24 17:44:29 UTC (rev 1339)
+++ trunk/dna-graph/src/main/java/org/jboss/dna/graph/query/model/Between.java 2009-11-24 17:46:37 UTC (rev 1340)
@@ -91,14 +91,18 @@
}
/**
- * @return lowerBound
+ * Get the lower bound operand.
+ *
+ * @return the lower bound; never null
*/
public StaticOperand getLowerBound() {
return lowerBound;
}
/**
- * @return upperBound
+ * Get the upper bound operand.
+ *
+ * @return the upper bound; never null
*/
public StaticOperand getUpperBound() {
return upperBound;
Modified: trunk/dna-graph/src/main/java/org/jboss/dna/graph/query/model/ChildNode.java
===================================================================
--- trunk/dna-graph/src/main/java/org/jboss/dna/graph/query/model/ChildNode.java 2009-11-24 17:44:29 UTC (rev 1339)
+++ trunk/dna-graph/src/main/java/org/jboss/dna/graph/query/model/ChildNode.java 2009-11-24 17:46:37 UTC (rev 1340)
@@ -26,7 +26,6 @@
import net.jcip.annotations.Immutable;
import org.jboss.dna.common.util.CheckArg;
import org.jboss.dna.common.util.HashCode;
-import org.jboss.dna.graph.property.Path;
/**
* A constraint requiring that the selected node is a child of the node reachable by the supplied absolute path
@@ -34,7 +33,7 @@
@Immutable
public class ChildNode extends Constraint {
private final SelectorName selectorName;
- private final Path parentPath;
+ private final String parentPath;
private final int hc;
/**
@@ -45,7 +44,7 @@
* @param parentPath the absolute path to the parent
*/
public ChildNode( SelectorName selectorName,
- Path parentPath ) {
+ String parentPath ) {
CheckArg.isNotNull(selectorName, "selectorName");
CheckArg.isNotNull(parentPath, "parentPath");
this.selectorName = selectorName;
@@ -54,16 +53,20 @@
}
/**
- * @return selectorName
+ * Get the name of the selector representing the child
+ *
+ * @return the selector name; never null
*/
public final SelectorName getSelectorName() {
return selectorName;
}
/**
- * @return parentPath
+ * Get the path of the parent.
+ *
+ * @return the parent path; never null
*/
- public final Path getParentPath() {
+ public final String getParentPath() {
return parentPath;
}
Modified: trunk/dna-graph/src/main/java/org/jboss/dna/graph/query/model/ChildNodeJoinCondition.java
===================================================================
--- trunk/dna-graph/src/main/java/org/jboss/dna/graph/query/model/ChildNodeJoinCondition.java 2009-11-24 17:44:29 UTC (rev 1339)
+++ trunk/dna-graph/src/main/java/org/jboss/dna/graph/query/model/ChildNodeJoinCondition.java 2009-11-24 17:46:37 UTC (rev 1340)
@@ -53,14 +53,18 @@
}
/**
- * @return childSelectorName
+ * Get the name of the selector that represents the child.
+ *
+ * @return the selector name of the child node; never null
*/
public final SelectorName getChildSelectorName() {
return childSelectorName;
}
/**
- * @return parentSelectorName
+ * Get the name of the selector that represents the parent.
+ *
+ * @return the selector name of the parent node; never null
*/
public final SelectorName getParentSelectorName() {
return parentSelectorName;
Modified: trunk/dna-graph/src/main/java/org/jboss/dna/graph/query/model/Column.java
===================================================================
--- trunk/dna-graph/src/main/java/org/jboss/dna/graph/query/model/Column.java 2009-11-24 17:44:29 UTC (rev 1339)
+++ trunk/dna-graph/src/main/java/org/jboss/dna/graph/query/model/Column.java 2009-11-24 17:46:37 UTC (rev 1340)
@@ -26,7 +26,6 @@
import net.jcip.annotations.Immutable;
import org.jboss.dna.common.util.CheckArg;
import org.jboss.dna.common.util.ObjectUtil;
-import org.jboss.dna.graph.property.Name;
/**
*
@@ -35,7 +34,7 @@
public class Column implements LanguageObject {
private final SelectorName selectorName;
- private final Name propertyName;
+ private final String propertyName;
private final String columnName;
/**
@@ -58,7 +57,7 @@
* @param columnName the name of the column
*/
public Column( SelectorName selectorName,
- Name propertyName,
+ String propertyName,
String columnName ) {
CheckArg.isNotNull(selectorName, "selectorName");
CheckArg.isNotNull(propertyName, "propertyName");
@@ -69,21 +68,27 @@
}
/**
- * @return selectorName
+ * Get the name of the selector for the node.
+ *
+ * @return the selector name; never null
*/
public final SelectorName getSelectorName() {
return selectorName;
}
/**
- * @return propertyName
+ * Get the name of the property that this column represents.
+ *
+ * @return the property name; or null if this represents all selectable columns on the {@link #getSelectorName() selector}
*/
- public final Name getPropertyName() {
+ public final String getPropertyName() {
return propertyName;
}
/**
- * @return columnName
+ * Get the name of the column.
+ *
+ * @return the column name; or null if this represents all selectable columsn on the {@link #getSelectorName() selector}
*/
public final String getColumnName() {
return columnName;
Modified: trunk/dna-graph/src/main/java/org/jboss/dna/graph/query/model/Comparison.java
===================================================================
--- trunk/dna-graph/src/main/java/org/jboss/dna/graph/query/model/Comparison.java 2009-11-24 17:44:29 UTC (rev 1339)
+++ trunk/dna-graph/src/main/java/org/jboss/dna/graph/query/model/Comparison.java 2009-11-24 17:46:37 UTC (rev 1340)
@@ -51,21 +51,27 @@
}
/**
- * @return operand1
+ * Get the dynamic operand of this comparison.
+ *
+ * @return the dynamic operand; never null
*/
public final DynamicOperand getOperand1() {
return operand1;
}
/**
- * @return operand2
+ * Get the dynamic operand of this comparison.
+ *
+ * @return the dynamic operand; never null
*/
public final StaticOperand getOperand2() {
return operand2;
}
/**
- * @return operator
+ * Get the operator for this comparison
+ *
+ * @return the operator; never null
*/
public final Operator getOperator() {
return operator;
Modified: trunk/dna-graph/src/main/java/org/jboss/dna/graph/query/model/DescendantNode.java
===================================================================
--- trunk/dna-graph/src/main/java/org/jboss/dna/graph/query/model/DescendantNode.java 2009-11-24 17:44:29 UTC (rev 1339)
+++ trunk/dna-graph/src/main/java/org/jboss/dna/graph/query/model/DescendantNode.java 2009-11-24 17:46:37 UTC (rev 1340)
@@ -25,7 +25,6 @@
import net.jcip.annotations.Immutable;
import org.jboss.dna.common.util.CheckArg;
-import org.jboss.dna.graph.property.Path;
/**
* A constraint requiring that the selected node is a descendant of the node reachable by the supplied absolute path
@@ -33,7 +32,7 @@
@Immutable
public class DescendantNode extends Constraint {
private final SelectorName selectorName;
- private final Path ancestorPath;
+ private final String ancestorPath;
/**
* Create a constraint requiring that the node identified by the selector is a descendant of the node reachable by the
@@ -43,7 +42,7 @@
* @param ancestorPath the absolute path to the ancestor
*/
public DescendantNode( SelectorName selectorName,
- Path ancestorPath ) {
+ String ancestorPath ) {
CheckArg.isNotNull(selectorName, "selectorName");
CheckArg.isNotNull(ancestorPath, "ancestorPath");
this.selectorName = selectorName;
@@ -51,16 +50,20 @@
}
/**
- * @return selectorName
+ * Get the name of the selector for the node.
+ *
+ * @return the selector name; never null
*/
public final SelectorName getSelectorName() {
return selectorName;
}
/**
- * @return ancestorPath
+ * Get the path of the node that is to be the ancestor of the target node.
+ *
+ * @return the path of the ancestor node; never null
*/
- public final Path getAncestorPath() {
+ public final String getAncestorPath() {
return ancestorPath;
}
Modified: trunk/dna-graph/src/main/java/org/jboss/dna/graph/query/model/DescendantNodeJoinCondition.java
===================================================================
--- trunk/dna-graph/src/main/java/org/jboss/dna/graph/query/model/DescendantNodeJoinCondition.java 2009-11-24 17:44:29 UTC (rev 1339)
+++ trunk/dna-graph/src/main/java/org/jboss/dna/graph/query/model/DescendantNodeJoinCondition.java 2009-11-24 17:46:37 UTC (rev 1340)
@@ -53,14 +53,18 @@
}
/**
- * @return descendantSelectorName
+ * Get the name of the selector for the descedant node.
+ *
+ * @return the selector name of the descendant node; never null
*/
public final SelectorName getDescendantSelectorName() {
return descendantSelectorName;
}
/**
- * @return ancestorSelectorName
+ * Get the name of the selector for the ancestor node.
+ *
+ * @return the selector name of the ancestor node; never null
*/
public final SelectorName getAncestorSelectorName() {
return ancestorSelectorName;
Modified: trunk/dna-graph/src/main/java/org/jboss/dna/graph/query/model/EquiJoinCondition.java
===================================================================
--- trunk/dna-graph/src/main/java/org/jboss/dna/graph/query/model/EquiJoinCondition.java 2009-11-24 17:44:29 UTC (rev 1339)
+++ trunk/dna-graph/src/main/java/org/jboss/dna/graph/query/model/EquiJoinCondition.java 2009-11-24 17:46:37 UTC (rev 1340)
@@ -26,7 +26,6 @@
import net.jcip.annotations.Immutable;
import org.jboss.dna.common.util.CheckArg;
import org.jboss.dna.common.util.HashCode;
-import org.jboss.dna.graph.property.Name;
/**
* A join condition that tests whether a property on a node is equal to a property on another node. A node-tuple satisfies the
@@ -40,15 +39,23 @@
@Immutable
public class EquiJoinCondition extends JoinCondition {
private final SelectorName selector1Name;
- private final Name property1Name;
+ private final String property1Name;
private final SelectorName selector2Name;
- private final Name property2Name;
+ private final String property2Name;
private final int hc;
+ /**
+ * Create an equi-join condition, given the names of the selector and property for the left- and right-hand-side of the join.
+ *
+ * @param selector1Name the selector name appearing on the left-side of the join; never null
+ * @param property1Name the property name for the left-side of the join; never null
+ * @param selector2Name the selector name appearing on the right-side of the join; never null
+ * @param property2Name the property name for the right-side of the join; never null
+ */
public EquiJoinCondition( SelectorName selector1Name,
- Name property1Name,
+ String property1Name,
SelectorName selector2Name,
- Name property2Name ) {
+ String property2Name ) {
CheckArg.isNotNull(selector1Name, "selector1Name");
CheckArg.isNotNull(property1Name, "property1Name");
CheckArg.isNotNull(selector2Name, "selector2Name");
@@ -60,36 +67,50 @@
this.hc = HashCode.compute(this.selector1Name, this.property1Name, this.selector2Name, this.property2Name);
}
+ /**
+ * Create an equi-join condition, given the columns.
+ *
+ * @param column1 the column for the left-side of the join; never null
+ * @param column2 the column for the right-side of the join; never null
+ */
public EquiJoinCondition( Column column1,
Column column2 ) {
this(column1.getSelectorName(), column1.getPropertyName(), column2.getSelectorName(), column2.getPropertyName());
}
/**
- * @return selector1Name
+ * Get the name of the selector that appears on the left-side of the join.
+ *
+ * @return the selector name appearing on the left-side of the join; never null
*/
public final SelectorName getSelector1Name() {
return selector1Name;
}
/**
- * @return property1Name
+ * Get the name of the property that appears on the left-side of the join.
+ *
+ * @return the property name for the left-side of the join; never null
*/
- public final Name getProperty1Name() {
+ public final String getProperty1Name() {
return property1Name;
}
/**
- * @return selector2Name
+ * Get the name of the selector that appears on the right-side of the join.
+ *
+ * @return the selector name appearing on the right-side of the join; never null
*/
public final SelectorName getSelector2Name() {
return selector2Name;
}
/**
- * @return property2Name
+ * Get the name of the property that appears on the left-side of the join.
+ *
+ * @return the property name for the left-side of the join; never null
*/
- public final Name getProperty2Name() {
+ public final String getProperty2Name() {
return property2Name;
}
Modified: trunk/dna-graph/src/main/java/org/jboss/dna/graph/query/model/FullTextSearch.java
===================================================================
--- trunk/dna-graph/src/main/java/org/jboss/dna/graph/query/model/FullTextSearch.java 2009-11-24 17:44:29 UTC (rev 1339)
+++ trunk/dna-graph/src/main/java/org/jboss/dna/graph/query/model/FullTextSearch.java 2009-11-24 17:46:37 UTC (rev 1340)
@@ -30,7 +30,6 @@
import org.jboss.dna.common.util.CheckArg;
import org.jboss.dna.common.util.HashCode;
import org.jboss.dna.common.util.ObjectUtil;
-import org.jboss.dna.graph.property.Name;
import org.jboss.dna.graph.query.parse.FullTextSearchParser;
/**
@@ -40,7 +39,7 @@
@Immutable
public class FullTextSearch extends Constraint {
private final SelectorName selectorName;
- private final Name propertyName;
+ private final String propertyName;
private final String fullTextSearchExpression;
private Term term;
private final int hc;
@@ -54,7 +53,7 @@
* @param term the term representation, if it is known; may be null
*/
public FullTextSearch( SelectorName selectorName,
- Name propertyName,
+ String propertyName,
String fullTextSearchExpression,
Term term ) {
CheckArg.isNotNull(selectorName, "selectorName");
@@ -73,7 +72,7 @@
* @param fullTextSearchExpression the search expression
*/
public FullTextSearch( SelectorName selectorName,
- Name propertyName,
+ String propertyName,
String fullTextSearchExpression ) {
CheckArg.isNotNull(selectorName, "selectorName");
CheckArg.isNotEmpty(fullTextSearchExpression, "fullTextSearchExpression");
@@ -101,21 +100,27 @@
}
/**
- * @return selectorName
+ * Get the name of the selector that is to be searched
+ *
+ * @return the selector name; never null
*/
public final SelectorName getSelectorName() {
return selectorName;
}
/**
- * @return propertyName
+ * Get the name of the property that is to be searched.
+ *
+ * @return the property name; never null
*/
- public final Name getPropertyName() {
+ public final String getPropertyName() {
return propertyName;
}
/**
- * @return fullTextSearchExpression
+ * Get the full-text search expression, as a string.
+ *
+ * @return the search expression; never null
*/
public final String getFullTextSearchExpression() {
return fullTextSearchExpression;
Modified: trunk/dna-graph/src/main/java/org/jboss/dna/graph/query/model/Join.java
===================================================================
--- trunk/dna-graph/src/main/java/org/jboss/dna/graph/query/model/Join.java 2009-11-24 17:44:29 UTC (rev 1339)
+++ trunk/dna-graph/src/main/java/org/jboss/dna/graph/query/model/Join.java 2009-11-24 17:46:37 UTC (rev 1340)
@@ -64,28 +64,36 @@
}
/**
- * @return left
+ * Get the source that represents the left-hand-side of the join.
+ *
+ * @return the left-side source; never null
*/
public final Source getLeft() {
return left;
}
/**
- * @return right
+ * Get the source that represents the right-hand-side of the join.
+ *
+ * @return the right-side source; never null
*/
public final Source getRight() {
return right;
}
/**
- * @return type
+ * Get the type of join.
+ *
+ * @return the join type; never null
*/
public final JoinType getType() {
return type;
}
/**
- * @return joinCondition
+ * Get the join condition
+ *
+ * @return the join condition; never null
*/
public final JoinCondition getJoinCondition() {
return joinCondition;
Modified: trunk/dna-graph/src/main/java/org/jboss/dna/graph/query/model/JoinType.java
===================================================================
--- trunk/dna-graph/src/main/java/org/jboss/dna/graph/query/model/JoinType.java 2009-11-24 17:44:29 UTC (rev 1339)
+++ trunk/dna-graph/src/main/java/org/jboss/dna/graph/query/model/JoinType.java 2009-11-24 17:46:37 UTC (rev 1340)
@@ -27,7 +27,6 @@
import java.util.HashMap;
import java.util.Map;
import org.jboss.dna.common.util.CheckArg;
-import org.jboss.dna.graph.ExecutionContext;
public enum JoinType implements Readable {
INNER("INNER JOIN"),
@@ -92,9 +91,9 @@
/**
* {@inheritDoc}
*
- * @see org.jboss.dna.graph.query.model.Readable#getString(org.jboss.dna.graph.ExecutionContext)
+ * @see org.jboss.dna.graph.query.model.Readable#getString()
*/
- public String getString( ExecutionContext context ) {
+ public String getString() {
return getSymbol();
}
}
Modified: trunk/dna-graph/src/main/java/org/jboss/dna/graph/query/model/Length.java
===================================================================
--- trunk/dna-graph/src/main/java/org/jboss/dna/graph/query/model/Length.java 2009-11-24 17:44:29 UTC (rev 1339)
+++ trunk/dna-graph/src/main/java/org/jboss/dna/graph/query/model/Length.java 2009-11-24 17:46:37 UTC (rev 1340)
@@ -54,7 +54,9 @@
}
/**
- * @return propertyValue
+ * Get the property value whose length is being constrained.
+ *
+ * @return the property value being constrained; never null
*/
public final PropertyValue getPropertyValue() {
return propertyValue;
Modified: trunk/dna-graph/src/main/java/org/jboss/dna/graph/query/model/Limit.java
===================================================================
--- trunk/dna-graph/src/main/java/org/jboss/dna/graph/query/model/Limit.java 2009-11-24 17:44:29 UTC (rev 1339)
+++ trunk/dna-graph/src/main/java/org/jboss/dna/graph/query/model/Limit.java 2009-11-24 17:46:37 UTC (rev 1340)
@@ -37,12 +37,25 @@
private final int offset;
private final int rowLimit;
+ /**
+ * Create a limit on the number of rows.
+ *
+ * @param rowLimit the maximum number of rows
+ * @throws IllegalArgumentException if the row limit is not positive
+ */
public Limit( int rowLimit ) {
CheckArg.isPositive(rowLimit, "rowLimit");
this.rowLimit = rowLimit;
this.offset = 0;
}
+ /**
+ * Create a limit on the number of rows and the number of initial rows to skip.
+ *
+ * @param rowLimit the maximum number of rows
+ * @param offset the number of rows to skip before beginning the results
+ * @throws IllegalArgumentException if the row limit is not positive, or if the offset is negative
+ */
public Limit( int rowLimit,
int offset ) {
CheckArg.isPositive(rowLimit, "rowLimit");
@@ -52,7 +65,9 @@
}
/**
- * @return offset
+ * Get the number of rows skipped before the results begin.
+ *
+ * @return the offset; always 0 or a positive number
*/
public final int getOffset() {
return offset;
Modified: trunk/dna-graph/src/main/java/org/jboss/dna/graph/query/model/LowerCase.java
===================================================================
--- trunk/dna-graph/src/main/java/org/jboss/dna/graph/query/model/LowerCase.java 2009-11-24 17:44:29 UTC (rev 1339)
+++ trunk/dna-graph/src/main/java/org/jboss/dna/graph/query/model/LowerCase.java 2009-11-24 17:46:37 UTC (rev 1340)
@@ -45,7 +45,9 @@
}
/**
- * @return operand
+ * Get the dynamic operand that is to be lower-cased.
+ *
+ * @return the dynamic operand; never null
*/
public final DynamicOperand getOperand() {
return operand;
Modified: trunk/dna-graph/src/main/java/org/jboss/dna/graph/query/model/Operator.java
===================================================================
--- trunk/dna-graph/src/main/java/org/jboss/dna/graph/query/model/Operator.java 2009-11-24 17:44:29 UTC (rev 1339)
+++ trunk/dna-graph/src/main/java/org/jboss/dna/graph/query/model/Operator.java 2009-11-24 17:46:37 UTC (rev 1340)
@@ -57,7 +57,9 @@
}
/**
- * @return symbol
+ * Get the symbol for this operator
+ *
+ * @return the symbolic representation; never null
*/
public String getSymbol() {
return symbol;
Modified: trunk/dna-graph/src/main/java/org/jboss/dna/graph/query/model/Order.java
===================================================================
--- trunk/dna-graph/src/main/java/org/jboss/dna/graph/query/model/Order.java 2009-11-24 17:44:29 UTC (rev 1339)
+++ trunk/dna-graph/src/main/java/org/jboss/dna/graph/query/model/Order.java 2009-11-24 17:46:37 UTC (rev 1340)
@@ -24,7 +24,6 @@
package org.jboss.dna.graph.query.model;
import org.jboss.dna.common.util.CheckArg;
-import org.jboss.dna.graph.ExecutionContext;
/**
*
@@ -40,7 +39,9 @@
}
/**
- * @return symbol
+ * Get the symbolic representation of the order
+ *
+ * @return the symbolic representation; never null
*/
public String getSymbol() {
return symbol;
@@ -73,9 +74,9 @@
/**
* {@inheritDoc}
*
- * @see org.jboss.dna.graph.query.model.Readable#getString(org.jboss.dna.graph.ExecutionContext)
+ * @see org.jboss.dna.graph.query.model.Readable#getString()
*/
- public String getString( ExecutionContext context ) {
+ public String getString() {
return getSymbol();
}
}
Modified: trunk/dna-graph/src/main/java/org/jboss/dna/graph/query/model/PropertyExistence.java
===================================================================
--- trunk/dna-graph/src/main/java/org/jboss/dna/graph/query/model/PropertyExistence.java 2009-11-24 17:44:29 UTC (rev 1339)
+++ trunk/dna-graph/src/main/java/org/jboss/dna/graph/query/model/PropertyExistence.java 2009-11-24 17:46:37 UTC (rev 1340)
@@ -26,7 +26,6 @@
import net.jcip.annotations.Immutable;
import org.jboss.dna.common.util.CheckArg;
import org.jboss.dna.common.util.HashCode;
-import org.jboss.dna.graph.property.Name;
/**
* A constraint that evaluates to true only when a named property exists on a node.
@@ -34,7 +33,7 @@
@Immutable
public class PropertyExistence extends Constraint {
private final SelectorName selectorName;
- private final Name propertyName;
+ private final String propertyName;
private final int hc;
/**
@@ -44,7 +43,7 @@
* @param propertyName the name of the property that must exist
*/
public PropertyExistence( SelectorName selectorName,
- Name propertyName ) {
+ String propertyName ) {
CheckArg.isNotNull(selectorName, "selectorName");
CheckArg.isNotNull(propertyName, "propertyName");
this.selectorName = selectorName;
@@ -66,7 +65,7 @@
*
* @return the property name; never null
*/
- public final Name getPropertyName() {
+ public final String getPropertyName() {
return propertyName;
}
Modified: trunk/dna-graph/src/main/java/org/jboss/dna/graph/query/model/PropertyValue.java
===================================================================
--- trunk/dna-graph/src/main/java/org/jboss/dna/graph/query/model/PropertyValue.java 2009-11-24 17:44:29 UTC (rev 1339)
+++ trunk/dna-graph/src/main/java/org/jboss/dna/graph/query/model/PropertyValue.java 2009-11-24 17:46:37 UTC (rev 1340)
@@ -26,7 +26,6 @@
import net.jcip.annotations.Immutable;
import org.jboss.dna.common.util.CheckArg;
import org.jboss.dna.common.util.HashCode;
-import org.jboss.dna.graph.property.Name;
/**
* A dynamic operand that evaluates to the value(s) of a property on a selector, used in a {@link Comparison} constraint.
@@ -34,7 +33,7 @@
@Immutable
public class PropertyValue extends DynamicOperand {
private final SelectorName selectorName;
- private final Name propertyName;
+ private final String propertyName;
private final int hc;
/**
@@ -45,7 +44,7 @@
* @throws IllegalArgumentException if the selector name or property name are null
*/
public PropertyValue( SelectorName selectorName,
- Name propertyName ) {
+ String propertyName ) {
CheckArg.isNotNull(selectorName, "selectorName");
CheckArg.isNotNull(propertyName, "propertyName");
this.selectorName = selectorName;
@@ -68,7 +67,7 @@
*
* @return the property name; never null
*/
- public final Name getPropertyName() {
+ public final String getPropertyName() {
return propertyName;
}
Modified: trunk/dna-graph/src/main/java/org/jboss/dna/graph/query/model/Query.java
===================================================================
--- trunk/dna-graph/src/main/java/org/jboss/dna/graph/query/model/Query.java 2009-11-24 17:44:29 UTC (rev 1339)
+++ trunk/dna-graph/src/main/java/org/jboss/dna/graph/query/model/Query.java 2009-11-24 17:46:37 UTC (rev 1340)
@@ -126,34 +126,81 @@
return distinct;
}
+ /**
+ * Create a copy of this query, but one in which there are no duplicate rows in the results.
+ *
+ * @return the copy of the query with no duplicate result rows; never null
+ */
public Query distinct() {
return new Query(source, constraint, getOrderings(), columns, getLimits(), true);
}
+ /**
+ * Create a copy of this query, but one in which there may be duplicate rows in the results.
+ *
+ * @return the copy of the query with potentially duplicate result rows; never null
+ */
public Query noDistinct() {
return new Query(source, constraint, getOrderings(), columns, getLimits(), false);
}
+ /**
+ * Create a copy of this query, but one that uses the supplied constraint.
+ *
+ * @param constraint the constraint that should be used; never null
+ * @return the copy of the query that uses the supplied constraint; never null
+ */
public Query constrainedBy( Constraint constraint ) {
return new Query(source, constraint, getOrderings(), columns, getLimits(), distinct);
}
+ /**
+ * Create a copy of this query, but one whose results should be ordered by the supplied orderings.
+ *
+ * @param orderings the result ordering specification that should be used; never null
+ * @return the copy of the query that uses the supplied ordering; never null
+ */
public Query orderedBy( List<Ordering> orderings ) {
return new Query(source, constraint, orderings, columns, getLimits(), distinct);
}
+ /**
+ * Create a copy of this query, but one that uses the supplied limit on the number of result rows.
+ *
+ * @param rowLimit the limit that should be used; must be a positive number
+ * @return the copy of the query that uses the supplied limit; never null
+ */
public Query withLimit( int rowLimit ) {
return new Query(source, constraint, getOrderings(), columns, getLimits().withRowLimit(rowLimit), distinct);
}
+ /**
+ * Create a copy of this query, but one that uses the supplied offset.
+ *
+ * @param offset the limit that should be used; may not be negative
+ * @return the copy of the query that uses the supplied offset; never null
+ */
public Query withOffset( int offset ) {
return new Query(source, constraint, getOrderings(), columns, getLimits().withOffset(offset), distinct);
}
+ /**
+ * Create a copy of this query, but that returns results with the supplied columns.
+ *
+ * @param columns the columns of the results; may not be null
+ * @return the copy of the query returning the supplied result columns; never null
+ */
public Query returning( List<Column> columns ) {
return new Query(source, constraint, getOrderings(), columns, getLimits(), distinct);
}
+ /**
+ * Create a copy of this query, but that returns results that are ordered by the {@link #getOrderings() orderings} of this
+ * column as well as those supplied.
+ *
+ * @param orderings the additional orderings of the result rows; may no be null
+ * @return the copy of the query returning the supplied result columns; never null
+ */
public Query adding( Ordering... orderings ) {
List<Ordering> newOrderings = null;
if (this.getOrderings() != null) {
@@ -167,6 +214,13 @@
return new Query(source, constraint, newOrderings, columns, getLimits(), distinct);
}
+ /**
+ * Create a copy of this query, but that returns results that include the columns specified by this query as well as the
+ * supplied columns.
+ *
+ * @param columns the additional columns that should be included in the the results; may not be null
+ * @return the copy of the query returning the supplied result columns; never null
+ */
public Query adding( Column... columns ) {
List<Column> newColumns = null;
if (this.columns != null) {
Modified: trunk/dna-graph/src/main/java/org/jboss/dna/graph/query/model/Readable.java
===================================================================
--- trunk/dna-graph/src/main/java/org/jboss/dna/graph/query/model/Readable.java 2009-11-24 17:44:29 UTC (rev 1339)
+++ trunk/dna-graph/src/main/java/org/jboss/dna/graph/query/model/Readable.java 2009-11-24 17:46:37 UTC (rev 1340)
@@ -23,7 +23,6 @@
*/
package org.jboss.dna.graph.query.model;
-import org.jboss.dna.graph.ExecutionContext;
/**
*
@@ -32,9 +31,8 @@
/**
* Get the string representation of this query object.
*
- * @param context the execution context in which the conversion is to take place
* @return the string representation; never null
*/
- String getString( ExecutionContext context );
+ String getString();
}
Modified: trunk/dna-graph/src/main/java/org/jboss/dna/graph/query/model/SameNode.java
===================================================================
--- trunk/dna-graph/src/main/java/org/jboss/dna/graph/query/model/SameNode.java 2009-11-24 17:44:29 UTC (rev 1339)
+++ trunk/dna-graph/src/main/java/org/jboss/dna/graph/query/model/SameNode.java 2009-11-24 17:46:37 UTC (rev 1340)
@@ -26,7 +26,6 @@
import net.jcip.annotations.Immutable;
import org.jboss.dna.common.util.CheckArg;
import org.jboss.dna.common.util.HashCode;
-import org.jboss.dna.graph.property.Path;
/**
* A constraint requiring that the selected node is reachable by the supplied absolute path
@@ -34,7 +33,7 @@
@Immutable
public class SameNode extends Constraint {
private final SelectorName selectorName;
- private final Path path;
+ private final String path;
private final int hc;
/**
@@ -45,7 +44,7 @@
* @throws IllegalArgumentException if the selector name or path are null
*/
public SameNode( SelectorName selectorName,
- Path path ) {
+ String path ) {
CheckArg.isNotNull(selectorName, "selectorName");
CheckArg.isNotNull(path, "path");
this.selectorName = selectorName;
@@ -67,7 +66,7 @@
*
* @return the absolute path; never null
*/
- public final Path getPath() {
+ public final String getPath() {
return path;
}
Modified: trunk/dna-graph/src/main/java/org/jboss/dna/graph/query/model/SameNodeJoinCondition.java
===================================================================
--- trunk/dna-graph/src/main/java/org/jboss/dna/graph/query/model/SameNodeJoinCondition.java 2009-11-24 17:44:29 UTC (rev 1339)
+++ trunk/dna-graph/src/main/java/org/jboss/dna/graph/query/model/SameNodeJoinCondition.java 2009-11-24 17:46:37 UTC (rev 1340)
@@ -27,7 +27,6 @@
import org.jboss.dna.common.util.CheckArg;
import org.jboss.dna.common.util.HashCode;
import org.jboss.dna.common.util.ObjectUtil;
-import org.jboss.dna.graph.property.Path;
/**
* A join condition that tests whether two nodes are the same nodes (that is, have the same identifier or have the same relative
@@ -37,7 +36,7 @@
public class SameNodeJoinCondition extends JoinCondition {
private final SelectorName selector1Name;
private final SelectorName selector2Name;
- private final Path selector2Path;
+ private final String selector2Path;
private final int hc;
/**
@@ -51,7 +50,7 @@
*/
public SameNodeJoinCondition( SelectorName selector1Name,
SelectorName selector2Name,
- Path selector2Path ) {
+ String selector2Path ) {
CheckArg.isNotNull(selector1Name, "selector1Name");
CheckArg.isNotNull(selector2Name, "selector2Name");
CheckArg.isNotNull(selector2Path, "selector2Path");
@@ -102,7 +101,7 @@
*
* @return the relative path to the node; may be null if the second selector is the node being used
*/
- public final Path getSelector2Path() {
+ public final String getSelector2Path() {
return selector2Path;
}
Modified: trunk/dna-graph/src/main/java/org/jboss/dna/graph/query/model/SelectorName.java
===================================================================
--- trunk/dna-graph/src/main/java/org/jboss/dna/graph/query/model/SelectorName.java 2009-11-24 17:44:29 UTC (rev 1339)
+++ trunk/dna-graph/src/main/java/org/jboss/dna/graph/query/model/SelectorName.java 2009-11-24 17:46:37 UTC (rev 1340)
@@ -25,7 +25,6 @@
import net.jcip.annotations.Immutable;
import org.jboss.dna.common.util.CheckArg;
-import org.jboss.dna.graph.ExecutionContext;
/**
* A representation of a qualified or expanded name.
@@ -52,9 +51,9 @@
/**
* {@inheritDoc}
*
- * @see org.jboss.dna.graph.query.model.Readable#getString(ExecutionContext)
+ * @see org.jboss.dna.graph.query.model.Readable#getString()
*/
- public String getString( ExecutionContext context ) {
+ public String getString() {
return name;
}
Modified: trunk/dna-graph/src/main/java/org/jboss/dna/graph/query/model/SetCriteria.java
===================================================================
--- trunk/dna-graph/src/main/java/org/jboss/dna/graph/query/model/SetCriteria.java 2009-11-24 17:44:29 UTC (rev 1339)
+++ trunk/dna-graph/src/main/java/org/jboss/dna/graph/query/model/SetCriteria.java 2009-11-24 17:46:37 UTC (rev 1340)
@@ -42,6 +42,7 @@
Collection<StaticOperand> setOperands ) {
CheckArg.isNotNull(left, "left");
CheckArg.isNotNull(setOperands, "setOperands");
+ CheckArg.isNotEmpty(setOperands, "setOperands");
this.left = left;
this.setOperands = setOperands;
}
@@ -50,19 +51,24 @@
StaticOperand... setOperands ) {
CheckArg.isNotNull(left, "left");
CheckArg.isNotNull(setOperands, "setOperands");
+ CheckArg.isNotEmpty(setOperands, "setOperands");
this.left = left;
this.setOperands = Collections.unmodifiableList(Arrays.asList(setOperands));
}
/**
- * @return operand1
+ * Get the dynamic operand to which the set constraint applies
+ *
+ * @return the dynamic operand; never null
*/
public final DynamicOperand getLeftOperand() {
return left;
}
/**
- * @return operand2
+ * Get the collection of static operands defining the constrained values.
+ *
+ * @return the right-hand-side static operands; never null and never empty
*/
public final Collection<StaticOperand> getRightOperands() {
return setOperands;
Modified: trunk/dna-graph/src/main/java/org/jboss/dna/graph/query/model/SetQuery.java
===================================================================
--- trunk/dna-graph/src/main/java/org/jboss/dna/graph/query/model/SetQuery.java 2009-11-24 17:44:29 UTC (rev 1339)
+++ trunk/dna-graph/src/main/java/org/jboss/dna/graph/query/model/SetQuery.java 2009-11-24 17:46:37 UTC (rev 1340)
@@ -33,7 +33,6 @@
import org.jboss.dna.common.util.CheckArg;
import org.jboss.dna.common.util.HashCode;
import org.jboss.dna.common.util.ObjectUtil;
-import org.jboss.dna.graph.ExecutionContext;
/**
* This object acts as a Set operator on multiple {@link QueryCommand queries}, such as performing UNION, INTERSECT, and EXCEPT
@@ -91,9 +90,9 @@
/**
* {@inheritDoc}
*
- * @see org.jboss.dna.graph.query.model.Readable#getString(org.jboss.dna.graph.ExecutionContext)
+ * @see org.jboss.dna.graph.query.model.Readable#getString()
*/
- public String getString( ExecutionContext context ) {
+ public String getString() {
return getSymbol();
}
}
@@ -104,6 +103,15 @@
private final boolean all;
private final int hc;
+ /**
+ * Create a set query involving the supplied left- and right-hand-side queries.
+ *
+ * @param left the left-hand-side query being combined
+ * @param operation the set operation
+ * @param right the right-hand-side query being combined
+ * @param all true if all of the results should be included
+ * @throws IllegalArgumentException if the left-hand-side query, right-hand-side query, or operation are null
+ */
public SetQuery( QueryCommand left,
Operation operation,
QueryCommand right,
@@ -119,6 +127,17 @@
this.hc = HashCode.compute(this.left, this.right, this.operation);
}
+ /**
+ * Create a set query involving the supplied left- and right-hand-side queries.
+ *
+ * @param left the left-hand-side query being combined
+ * @param operation the set operation
+ * @param right the right-hand-side query being combined
+ * @param all true if all of the results should be included
+ * @param orderings the specification of the order of the result rows, or null if the results need not be ordered
+ * @param limit the limit for the result rows, or null if there are no limits
+ * @throws IllegalArgumentException if the left-hand-side query, right-hand-side query, or operation are null
+ */
public SetQuery( QueryCommand left,
Operation operation,
QueryCommand right,
Added: trunk/dna-graph/src/main/java/org/jboss/dna/graph/query/model/TypeSystem.java
===================================================================
--- trunk/dna-graph/src/main/java/org/jboss/dna/graph/query/model/TypeSystem.java (rev 0)
+++ trunk/dna-graph/src/main/java/org/jboss/dna/graph/query/model/TypeSystem.java 2009-11-24 17:46:37 UTC (rev 1340)
@@ -0,0 +1,143 @@
+/*
+ * JBoss DNA (http://www.jboss.org/dna)
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ * See the AUTHORS.txt file in the distribution for a full listing of
+ * individual contributors.
+ *
+ * JBoss DNA is free software. Unless otherwise indicated, all code in JBoss DNA
+ * is licensed to you under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation; either version 2.1 of
+ * the License, or (at your option) any later version.
+ *
+ * JBoss DNA is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this software; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+ */
+package org.jboss.dna.graph.query.model;
+
+import java.util.Comparator;
+import java.util.Set;
+import net.jcip.annotations.Immutable;
+import org.jboss.dna.graph.property.ValueFormatException;
+
+/**
+ *
+ */
+@Immutable
+public interface TypeSystem {
+
+ TypeFactory<?> getTypeFactory( String typeName );
+
+ TypeFactory<?> getTypeFactory( Object prototype );
+
+ TypeFactory<Boolean> getBooleanFactory();
+
+ TypeFactory<Long> getLongFactory();
+
+ TypeFactory<String> getStringFactory();
+
+ TypeFactory<Double> getDoubleFactory();
+
+ TypeFactory<?> getDateTimeFactory();
+
+ TypeFactory<?> getPathFactory();
+
+ String getDefaultType();
+
+ Comparator<Object> getDefaultComparator();
+
+ /**
+ * Get the names of the supported types.
+ *
+ * @return the immutable set of the uppercase names of the types; never null
+ */
+ Set<String> getTypeNames();
+
+ /**
+ * Get the string representation of the supplied value, using the most appropriate factory given the value.
+ *
+ * @param value the value
+ * @return the string representation; never null
+ */
+ String asString( Object value );
+
+ /**
+ * Factory interface for creating values from strings.
+ *
+ * @param <T> the type of value object
+ */
+ public interface TypeFactory<T> {
+
+ /**
+ * Get the class representing the value type.
+ *
+ * @return the value type; never null
+ */
+ Class<T> getType();
+
+ /**
+ * Get a comparator that can be used to store the values of this type.
+ *
+ * @return the comparator; never null
+ */
+ Comparator<T> getComparator();
+
+ /**
+ * Get the name of the type created by this factory.
+ *
+ * @return the type name; never null and never empty or blank
+ */
+ String getTypeName();
+
+ /**
+ * Create the typed representation of the value given the supplied string representation.
+ *
+ * @param value the string representation of the value
+ * @return the typed representation, which will be an instance of the {@link #getType() type}
+ * @throws ValueFormatException if the string cannot be converted to a typed value
+ */
+ T create( String value ) throws ValueFormatException;
+
+ /**
+ * Create the typed representation of the value given the supplied object representation.
+ *
+ * @param value the object representation of the value
+ * @return the typed representation, which will be an instance of the {@link #getType() type}
+ * @throws ValueFormatException if the object cannot be converted to a typed value
+ */
+ T create( Object value ) throws ValueFormatException;
+
+ /**
+ * Get the string representation of the supplied value.
+ *
+ * @param value the value
+ * @return the string representation; never null
+ */
+ String asString( Object value );
+
+ /**
+ * Get the length of the supplied value.
+ *
+ * @param value the value
+ * @return the length; never negative
+ */
+ long length( Object value );
+
+ /**
+ * Get a readable and potentially shorter string representation of the supplied value.
+ *
+ * @param value the value
+ * @return the readable string representation; never null
+ */
+ String asReadableString( Object value );
+ }
+
+}
Property changes on: trunk/dna-graph/src/main/java/org/jboss/dna/graph/query/model/TypeSystem.java
___________________________________________________________________
Name: svn:keywords
+ Id Revision
Name: svn:eol-style
+ LF
Modified: trunk/dna-graph/src/main/java/org/jboss/dna/graph/query/model/Visitable.java
===================================================================
--- trunk/dna-graph/src/main/java/org/jboss/dna/graph/query/model/Visitable.java 2009-11-24 17:44:29 UTC (rev 1339)
+++ trunk/dna-graph/src/main/java/org/jboss/dna/graph/query/model/Visitable.java 2009-11-24 17:46:37 UTC (rev 1340)
@@ -26,9 +26,14 @@
import net.jcip.annotations.Immutable;
/**
- *
+ * An interface called by a visitor when that visitor is visiting the node.
*/
@Immutable
public interface Visitable {
+ /**
+ * Accept the supplied visitor, which should call back to the visitor to complete the double-dispatch operation.
+ *
+ * @param visitor the visitor; never null
+ */
void accept( Visitor visitor );
}
Modified: trunk/dna-graph/src/main/java/org/jboss/dna/graph/query/model/Visitors.java
===================================================================
--- trunk/dna-graph/src/main/java/org/jboss/dna/graph/query/model/Visitors.java 2009-11-24 17:44:29 UTC (rev 1339)
+++ trunk/dna-graph/src/main/java/org/jboss/dna/graph/query/model/Visitors.java 2009-11-24 17:46:37 UTC (rev 1340)
@@ -74,20 +74,8 @@
* Using a visitor, obtain the readable string representation of the supplied {@link Visitable object}
*
* @param visitable the visitable
- * @param context the execution context in which the representation should be produced, or null if there is none
* @return the string representation
*/
- public static String readable( Visitable visitable,
- ExecutionContext context ) {
- return visit(visitable, new ReadableVisitor(context)).getString();
- }
-
- /**
- * Using a visitor, obtain the readable string representation of the supplied {@link Visitable object}
- *
- * @param visitable the visitable
- * @return the string representation
- */
public static String readable( Visitable visitable ) {
return visit(visitable, new ReadableVisitor()).getString();
}
@@ -955,7 +943,7 @@
}
protected final ReadableVisitor append( SelectorName name ) {
- sb.append(name.getString(context));
+ sb.append(name.getString());
return this;
}
@@ -1082,10 +1070,9 @@
if (column.getPropertyName() == null) {
append(".*");
} else {
- Name propertyName = column.getPropertyName();
- String propName = propertyName.getString(registry, null, null);
- append('.').append(propName);
- if (!propName.equals(column.getColumnName()) && !propertyName.getLocalName().equals(column.getColumnName())) {
+ String propertyName = column.getPropertyName();
+ append('.').append(propertyName);
+ if (!propertyName.equals(column.getColumnName()) && !propertyName.equals(column.getColumnName())) {
append(" AS ").append(column.getColumnName());
}
}
Modified: trunk/dna-graph/src/main/java/org/jboss/dna/graph/query/optimize/ChooseJoinAlgorithm.java
===================================================================
--- trunk/dna-graph/src/main/java/org/jboss/dna/graph/query/optimize/ChooseJoinAlgorithm.java 2009-11-24 17:44:29 UTC (rev 1339)
+++ trunk/dna-graph/src/main/java/org/jboss/dna/graph/query/optimize/ChooseJoinAlgorithm.java 2009-11-24 17:46:37 UTC (rev 1340)
@@ -27,7 +27,6 @@
import java.util.List;
import java.util.Set;
import net.jcip.annotations.Immutable;
-import org.jboss.dna.graph.property.Name;
import org.jboss.dna.graph.query.QueryContext;
import org.jboss.dna.graph.query.model.ChildNodeJoinCondition;
import org.jboss.dna.graph.query.model.DescendantNodeJoinCondition;
@@ -206,8 +205,8 @@
EquiJoinCondition joinCondition = (EquiJoinCondition)condition;
SelectorName selector1 = joinCondition.getSelector1Name();
SelectorName selector2 = joinCondition.getSelector2Name();
- Name property1 = joinCondition.getProperty1Name();
- Name property2 = joinCondition.getProperty2Name();
+ String property1 = joinCondition.getProperty1Name();
+ String property2 = joinCondition.getProperty2Name();
// Create the Ordering for the first selector/property pair ...
DynamicOperand operand1 = new PropertyValue(selector1, property1);
Modified: trunk/dna-graph/src/main/java/org/jboss/dna/graph/query/optimize/CopyCriteria.java
===================================================================
--- trunk/dna-graph/src/main/java/org/jboss/dna/graph/query/optimize/CopyCriteria.java 2009-11-24 17:44:29 UTC (rev 1339)
+++ trunk/dna-graph/src/main/java/org/jboss/dna/graph/query/optimize/CopyCriteria.java 2009-11-24 17:46:37 UTC (rev 1340)
@@ -28,9 +28,6 @@
import java.util.LinkedList;
import java.util.Set;
import net.jcip.annotations.Immutable;
-import org.jboss.dna.graph.ExecutionContext;
-import org.jboss.dna.graph.property.Name;
-import org.jboss.dna.graph.property.ValueFactory;
import org.jboss.dna.graph.query.QueryContext;
import org.jboss.dna.graph.query.model.Column;
import org.jboss.dna.graph.query.model.Constraint;
@@ -75,8 +72,8 @@
EquiJoinCondition equiJoinCondition = (EquiJoinCondition)joinCondition;
SelectorName selector1 = equiJoinCondition.getSelector1Name();
SelectorName selector2 = equiJoinCondition.getSelector2Name();
- Name property1 = equiJoinCondition.getProperty1Name();
- Name property2 = equiJoinCondition.getProperty2Name();
+ String property1 = equiJoinCondition.getProperty1Name();
+ String property2 = equiJoinCondition.getProperty2Name();
// Walk up the tree looking for SELECT nodes that apply to one of the sides ...
PlanNode node = join.getParent();
@@ -145,14 +142,14 @@
protected PlanNode copySelectNode( QueryContext context,
PlanNode selectNode,
SelectorName selectorName,
- Name propertyName,
+ String propertyName,
SelectorName copySelectorName,
- Name copyPropertyName ) {
+ String copyPropertyName ) {
if (selectNode.isNot(Type.SELECT)) return null;
if (selectNode.getSelectors().size() != 1 || !selectNode.getSelectors().contains(selectorName)) return null;
Constraint constraint = selectNode.getProperty(Property.SELECT_CRITERIA, Constraint.class);
- Set<Column> columns = getColumnsReferencedBy(constraint, context.getExecutionContext());
+ Set<Column> columns = getColumnsReferencedBy(constraint);
if (columns.size() != 1) return null;
Column column = columns.iterator().next();
if (!column.getSelectorName().equals(selectorName)) return null;
@@ -165,10 +162,8 @@
PlanNode copy = new PlanNode(Type.SELECT, copySelectorName);
// Copy the constraint, but change the references to the copy selector and property ...
- ValueFactory<String> stringFactory = context.getExecutionContext().getValueFactories().getStringFactory();
PlanUtil.ColumnMapping mappings = new PlanUtil.ColumnMapping(selectorName);
- mappings.map(stringFactory.create(propertyName), new Column(copySelectorName, copyPropertyName,
- stringFactory.create(copyPropertyName)));
+ mappings.map(propertyName, new Column(copySelectorName, copyPropertyName, copyPropertyName));
Constraint newCriteria = PlanUtil.replaceReferences(context, constraint, mappings, copy);
copy.setProperty(Property.SELECT_CRITERIA, newCriteria);
@@ -189,20 +184,17 @@
* Get the set of Column objects that represent those columns referenced by the visitable object.
*
* @param visitable the object to be visited
- * @param context the context; may not be null
* @return the set of Column objects, with column names that always are the string-form of the
* {@link Column#getPropertyName() property name}; never null
*/
- public static Set<Column> getColumnsReferencedBy( Visitable visitable,
- ExecutionContext context ) {
+ public static Set<Column> getColumnsReferencedBy( Visitable visitable ) {
if (visitable == null) return Collections.emptySet();
- final ValueFactory<String> stringFactory = context.getValueFactories().getStringFactory();
final Set<Column> symbols = new HashSet<Column>();
// Walk the entire structure, so only supply a StrategyVisitor (that does no navigation) ...
Visitors.visitAll(visitable, new AbstractVisitor() {
protected void addColumnFor( SelectorName selectorName,
- Name property ) {
- symbols.add(new Column(selectorName, property, stringFactory.create(property)));
+ String property ) {
+ symbols.add(new Column(selectorName, property, property));
}
@Override
Modified: trunk/dna-graph/src/main/java/org/jboss/dna/graph/query/optimize/RaiseSelectCriteria.java
===================================================================
--- trunk/dna-graph/src/main/java/org/jboss/dna/graph/query/optimize/RaiseSelectCriteria.java 2009-11-24 17:44:29 UTC (rev 1339)
+++ trunk/dna-graph/src/main/java/org/jboss/dna/graph/query/optimize/RaiseSelectCriteria.java 2009-11-24 17:46:37 UTC (rev 1340)
@@ -28,9 +28,6 @@
import java.util.LinkedList;
import java.util.Set;
import net.jcip.annotations.Immutable;
-import org.jboss.dna.graph.ExecutionContext;
-import org.jboss.dna.graph.property.Name;
-import org.jboss.dna.graph.property.ValueFactory;
import org.jboss.dna.graph.query.QueryContext;
import org.jboss.dna.graph.query.model.Column;
import org.jboss.dna.graph.query.model.Constraint;
@@ -136,8 +133,8 @@
EquiJoinCondition equiJoinCondition = (EquiJoinCondition)joinCondition;
SelectorName selector1 = equiJoinCondition.getSelector1Name();
SelectorName selector2 = equiJoinCondition.getSelector2Name();
- Name property1 = equiJoinCondition.getProperty1Name();
- Name property2 = equiJoinCondition.getProperty2Name();
+ String property1 = equiJoinCondition.getProperty1Name();
+ String property2 = equiJoinCondition.getProperty2Name();
// Walk up the tree looking for SELECT nodes that apply to one of the sides ...
PlanNode node = join.getParent();
@@ -167,14 +164,14 @@
protected PlanNode copySelectNode( QueryContext context,
PlanNode selectNode,
SelectorName selectorName,
- Name propertyName,
+ String propertyName,
SelectorName copySelectorName,
- Name copyPropertyName ) {
+ String copyPropertyName ) {
if (selectNode.isNot(Type.SELECT)) return null;
if (selectNode.getSelectors().size() != 1 || !selectNode.getSelectors().contains(selectorName)) return null;
Constraint constraint = selectNode.getProperty(Property.SELECT_CRITERIA, Constraint.class);
- Set<Column> columns = getColumnsReferencedBy(constraint, context.getExecutionContext());
+ Set<Column> columns = getColumnsReferencedBy(constraint);
if (columns.size() != 1) return null;
Column column = columns.iterator().next();
if (!column.getSelectorName().equals(selectorName)) return null;
@@ -187,10 +184,8 @@
PlanNode copy = new PlanNode(Type.SELECT, copySelectorName);
// Copy the constraint, but change the references to the copy selector and property ...
- ValueFactory<String> stringFactory = context.getExecutionContext().getValueFactories().getStringFactory();
PlanUtil.ColumnMapping mappings = new PlanUtil.ColumnMapping(selectorName);
- mappings.map(stringFactory.create(propertyName), new Column(copySelectorName, copyPropertyName,
- stringFactory.create(copyPropertyName)));
+ mappings.map(propertyName, new Column(copySelectorName, copyPropertyName, copyPropertyName));
Constraint newCriteria = PlanUtil.replaceReferences(context, constraint, mappings, copy);
copy.setProperty(Property.SELECT_CRITERIA, newCriteria);
@@ -211,20 +206,17 @@
* Get the set of Column objects that represent those columns referenced by the visitable object.
*
* @param visitable the object to be visited
- * @param context the context; may not be null
* @return the set of Column objects, with column names that always are the string-form of the
* {@link Column#getPropertyName() property name}; never null
*/
- public static Set<Column> getColumnsReferencedBy( Visitable visitable,
- ExecutionContext context ) {
+ public static Set<Column> getColumnsReferencedBy( Visitable visitable ) {
if (visitable == null) return Collections.emptySet();
- final ValueFactory<String> stringFactory = context.getValueFactories().getStringFactory();
final Set<Column> symbols = new HashSet<Column>();
// Walk the entire structure, so only supply a StrategyVisitor (that does no navigation) ...
Visitors.visitAll(visitable, new AbstractVisitor() {
protected void addColumnFor( SelectorName selectorName,
- Name property ) {
- symbols.add(new Column(selectorName, property, stringFactory.create(property)));
+ String property ) {
+ symbols.add(new Column(selectorName, property, property));
}
@Override
Modified: trunk/dna-graph/src/main/java/org/jboss/dna/graph/query/optimize/RewriteIdentityJoins.java
===================================================================
--- trunk/dna-graph/src/main/java/org/jboss/dna/graph/query/optimize/RewriteIdentityJoins.java 2009-11-24 17:44:29 UTC (rev 1339)
+++ trunk/dna-graph/src/main/java/org/jboss/dna/graph/query/optimize/RewriteIdentityJoins.java 2009-11-24 17:46:37 UTC (rev 1340)
@@ -29,7 +29,6 @@
import java.util.Map;
import net.jcip.annotations.Immutable;
import org.jboss.dna.graph.GraphI18n;
-import org.jboss.dna.graph.property.ValueFactory;
import org.jboss.dna.graph.query.QueryContext;
import org.jboss.dna.graph.query.model.Column;
import org.jboss.dna.graph.query.model.EquiJoinCondition;
@@ -118,9 +117,8 @@
context.getProblems().addError(GraphI18n.tableDoesNotExist, leftTableName);
continue;
}
- ValueFactory<String> stringFactory = context.getExecutionContext().getValueFactories().getStringFactory();
- String leftColumnName = stringFactory.create(equiJoin.getProperty1Name());
- String rightColumnName = stringFactory.create(equiJoin.getProperty2Name());
+ String leftColumnName = equiJoin.getProperty1Name();
+ String rightColumnName = equiJoin.getProperty2Name();
Schemata.Column leftColumn = table.getColumn(leftColumnName);
Schemata.Column rightColumn = table.getColumn(rightColumnName);
if (leftColumn == null) {
Modified: trunk/dna-graph/src/main/java/org/jboss/dna/graph/query/parse/QueryParser.java
===================================================================
--- trunk/dna-graph/src/main/java/org/jboss/dna/graph/query/parse/QueryParser.java 2009-11-24 17:44:29 UTC (rev 1339)
+++ trunk/dna-graph/src/main/java/org/jboss/dna/graph/query/parse/QueryParser.java 2009-11-24 17:46:37 UTC (rev 1340)
@@ -25,8 +25,8 @@
import net.jcip.annotations.Immutable;
import org.jboss.dna.common.text.ParsingException;
-import org.jboss.dna.graph.ExecutionContext;
import org.jboss.dna.graph.query.model.QueryCommand;
+import org.jboss.dna.graph.query.model.TypeSystem;
/**
* The basic interface defining a component that is able to parse a string query into a {@link QueryCommand}.
@@ -45,12 +45,12 @@
* Parse the supplied query from a string representation into a {@link QueryCommand}.
*
* @param query the query in string form; may not be null
- * @param context the context in which the query is being parsed
+ * @param typeSystem the type system used by the query; may not be null
* @return the query command
* @throws ParsingException if there is an error parsing the supplied query
* @throws InvalidQueryException if the supplied query can be parsed but is invalid
*/
QueryCommand parseQuery( String query,
- ExecutionContext context ) throws InvalidQueryException;
+ TypeSystem typeSystem ) throws InvalidQueryException;
}
Modified: trunk/dna-graph/src/main/java/org/jboss/dna/graph/query/parse/QueryParsers.java
===================================================================
--- trunk/dna-graph/src/main/java/org/jboss/dna/graph/query/parse/QueryParsers.java 2009-11-24 17:44:29 UTC (rev 1339)
+++ trunk/dna-graph/src/main/java/org/jboss/dna/graph/query/parse/QueryParsers.java 2009-11-24 17:46:37 UTC (rev 1340)
@@ -32,9 +32,9 @@
import net.jcip.annotations.ThreadSafe;
import org.jboss.dna.common.text.ParsingException;
import org.jboss.dna.common.util.CheckArg;
-import org.jboss.dna.graph.ExecutionContext;
import org.jboss.dna.graph.GraphI18n;
import org.jboss.dna.graph.query.model.QueryCommand;
+import org.jboss.dna.graph.query.model.TypeSystem;
/**
* A thread-safe collection of {@link QueryParser} implementations that can be used to parse queries by language.
@@ -155,7 +155,7 @@
/**
* Execute the supplied query by planning, optimizing, and then processing it.
*
- * @param context the context in which the query should be executed
+ * @param typeSystem the type system that should be used
* @param language the language in which the query is expressed; must be one of the supported {@link #getLanguages()
* languages}
* @param query the query that is to be executed
@@ -164,17 +164,17 @@
* @throws ParsingException if there is an error parsing the supplied query
* @throws InvalidQueryException if the supplied query can be parsed but is invalid
*/
- public QueryCommand parse( ExecutionContext context,
+ public QueryCommand parse( TypeSystem typeSystem,
String language,
String query ) {
CheckArg.isNotNull(language, "language");
- CheckArg.isNotNull(context, "context");
+ CheckArg.isNotNull(typeSystem, "typeSystem");
CheckArg.isNotNull(query, "query");
QueryParser parser = parsers.get(language.toLowerCase());
if (parser == null) {
throw new IllegalArgumentException(GraphI18n.unknownQueryLanguage.text(language));
}
- return parser.parseQuery(query, context);
+ return parser.parseQuery(query, typeSystem);
}
/**
Modified: trunk/dna-graph/src/main/java/org/jboss/dna/graph/query/parse/SqlQueryParser.java
===================================================================
--- trunk/dna-graph/src/main/java/org/jboss/dna/graph/query/parse/SqlQueryParser.java 2009-11-24 17:44:29 UTC (rev 1339)
+++ trunk/dna-graph/src/main/java/org/jboss/dna/graph/query/parse/SqlQueryParser.java 2009-11-24 17:46:37 UTC (rev 1340)
@@ -37,15 +37,7 @@
import org.jboss.dna.common.text.TokenStream.Tokenizer;
import org.jboss.dna.common.text.TokenStream.Tokens;
import org.jboss.dna.common.xml.XmlCharacters;
-import org.jboss.dna.graph.ExecutionContext;
import org.jboss.dna.graph.GraphI18n;
-import org.jboss.dna.graph.property.DateTime;
-import org.jboss.dna.graph.property.Name;
-import org.jboss.dna.graph.property.NameFactory;
-import org.jboss.dna.graph.property.Path;
-import org.jboss.dna.graph.property.PathFactory;
-import org.jboss.dna.graph.property.ValueFactories;
-import org.jboss.dna.graph.property.ValueFactory;
import org.jboss.dna.graph.property.ValueFormatException;
import org.jboss.dna.graph.query.model.And;
import org.jboss.dna.graph.query.model.Between;
@@ -90,9 +82,11 @@
import org.jboss.dna.graph.query.model.SetQuery;
import org.jboss.dna.graph.query.model.Source;
import org.jboss.dna.graph.query.model.StaticOperand;
+import org.jboss.dna.graph.query.model.TypeSystem;
import org.jboss.dna.graph.query.model.UpperCase;
import org.jboss.dna.graph.query.model.FullTextSearch.Term;
import org.jboss.dna.graph.query.model.SetQuery.Operation;
+import org.jboss.dna.graph.query.model.TypeSystem.TypeFactory;
/**
* A {@link QueryParser} implementation that parses a subset of SQL select and set queries.
@@ -475,24 +469,24 @@
/**
* {@inheritDoc}
*
- * @see org.jboss.dna.graph.query.parse.QueryParser#parseQuery(String, ExecutionContext)
+ * @see org.jboss.dna.graph.query.parse.QueryParser#parseQuery(String, TypeSystem)
*/
public QueryCommand parseQuery( String query,
- ExecutionContext context ) {
+ TypeSystem typeSystem ) {
Tokenizer tokenizer = new SqlTokenizer(false);
TokenStream tokens = new TokenStream(query, tokenizer, false);
tokens.start();
- return parseQueryCommand(tokens, context);
+ return parseQueryCommand(tokens, typeSystem);
}
protected QueryCommand parseQueryCommand( TokenStream tokens,
- ExecutionContext context ) {
+ TypeSystem typeSystem ) {
QueryCommand command = null;
if (tokens.matches("SELECT")) {
- command = parseQuery(tokens, context);
+ command = parseQuery(tokens, typeSystem);
while (tokens.hasNext()) {
if (tokens.matchesAnyOf("UNION", "INTERSECT", "EXCEPT")) {
- command = parseSetQuery(tokens, command, context);
+ command = parseSetQuery(tokens, command, typeSystem);
} else {
Position pos = tokens.previousPosition();
String msg = GraphI18n.unexpectedToken.text(tokens.consume(), pos.getLine(), pos.getColumn());
@@ -504,21 +498,21 @@
}
protected Query parseQuery( TokenStream tokens,
- ExecutionContext context ) {
+ TypeSystem typeSystem ) {
AtomicBoolean isDistinct = new AtomicBoolean(false);
- List<ColumnExpression> columnExpressions = parseSelect(tokens, isDistinct, context);
- Source source = parseFrom(tokens, context);
- Constraint constraint = parseWhere(tokens, context, source);
+ List<ColumnExpression> columnExpressions = parseSelect(tokens, isDistinct, typeSystem);
+ Source source = parseFrom(tokens, typeSystem);
+ Constraint constraint = parseWhere(tokens, typeSystem, source);
// Parse the order by and limit (can be in any order) ...
- List<Ordering> orderings = parseOrderBy(tokens, context, source);
+ List<Ordering> orderings = parseOrderBy(tokens, typeSystem, source);
Limit limit = parseLimit(tokens);
- if (orderings == null) parseOrderBy(tokens, context, source);
+ if (orderings == null) parseOrderBy(tokens, typeSystem, source);
// Convert the column expressions to columns ...
List<Column> columns = new ArrayList<Column>(columnExpressions.size());
for (ColumnExpression expression : columnExpressions) {
SelectorName selectorName = expression.getSelectorName();
- Name propertyName = nameFrom(expression.getPropertyName(), expression.getPosition(), context);
+ String propertyName = expression.getPropertyName();
if (selectorName == null) {
if (source instanceof Selector) {
selectorName = ((Selector)source).getName();
@@ -536,7 +530,7 @@
protected SetQuery parseSetQuery( TokenStream tokens,
QueryCommand leftHandSide,
- ExecutionContext context ) {
+ TypeSystem typeSystem ) {
Operation operation = null;
if (tokens.canConsume("UNION")) {
operation = Operation.UNION;
@@ -548,13 +542,13 @@
}
boolean all = tokens.canConsume("ALL");
// Parse the next select
- QueryCommand rightQuery = parseQuery(tokens, context);
+ QueryCommand rightQuery = parseQuery(tokens, typeSystem);
return new SetQuery(leftHandSide, operation, rightQuery, all);
}
protected List<ColumnExpression> parseSelect( TokenStream tokens,
AtomicBoolean isDistinct,
- ExecutionContext context ) {
+ TypeSystem typeSystem ) {
tokens.consume("SELECT");
if (tokens.canConsume("DISTINCT")) isDistinct.set(true);
if (tokens.canConsume('*')) {
@@ -578,7 +572,7 @@
}
protected Source parseFrom( TokenStream tokens,
- ExecutionContext context ) {
+ TypeSystem typeSystem ) {
Source source = null;
tokens.consume("FROM");
source = parseNamedSelector(tokens);
@@ -600,7 +594,7 @@
// Read the name of the selector on the right side of the join ...
NamedSelector right = parseNamedSelector(tokens);
// Read the join condition ...
- JoinCondition joinCondition = parseJoinCondition(tokens, context);
+ JoinCondition joinCondition = parseJoinCondition(tokens, typeSystem);
// Create the join ...
source = new Join(source, joinType, right, joinCondition);
}
@@ -608,14 +602,14 @@
}
protected JoinCondition parseJoinCondition( TokenStream tokens,
- ExecutionContext context ) {
+ TypeSystem typeSystem ) {
tokens.consume("ON");
if (tokens.canConsume("ISSAMENODE", "(")) {
SelectorName selector1Name = parseSelectorName(tokens);
tokens.consume(',');
SelectorName selector2Name = parseSelectorName(tokens);
if (tokens.canConsume('.')) {
- Path path = parsePath(tokens, context);
+ String path = parsePath(tokens, typeSystem);
tokens.consume(')');
return new SameNodeJoinCondition(selector1Name, selector2Name, path);
}
@@ -638,52 +632,52 @@
}
SelectorName selector1 = parseSelectorName(tokens);
tokens.consume('.');
- Name property1 = parseName(tokens, context);
+ String property1 = parseName(tokens, typeSystem);
tokens.consume('=');
SelectorName selector2 = parseSelectorName(tokens);
tokens.consume('.');
- Name property2 = parseName(tokens, context);
+ String property2 = parseName(tokens, typeSystem);
return new EquiJoinCondition(selector1, property1, selector2, property2);
}
protected Constraint parseWhere( TokenStream tokens,
- ExecutionContext context,
+ TypeSystem typeSystem,
Source source ) {
if (tokens.canConsume("WHERE")) {
- return parseConstraint(tokens, context, source);
+ return parseConstraint(tokens, typeSystem, source);
}
return null;
}
protected Constraint parseConstraint( TokenStream tokens,
- ExecutionContext context,
+ TypeSystem typeSystem,
Source source ) {
Constraint constraint = null;
Position pos = tokens.nextPosition();
if (tokens.canConsume("(")) {
- constraint = parseConstraint(tokens, context, source);
+ constraint = parseConstraint(tokens, typeSystem, source);
tokens.consume(")");
} else if (tokens.canConsume("NOT")) {
tokens.canConsume('(');
- constraint = new Not(parseConstraint(tokens, context, source));
+ constraint = new Not(parseConstraint(tokens, typeSystem, source));
tokens.canConsume(')');
} else if (tokens.canConsume("CONTAINS", "(")) {
// Either 'selectorName.propertyName', or 'selectorName.*' or 'propertyName' ...
String first = tokens.consume();
SelectorName selectorName = null;
- Name propertyName = null;
+ String propertyName = null;
if (tokens.canConsume(".", "*")) {
selectorName = new SelectorName(removeBracketsAndQuotes(first));
} else if (tokens.canConsume('.')) {
selectorName = new SelectorName(removeBracketsAndQuotes(first));
- propertyName = parseName(tokens, context);
+ propertyName = parseName(tokens, typeSystem);
} else {
if (!(source instanceof Selector)) {
String msg = GraphI18n.functionIsAmbiguous.text("CONTAINS()", pos.getLine(), pos.getColumn());
throw new ParsingException(pos, msg);
}
selectorName = ((Selector)source).getName();
- propertyName = nameFrom(first, pos, context);
+ propertyName = first;
}
tokens.consume(',');
@@ -704,7 +698,7 @@
selectorName = parseSelectorName(tokens);
tokens.consume(',');
}
- Path path = parsePath(tokens, context);
+ String path = parsePath(tokens, typeSystem);
tokens.consume(')');
constraint = new SameNode(selectorName, path);
} else if (tokens.canConsume("ISCHILDNODE", "(")) {
@@ -719,7 +713,7 @@
selectorName = parseSelectorName(tokens);
tokens.consume(',');
}
- Path path = parsePath(tokens, context);
+ String path = parsePath(tokens, typeSystem);
tokens.consume(')');
constraint = new ChildNode(selectorName, path);
} else if (tokens.canConsume("ISDESCENDANTNODE", "(")) {
@@ -734,41 +728,41 @@
selectorName = parseSelectorName(tokens);
tokens.consume(',');
}
- Path path = parsePath(tokens, context);
+ String path = parsePath(tokens, typeSystem);
tokens.consume(')');
constraint = new DescendantNode(selectorName, path);
} else {
// First try a property existance ...
Position pos2 = tokens.nextPosition();
- constraint = parsePropertyExistance(tokens, context, source);
+ constraint = parsePropertyExistance(tokens, typeSystem, source);
if (constraint == null) {
// Try to parse as a dynamic operand ...
- DynamicOperand left = parseDynamicOperand(tokens, context, source);
+ DynamicOperand left = parseDynamicOperand(tokens, typeSystem, source);
if (left != null) {
if (tokens.matches('(') && left instanceof PropertyValue) {
// This was probably a bad function that we parsed as the start of a dynamic operation ...
- String name = ((PropertyValue)left).getPropertyName().getLocalName(); // this may be the function name
+ String name = ((PropertyValue)left).getPropertyName(); // this may be the function name
String msg = GraphI18n.expectingConstraintCondition.text(name, pos2.getLine(), pos2.getColumn());
throw new ParsingException(pos, msg);
}
if (tokens.matches("IN", "(") || tokens.matches("NOT", "IN", "(")) {
boolean not = tokens.canConsume("NOT");
- Collection<StaticOperand> staticOperands = parseInClause(tokens, context);
+ Collection<StaticOperand> staticOperands = parseInClause(tokens, typeSystem);
constraint = new SetCriteria(left, staticOperands);
if (not) constraint = new Not(constraint);
} else if (tokens.matches("BETWEEN") || tokens.matches("NOT", "BETWEEN")) {
boolean not = tokens.canConsume("NOT");
tokens.consume("BETWEEN");
- StaticOperand lowerBound = parseStaticOperand(tokens, context);
+ StaticOperand lowerBound = parseStaticOperand(tokens, typeSystem);
boolean lowerInclusive = !tokens.canConsume("EXCLUSIVE");
tokens.consume("AND");
- StaticOperand upperBound = parseStaticOperand(tokens, context);
+ StaticOperand upperBound = parseStaticOperand(tokens, typeSystem);
boolean upperInclusive = !tokens.canConsume("EXCLUSIVE");
constraint = new Between(left, lowerBound, upperBound, lowerInclusive, upperInclusive);
if (not) constraint = new Not(constraint);
} else {
Operator operator = parseComparisonOperator(tokens);
- StaticOperand right = parseStaticOperand(tokens, context);
+ StaticOperand right = parseStaticOperand(tokens, typeSystem);
constraint = new Comparison(left, operator, right);
}
}
@@ -781,23 +775,23 @@
}
// AND has higher precedence than OR, so we need to evaluate it first ...
while (tokens.canConsume("AND")) {
- constraint = new And(constraint, parseConstraint(tokens, context, source));
+ constraint = new And(constraint, parseConstraint(tokens, typeSystem, source));
}
while (tokens.canConsume("OR")) {
- constraint = new Or(constraint, parseConstraint(tokens, context, source));
+ constraint = new Or(constraint, parseConstraint(tokens, typeSystem, source));
}
return constraint;
}
protected List<StaticOperand> parseInClause( TokenStream tokens,
- ExecutionContext context ) {
+ TypeSystem typeSystem ) {
List<StaticOperand> result = new ArrayList<StaticOperand>();
tokens.consume("IN");
tokens.consume("(");
if (!tokens.canConsume(")")) {
// Not empty, so read the static operands ...
do {
- result.add(parseStaticOperand(tokens, context));
+ result.add(parseStaticOperand(tokens, typeSystem));
} while (tokens.canConsume(','));
tokens.consume(")");
}
@@ -833,12 +827,12 @@
}
protected List<Ordering> parseOrderBy( TokenStream tokens,
- ExecutionContext context,
+ TypeSystem typeSystem,
Source source ) {
if (tokens.canConsume("ORDER", "BY")) {
List<Ordering> orderings = new ArrayList<Ordering>();
do {
- orderings.add(parseOrdering(tokens, context, source));
+ orderings.add(parseOrdering(tokens, typeSystem, source));
} while (tokens.canConsume(','));
return orderings;
}
@@ -846,9 +840,9 @@
}
protected Ordering parseOrdering( TokenStream tokens,
- ExecutionContext context,
+ TypeSystem typeSystem,
Source source ) {
- DynamicOperand operand = parseDynamicOperand(tokens, context, source);
+ DynamicOperand operand = parseDynamicOperand(tokens, typeSystem, source);
Order order = Order.ASCENDING;
if (tokens.canConsume("DESC")) order = Order.DESCENDING;
if (tokens.canConsume("ASC")) order = Order.ASCENDING;
@@ -856,7 +850,7 @@
}
protected Constraint parsePropertyExistance( TokenStream tokens,
- ExecutionContext context,
+ TypeSystem typeSystem,
Source source ) {
if (tokens.matches(ANY_VALUE, ".", ANY_VALUE, "IS", "NOT", "NULL")
|| tokens.matches(ANY_VALUE, ".", ANY_VALUE, "IS", "NULL") || tokens.matches(ANY_VALUE, "IS", "NOT", "NULL")
@@ -864,11 +858,11 @@
Position pos = tokens.nextPosition();
String firstWord = tokens.consume();
SelectorName selectorName = null;
- Name propertyName = null;
+ String propertyName = null;
if (tokens.canConsume('.')) {
// We actually read the selector name, so now read the property name ...
selectorName = new SelectorName(firstWord);
- propertyName = parseName(tokens, context);
+ propertyName = parseName(tokens, typeSystem);
} else {
// Otherwise the source should be a single named selector
if (!(source instanceof Selector)) {
@@ -876,7 +870,7 @@
throw new ParsingException(pos, msg);
}
selectorName = ((Selector)source).getName();
- propertyName = nameFrom(firstWord, pos, context);
+ propertyName = firstWord;
}
if (tokens.canConsume("IS", "NOT", "NULL")) {
return new PropertyExistence(selectorName, propertyName);
@@ -888,7 +882,7 @@
}
protected StaticOperand parseStaticOperand( TokenStream tokens,
- ExecutionContext context ) {
+ TypeSystem typeSystem ) {
if (tokens.canConsume('$')) {
// The variable name must conform to a valid prefix, which is defined as a valid NCName ...
String value = tokens.consume();
@@ -899,66 +893,52 @@
}
return new BindVariableName(value);
}
- return parseLiteral(tokens, context);
+ return parseLiteral(tokens, typeSystem);
}
protected Literal parseLiteral( TokenStream tokens,
- ExecutionContext context ) {
+ TypeSystem typeSystem ) {
if (tokens.canConsume("CAST", "(")) {
// Get the value that is to be cast ...
Position pos = tokens.nextPosition();
- String value = parseLiteralValue(tokens, context);
+ String value = parseLiteralValue(tokens, typeSystem);
// Figure out the type we're supposed to cast to ...
- ValueFactories factories = context.getValueFactories();
- ValueFactory<?> factory = factories.getStringFactory();
tokens.consume("AS");
- if (tokens.canConsume("STRING")) factory = factories.getStringFactory();
- else if (tokens.canConsume("BINARY")) factory = factories.getBinaryFactory();
- else if (tokens.canConsume("DATE")) factory = factories.getDateFactory();
- else if (tokens.canConsume("LONG")) factory = factories.getLongFactory();
- else if (tokens.canConsume("DOUBLE")) factory = factories.getDoubleFactory();
- else if (tokens.canConsume("DECIMAL")) factory = factories.getDecimalFactory();
- else if (tokens.canConsume("BOOLEAN")) factory = factories.getBooleanFactory();
- else if (tokens.canConsume("NAME")) factory = factories.getNameFactory();
- else if (tokens.canConsume("PATH")) factory = factories.getPathFactory();
- else if (tokens.canConsume("REFERENCE")) factory = factories.getReferenceFactory();
- else if (tokens.canConsume("WEAKREFERENCE")) factory = factories.getPathFactory();
- else if (tokens.canConsume("URI")) factory = factories.getUriFactory();
- else {
- Position typePos = tokens.nextPosition();
+ String typeName = tokens.consume();
+ TypeFactory<?> typeFactory = typeSystem.getTypeFactory(typeName);
+ if (typeFactory == null) {
+ Position typePos = tokens.previousPosition();
String msg = GraphI18n.invalidPropertyType.text(tokens.consume(), typePos.getLine(), typePos.getColumn());
throw new ParsingException(typePos, msg);
}
// Convert the supplied value to the desired value ...
tokens.consume(')');
try {
- Object literal = factory.create(value);
- if (literal instanceof DateTime) {
- // Convert the timestamp to UTC, since that's how everything should be stored ...
- literal = ((DateTime)literal).toUtcTimeZone();
- }
+ Object literal = typeFactory.create(value);
return new Literal(literal);
} catch (ValueFormatException e) {
String msg = GraphI18n.valueCannotBeCastToSpecifiedType.text(value,
pos.getLine(),
pos.getColumn(),
- factory.getPropertyType().name(),
+ typeFactory.getTypeName(),
e.getMessage());
throw new ParsingException(pos, msg);
}
}
// Just create a literal out of the supplied value ...
- return new Literal(parseLiteralValue(tokens, context));
+ return new Literal(parseLiteralValue(tokens, typeSystem));
}
protected String parseLiteralValue( TokenStream tokens,
- ExecutionContext context ) {
+ TypeSystem typeSystem ) {
if (tokens.matches(SqlTokenizer.QUOTED_STRING)) {
return removeBracketsAndQuotes(tokens.consume());
}
- ValueFactory<String> stringFactory = context.getValueFactories().getStringFactory();
- if (tokens.canConsume("TRUE")) return stringFactory.create(Boolean.TRUE);
- if (tokens.canConsume("FALSE")) return stringFactory.create(Boolean.FALSE);
+ TypeFactory<Boolean> booleanFactory = typeSystem.getBooleanFactory();
+ if (booleanFactory != null) {
+ if (tokens.canConsume("TRUE")) return booleanFactory.asString(Boolean.TRUE);
+ if (tokens.canConsume("FALSE")) return booleanFactory.asString(Boolean.FALSE);
+ }
// Otherwise it is an unquoted literal value ...
Position pos = tokens.nextPosition();
@@ -968,95 +948,100 @@
// Try to parse this value as a number ...
String integral = tokens.consume();
- String decimal = null;
- if (tokens.canConsume('.')) {
- decimal = tokens.consume();
- String value = sign + integral + "." + decimal;
- if (decimal.endsWith("e") && (tokens.matches('+') || tokens.matches('-'))) {
- // There's more to the number ...
- value = value + tokens.consume() + tokens.consume(); // +/-EXP
+ TypeFactory<Double> doubleFactory = typeSystem.getDoubleFactory();
+ if (doubleFactory != null) {
+ String decimal = null;
+ if (tokens.canConsume('.')) {
+ decimal = tokens.consume();
+ String value = sign + integral + "." + decimal;
+ if (decimal.endsWith("e") && (tokens.matches('+') || tokens.matches('-'))) {
+ // There's more to the number ...
+ value = value + tokens.consume() + tokens.consume(); // +/-EXP
+ }
+ try {
+ // Convert to a double and then back to a string to get canonical form ...
+ return doubleFactory.asString(doubleFactory.create(value));
+ } catch (ValueFormatException e) {
+ String msg = GraphI18n.expectingLiteralAndUnableToParseAsDouble.text(value, pos.getLine(), pos.getColumn());
+ throw new ParsingException(pos, msg);
+ }
}
- try {
- // Convert to a double and then back to a string to get canonical form ...
- return stringFactory.create(context.getValueFactories().getDoubleFactory().create(value));
- } catch (ValueFormatException e) {
- String msg = GraphI18n.expectingLiteralAndUnableToParseAsDouble.text(value, pos.getLine(), pos.getColumn());
- throw new ParsingException(pos, msg);
- }
}
- if (tokens.canConsume('-')) {
- // Looks like a date (see Section 3.6.4.3 of the JCR 2.0 specification) ...
- // sYYYY-MM-DDThh:mm:ss.sssTZD
- String year = integral;
- String month = tokens.consume();
- tokens.consume('-');
- String dateAndHour = tokens.consume();
- tokens.consume(':');
- String minutes = tokens.consume();
- tokens.consume(':');
- String seconds = tokens.consume();
- tokens.consume('.');
- String subSeconds = tokens.consume(); // should contain 'T' separator and possibly the TZ name and (if no +/-)
- // hours
- String tzSign = "+";
- String tzHours = "00";
- String tzMinutes = "00";
- String tzDelim = ":";
- if (tokens.canConsume('+')) {
- // the fractionalSeconds did NOT contain the tzHours ...
- tzHours = tokens.consume();
- if (tokens.canConsume(':')) tzMinutes = tokens.consume();
- } else if (tokens.canConsume('-')) {
- // the fractionalSeconds did NOT contain the tzHours ...
- tzSign = "-";
- tzHours = tokens.consume();
- if (tokens.canConsume(':')) tzMinutes = tokens.consume();
- } else if (tokens.canConsume(':')) {
- // fractionalSeconds DID contain the TZ hours (without + or -)
- tzHours = tzSign = "";
- if (tokens.canConsume(':')) tzMinutes = tokens.consume();
- } else if (subSeconds.endsWith("Z")) {
- tzSign = tzMinutes = tzDelim = tzHours = "";
- } else if (subSeconds.endsWith("UTC")) {
- subSeconds = subSeconds.length() > 3 ? subSeconds.substring(0, subSeconds.length() - 3) : subSeconds;
+ TypeFactory<?> dateTimeFactory = typeSystem.getDateTimeFactory();
+ if (dateTimeFactory != null) {
+ if (tokens.canConsume('-')) {
+ // Looks like a date (see Section 3.6.4.3 of the JCR 2.0 specification) ...
+ // sYYYY-MM-DDThh:mm:ss.sssTZD
+ String year = integral;
+ String month = tokens.consume();
+ tokens.consume('-');
+ String dateAndHour = tokens.consume();
+ tokens.consume(':');
+ String minutes = tokens.consume();
+ tokens.consume(':');
+ String seconds = tokens.consume();
+ tokens.consume('.');
+ String subSeconds = tokens.consume(); // should contain 'T' separator and possibly the TZ name and (if no +/-)
+ // hours
+ String tzSign = "+";
+ String tzHours = "00";
+ String tzMinutes = "00";
+ String tzDelim = ":";
+ if (tokens.canConsume('+')) {
+ // the fractionalSeconds did NOT contain the tzHours ...
+ tzHours = tokens.consume();
+ if (tokens.canConsume(':')) tzMinutes = tokens.consume();
+ } else if (tokens.canConsume('-')) {
+ // the fractionalSeconds did NOT contain the tzHours ...
+ tzSign = "-";
+ tzHours = tokens.consume();
+ if (tokens.canConsume(':')) tzMinutes = tokens.consume();
+ } else if (tokens.canConsume(':')) {
+ // fractionalSeconds DID contain the TZ hours (without + or -)
+ tzHours = tzSign = "";
+ if (tokens.canConsume(':')) tzMinutes = tokens.consume();
+ } else if (subSeconds.endsWith("Z")) {
+ tzSign = tzMinutes = tzDelim = tzHours = "";
+ } else if (subSeconds.endsWith("UTC")) {
+ subSeconds = subSeconds.length() > 3 ? subSeconds.substring(0, subSeconds.length() - 3) : subSeconds;
+ }
+ String value = sign + year + "-" + month + "-" + dateAndHour + ":" + minutes + ":" + seconds + "." + subSeconds
+ + tzSign + tzHours + tzDelim + tzMinutes;
+ try {
+ // Convert to a date and then back to a string to get canonical form ...
+ Object dateTime = dateTimeFactory.create(value);
+ return dateTimeFactory.asString(dateTime);
+ } catch (ValueFormatException e) {
+ String msg = GraphI18n.expectingLiteralAndUnableToParseAsDate.text(value, pos.getLine(), pos.getColumn());
+ throw new ParsingException(pos, msg);
+ }
}
- String value = sign + year + "-" + month + "-" + dateAndHour + ":" + minutes + ":" + seconds + "." + subSeconds
- + tzSign + tzHours + tzDelim + tzMinutes;
- try {
- // Convert to a date and then back to a string to get canonical form ...
- DateTime dateTime = context.getValueFactories().getDateFactory().create(value);
- dateTime = dateTime.toUtcTimeZone();
- return stringFactory.create(dateTime);
- } catch (ValueFormatException e) {
- String msg = GraphI18n.expectingLiteralAndUnableToParseAsDate.text(value, pos.getLine(), pos.getColumn());
- throw new ParsingException(pos, msg);
- }
}
+ TypeFactory<Long> longFactory = typeSystem.getLongFactory();
// try to parse an a long ...
String value = sign + integral;
try {
// Convert to a long and then back to a string to get canonical form ...
- return stringFactory.create(context.getValueFactories().getLongFactory().create(value));
+ return longFactory.asString(longFactory.create(value));
} catch (ValueFormatException e) {
String msg = GraphI18n.expectingLiteralAndUnableToParseAsLong.text(value, pos.getLine(), pos.getColumn());
throw new ParsingException(pos, msg);
}
-
}
protected DynamicOperand parseDynamicOperand( TokenStream tokens,
- ExecutionContext context,
+ TypeSystem typeSystem,
Source source ) {
DynamicOperand result = null;
Position pos = tokens.nextPosition();
if (tokens.canConsume("LENGTH", "(")) {
- result = new Length(parsePropertyValue(tokens, context, source));
+ result = new Length(parsePropertyValue(tokens, typeSystem, source));
tokens.consume(")");
} else if (tokens.canConsume("LOWER", "(")) {
- result = new LowerCase(parseDynamicOperand(tokens, context, source));
+ result = new LowerCase(parseDynamicOperand(tokens, typeSystem, source));
tokens.consume(")");
} else if (tokens.canConsume("UPPER", "(")) {
- result = new UpperCase(parseDynamicOperand(tokens, context, source));
+ result = new UpperCase(parseDynamicOperand(tokens, typeSystem, source));
tokens.consume(")");
} else if (tokens.canConsume("NAME", "(")) {
if (tokens.canConsume(")")) {
@@ -1109,13 +1094,13 @@
result = new NodePath(parseSelectorName(tokens));
tokens.consume(")");
} else {
- result = parsePropertyValue(tokens, context, source);
+ result = parsePropertyValue(tokens, typeSystem, source);
}
return result;
}
protected PropertyValue parsePropertyValue( TokenStream tokens,
- ExecutionContext context,
+ TypeSystem typeSystem,
Source source ) {
Position pos = tokens.nextPosition();
String firstWord = removeBracketsAndQuotes(tokens.consume());
@@ -1123,13 +1108,13 @@
if (tokens.canConsume('.')) {
// We actually read the selector name, so now read the property name ...
selectorName = new SelectorName(firstWord);
- Name propertyName = parseName(tokens, context);
+ String propertyName = parseName(tokens, typeSystem);
return new PropertyValue(selectorName, propertyName);
}
// Otherwise the source should be a single named selector
if (source instanceof Selector) {
selectorName = ((Selector)source).getName();
- return new PropertyValue(selectorName, nameFrom(firstWord, pos, context));
+ return new PropertyValue(selectorName, firstWord);
}
String msg = GraphI18n.mustBeScopedAtLineAndColumn.text(firstWord, pos.getLine(), pos.getColumn());
throw new ParsingException(pos, msg);
@@ -1196,40 +1181,16 @@
return new SelectorName(removeBracketsAndQuotes(tokens.consume()));
}
- protected Path parsePath( TokenStream tokens,
- ExecutionContext context ) {
- return pathFrom(removeBracketsAndQuotes(tokens.consume()), tokens.previousPosition(), context);
+ protected String parsePath( TokenStream tokens,
+ TypeSystem typeSystem ) {
+ return removeBracketsAndQuotes(tokens.consume());
}
- protected Name parseName( TokenStream tokens,
- ExecutionContext context ) {
- return nameFrom(removeBracketsAndQuotes(tokens.consume()), tokens.previousPosition(), context);
+ protected String parseName( TokenStream tokens,
+ TypeSystem typeSystem ) {
+ return removeBracketsAndQuotes(tokens.consume());
}
- protected Path pathFrom( String name,
- Position position,
- ExecutionContext context ) {
- PathFactory pathFactory = context.getValueFactories().getPathFactory();
- try {
- return pathFactory.create(name);
- } catch (ValueFormatException e) {
- String msg = GraphI18n.expectingValidPathAtLineAndColumn.text(name, position.getLine(), position.getColumn());
- throw new ParsingException(position, msg);
- }
- }
-
- protected Name nameFrom( String name,
- Position position,
- ExecutionContext context ) {
- NameFactory nameFactory = context.getValueFactories().getNameFactory();
- try {
- return nameFactory.create(removeBracketsAndQuotes(name));
- } catch (ValueFormatException e) {
- String msg = GraphI18n.expectingValidNameAtLineAndColumn.text(name, position.getLine(), position.getColumn());
- throw new ParsingException(position, msg);
- }
- }
-
/**
* A {@link TokenStream.Tokenizer} implementation that parses words, quoted phrases, comments, and symbols. Words are
* delimited by whitespace and consist only of alpha-number characters plus the underscore character. Quoted phrases are
Modified: trunk/dna-graph/src/main/java/org/jboss/dna/graph/query/plan/CanonicalPlanner.java
===================================================================
--- trunk/dna-graph/src/main/java/org/jboss/dna/graph/query/plan/CanonicalPlanner.java 2009-11-24 17:44:29 UTC (rev 1339)
+++ trunk/dna-graph/src/main/java/org/jboss/dna/graph/query/plan/CanonicalPlanner.java 2009-11-24 17:46:37 UTC (rev 1340)
@@ -29,9 +29,6 @@
import java.util.List;
import java.util.Map;
import org.jboss.dna.graph.GraphI18n;
-import org.jboss.dna.graph.property.Name;
-import org.jboss.dna.graph.property.NameFactory;
-import org.jboss.dna.graph.property.ValueFactory;
import org.jboss.dna.graph.query.QueryContext;
import org.jboss.dna.graph.query.model.AllNodes;
import org.jboss.dna.graph.query.model.And;
@@ -223,8 +220,7 @@
}
node.setProperty(Property.SOURCE_COLUMNS, table.getColumns());
} else {
- context.getProblems().addError(GraphI18n.tableDoesNotExist,
- selector.getName().getString(context.getExecutionContext()));
+ context.getProblems().addError(GraphI18n.tableDoesNotExist, selector.getName());
}
return node;
}
@@ -395,20 +391,18 @@
if (columns.isEmpty()) {
columns = new LinkedList<Column>();
// SELECT *, so find all of the columns that are available from all the sources ...
- NameFactory nameFactory = context.getExecutionContext().getValueFactories().getNameFactory();
for (Table table : selectors.values()) {
// Add the selector that is being used ...
projectNode.addSelector(table.getName());
// Compute the columns from this selector ...
for (Schemata.Column column : table.getColumns()) {
String columnName = column.getName();
- Name propertyName = nameFactory.create(columnName);
+ String propertyName = columnName;
columns.add(new Column(table.getName(), propertyName, columnName));
}
}
} else {
// Add the selector used by each column ...
- ValueFactory<String> stringFactory = context.getExecutionContext().getValueFactories().getStringFactory();
for (Column column : columns) {
SelectorName tableName = column.getSelectorName();
// Add the selector that is being used ...
@@ -417,16 +411,13 @@
// Verify that each column is available in the appropriate source ...
Table table = selectors.get(tableName);
if (table == null) {
- context.getProblems().addError(GraphI18n.tableDoesNotExist,
- tableName.getString(context.getExecutionContext()));
+ context.getProblems().addError(GraphI18n.tableDoesNotExist, tableName);
} else {
// Make sure that the column is in the table ...
- Name columnName = column.getPropertyName();
- String name = stringFactory.create(columnName);
+ String columnName = column.getPropertyName();
+ String name = columnName;
if (table.getColumn(name) == null) {
- context.getProblems().addError(GraphI18n.columnDoesNotExistOnTable,
- name,
- tableName.getString(context.getExecutionContext()));
+ context.getProblems().addError(GraphI18n.columnDoesNotExistOnTable, name, tableName);
}
}
}
Modified: trunk/dna-graph/src/main/java/org/jboss/dna/graph/query/plan/PlanNode.java
===================================================================
--- trunk/dna-graph/src/main/java/org/jboss/dna/graph/query/plan/PlanNode.java 2009-11-24 17:44:29 UTC (rev 1339)
+++ trunk/dna-graph/src/main/java/org/jboss/dna/graph/query/plan/PlanNode.java 2009-11-24 17:46:37 UTC (rev 1340)
@@ -37,7 +37,6 @@
import net.jcip.annotations.NotThreadSafe;
import org.jboss.dna.common.util.CheckArg;
import org.jboss.dna.common.util.ObjectUtil;
-import org.jboss.dna.graph.ExecutionContext;
import org.jboss.dna.graph.query.model.Column;
import org.jboss.dna.graph.query.model.Constraint;
import org.jboss.dna.graph.query.model.JoinCondition;
@@ -915,7 +914,7 @@
*/
@Override
public String toString() {
- return getString(ExecutionContext.DEFAULT_CONTEXT);
+ return getString();
}
/**
@@ -980,30 +979,28 @@
/**
* {@inheritDoc}
*
- * @see org.jboss.dna.graph.query.model.Readable#getString(org.jboss.dna.graph.ExecutionContext)
+ * @see org.jboss.dna.graph.query.model.Readable#getString()
*/
- public String getString( ExecutionContext context ) {
+ public String getString() {
StringBuilder sb = new StringBuilder();
- getRecursiveString(context, sb, 0);
+ getRecursiveString(sb, 0);
return sb.toString();
}
- private void getRecursiveString( ExecutionContext context,
- StringBuilder str,
+ private void getRecursiveString( StringBuilder str,
int indentLevel ) {
for (int i = 0; i < indentLevel; ++i) {
str.append(" ");
}
- getNodeString(context, str).append('\n');
+ getNodeString(str).append('\n');
// Recursively add children at one greater tab level
for (PlanNode child : this) {
- child.getRecursiveString(context, str, indentLevel + 1);
+ child.getRecursiveString(str, indentLevel + 1);
}
}
- private StringBuilder getNodeString( ExecutionContext context,
- StringBuilder str ) {
+ private StringBuilder getNodeString( StringBuilder str ) {
str.append(this.type.getSymbol());
if (!selectors.isEmpty()) {
str.append(" [");
@@ -1024,7 +1021,7 @@
str.append(entry.getKey()).append('=');
Object value = entry.getValue();
if (value instanceof Visitable) {
- str.append(Visitors.readable((Visitable)value, context));
+ str.append(Visitors.readable((Visitable)value));
} else if (value instanceof Collection) {
boolean firstItem = true;
str.append('[');
@@ -1032,7 +1029,7 @@
if (firstItem) firstItem = false;
else str.append(", ");
if (item instanceof Visitable) {
- str.append(Visitors.readable((Visitable)item, context));
+ str.append(Visitors.readable((Visitable)item));
} else {
str.append(item);
}
Modified: trunk/dna-graph/src/main/java/org/jboss/dna/graph/query/plan/PlanUtil.java
===================================================================
--- trunk/dna-graph/src/main/java/org/jboss/dna/graph/query/plan/PlanUtil.java 2009-11-24 17:44:29 UTC (rev 1339)
+++ trunk/dna-graph/src/main/java/org/jboss/dna/graph/query/plan/PlanUtil.java 2009-11-24 17:46:37 UTC (rev 1340)
@@ -31,9 +31,6 @@
import java.util.List;
import java.util.Map;
import java.util.Set;
-import org.jboss.dna.graph.ExecutionContext;
-import org.jboss.dna.graph.property.Name;
-import org.jboss.dna.graph.property.ValueFactory;
import org.jboss.dna.graph.query.QueryContext;
import org.jboss.dna.graph.query.model.And;
import org.jboss.dna.graph.query.model.Between;
@@ -124,7 +121,7 @@
}
// Add the PROJECT columns first ...
- RequiredColumnVisitor collectionVisitor = new RequiredColumnVisitor(context.getExecutionContext(), names);
+ RequiredColumnVisitor collectionVisitor = new RequiredColumnVisitor(names);
if (columns != null) {
for (Column projectedColumn : columns) {
collectionVisitor.visit(projectedColumn);
@@ -157,15 +154,12 @@
}
protected static class RequiredColumnVisitor extends AbstractVisitor {
- private final ExecutionContext context;
private final Set<SelectorName> names;
private final List<Column> columns = new LinkedList<Column>();
- private final Set<Name> requiredColumnNames = new HashSet<Name>();
+ private final Set<String> requiredColumnNames = new HashSet<String>();
- protected RequiredColumnVisitor( ExecutionContext context,
- Set<SelectorName> names ) {
+ protected RequiredColumnVisitor( Set<SelectorName> names ) {
this.names = names;
- this.context = context;
}
/**
@@ -210,11 +204,11 @@
}
protected void requireColumn( SelectorName selector,
- Name propertyName ) {
+ String propertyName ) {
if (names.contains(selector)) {
// The column is part of the table we're interested in ...
if (requiredColumnNames.add(propertyName)) {
- String alias = context.getValueFactories().getStringFactory().create(propertyName);
+ String alias = propertyName;
columns.add(new Column(selector, propertyName, alias));
}
}
@@ -496,7 +490,6 @@
// Walk up the plan to change any references to the view columns into references to the source columns...
PlanNode node = topOfViewInPlan;
- ValueFactory<String> stringFactory = context.getExecutionContext().getValueFactories().getStringFactory();
List<PlanNode> potentiallyRemovableSources = new LinkedList<PlanNode>();
do {
// Remove the view from the selectors ...
@@ -510,7 +503,7 @@
Column column = columns.get(i);
if (column.getSelectorName().equals(viewName)) {
// This column references the view ...
- String columnName = stringFactory.create(column.getPropertyName());
+ String columnName = column.getPropertyName();
String columnAlias = column.getColumnName();
// Find the source column that this view column corresponds to ...
Column sourceColumn = mappings.getMappedColumn(columnName);
@@ -647,8 +640,7 @@
if (constraint instanceof PropertyExistence) {
PropertyExistence existence = (PropertyExistence)constraint;
if (!mapping.getOriginalName().equals(existence.getSelectorName())) return existence;
- ValueFactory<String> stringFactory = context.getExecutionContext().getValueFactories().getStringFactory();
- Column sourceColumn = mapping.getMappedColumn(stringFactory.create(existence.getPropertyName()));
+ Column sourceColumn = mapping.getMappedColumn(existence.getPropertyName());
if (sourceColumn == null) return existence;
node.addSelector(sourceColumn.getSelectorName());
return new PropertyExistence(sourceColumn.getSelectorName(), sourceColumn.getPropertyName());
@@ -656,8 +648,7 @@
if (constraint instanceof FullTextSearch) {
FullTextSearch search = (FullTextSearch)constraint;
if (!mapping.getOriginalName().equals(search.getSelectorName())) return search;
- ValueFactory<String> stringFactory = context.getExecutionContext().getValueFactories().getStringFactory();
- Column sourceColumn = mapping.getMappedColumn(stringFactory.create(search.getPropertyName()));
+ Column sourceColumn = mapping.getMappedColumn(search.getPropertyName());
if (sourceColumn == null) return search;
node.addSelector(sourceColumn.getSelectorName());
return new FullTextSearch(sourceColumn.getSelectorName(), sourceColumn.getPropertyName(),
@@ -722,8 +713,7 @@
if (operand instanceof PropertyValue) {
PropertyValue value = (PropertyValue)operand;
if (!mapping.getOriginalName().equals(value.getSelectorName())) return value;
- ValueFactory<String> stringFactory = context.getExecutionContext().getValueFactories().getStringFactory();
- Column sourceColumn = mapping.getMappedColumn(stringFactory.create(value.getPropertyName()));
+ Column sourceColumn = mapping.getMappedColumn(value.getPropertyName());
if (sourceColumn == null) return value;
node.addSelector(sourceColumn.getSelectorName());
return new PropertyValue(sourceColumn.getSelectorName(), sourceColumn.getPropertyName());
@@ -753,19 +743,17 @@
EquiJoinCondition condition = (EquiJoinCondition)joinCondition;
SelectorName replacement1 = condition.getSelector1Name();
SelectorName replacement2 = condition.getSelector2Name();
- Name property1 = condition.getProperty1Name();
- Name property2 = condition.getProperty2Name();
+ String property1 = condition.getProperty1Name();
+ String property2 = condition.getProperty2Name();
if (replacement1.equals(mapping.getOriginalName())) {
- ValueFactory<String> stringFactory = context.getExecutionContext().getValueFactories().getStringFactory();
- Column sourceColumn = mapping.getMappedColumn(stringFactory.create(property1));
+ Column sourceColumn = mapping.getMappedColumn(property1);
if (sourceColumn != null) {
replacement1 = sourceColumn.getSelectorName();
property1 = sourceColumn.getPropertyName();
}
}
if (replacement2.equals(mapping.getOriginalName())) {
- ValueFactory<String> stringFactory = context.getExecutionContext().getValueFactories().getStringFactory();
- Column sourceColumn = mapping.getMappedColumn(stringFactory.create(property2));
+ Column sourceColumn = mapping.getMappedColumn(property2);
if (sourceColumn != null) {
replacement2 = sourceColumn.getSelectorName();
property2 = sourceColumn.getPropertyName();
Modified: trunk/dna-graph/src/main/java/org/jboss/dna/graph/query/process/AbstractAccessComponent.java
===================================================================
--- trunk/dna-graph/src/main/java/org/jboss/dna/graph/query/process/AbstractAccessComponent.java 2009-11-24 17:44:29 UTC (rev 1339)
+++ trunk/dna-graph/src/main/java/org/jboss/dna/graph/query/process/AbstractAccessComponent.java 2009-11-24 17:46:37 UTC (rev 1340)
@@ -27,8 +27,6 @@
import java.util.Collections;
import java.util.List;
import org.jboss.dna.graph.Location;
-import org.jboss.dna.graph.property.Name;
-import org.jboss.dna.graph.property.NameFactory;
import org.jboss.dna.graph.query.QueryContext;
import org.jboss.dna.graph.query.QueryResults.Columns;
import org.jboss.dna.graph.query.model.AllNodes;
@@ -80,11 +78,10 @@
// Get the columns from the source columns ...
List<Schemata.Column> schemataColumns = source.getPropertyAsList(Property.SOURCE_COLUMNS, Schemata.Column.class);
this.projectedColumns = new ArrayList<Column>(schemataColumns.size());
- NameFactory nameFactory = context.getExecutionContext().getValueFactories().getNameFactory();
for (Schemata.Column schemataColumn : schemataColumns) {
String columnName = schemataColumn.getName();
// PropertyType type = schemataColumn.getPropertyType();
- Name propertyName = nameFactory.create(columnName);
+ String propertyName = columnName;
Column column = new Column(sourceName, propertyName, columnName);
this.projectedColumns.add(column);
}
Modified: trunk/dna-graph/src/main/java/org/jboss/dna/graph/query/process/JoinComponent.java
===================================================================
--- trunk/dna-graph/src/main/java/org/jboss/dna/graph/query/process/JoinComponent.java 2009-11-24 17:44:29 UTC (rev 1339)
+++ trunk/dna-graph/src/main/java/org/jboss/dna/graph/query/process/JoinComponent.java 2009-11-24 17:46:37 UTC (rev 1340)
@@ -27,11 +27,8 @@
import java.util.Comparator;
import java.util.List;
import org.jboss.dna.graph.Location;
-import org.jboss.dna.graph.property.Name;
import org.jboss.dna.graph.property.Path;
-import org.jboss.dna.graph.property.PropertyType;
import org.jboss.dna.graph.property.ValueComparators;
-import org.jboss.dna.graph.property.ValueFactory;
import org.jboss.dna.graph.query.QueryContext;
import org.jboss.dna.graph.query.QueryResults.Columns;
import org.jboss.dna.graph.query.model.ChildNodeJoinCondition;
@@ -42,6 +39,8 @@
import org.jboss.dna.graph.query.model.JoinType;
import org.jboss.dna.graph.query.model.SameNodeJoinCondition;
import org.jboss.dna.graph.query.model.SelectorName;
+import org.jboss.dna.graph.query.model.TypeSystem;
+import org.jboss.dna.graph.query.model.TypeSystem.TypeFactory;
import org.jboss.dna.graph.query.validate.Schemata;
/**
@@ -166,8 +165,7 @@
/**
* {@inheritDoc}
*
- * @see org.jboss.dna.graph.query.process.JoinComponent.TupleMerger#merge(java.lang.Object[],
- * java.lang.Object[])
+ * @see org.jboss.dna.graph.query.process.JoinComponent.TupleMerger#merge(java.lang.Object[], java.lang.Object[])
*/
public Object[] merge( Object[] leftTuple,
Object[] rightTuple ) {
@@ -275,12 +273,12 @@
} else if (condition instanceof EquiJoinCondition) {
EquiJoinCondition joinCondition = (EquiJoinCondition)condition;
SelectorName selector1Name = joinCondition.getSelector1Name();
- Name propName1 = joinCondition.getProperty1Name();
+ String propName1 = joinCondition.getProperty1Name();
if (source.getColumns().hasSelector(selector1Name.getName())) {
return selectValue(source, selector1Name, propName1);
}
SelectorName selector2Name = joinCondition.getSelector2Name();
- Name propName2 = joinCondition.getProperty2Name();
+ String propName2 = joinCondition.getProperty2Name();
return selectValue(source, selector2Name, propName2);
}
throw new IllegalArgumentException();
@@ -299,7 +297,7 @@
private static ValueSelector selectValue( ProcessingComponent component,
SelectorName selectorName,
- Name propertyName ) {
+ String propertyName ) {
final int index = component.getColumns().getColumnIndexForProperty(selectorName.getName(), propertyName);
return new ValueSelector() {
public Object evaluate( Object[] tuple ) {
@@ -457,20 +455,26 @@
EquiJoinCondition joinCondition = (EquiJoinCondition)condition;
SelectorName leftSelectorName = joinCondition.getSelector1Name();
SelectorName rightSelectorName = joinCondition.getSelector2Name();
- Name leftPropertyName = joinCondition.getProperty1Name();
- Name rightPropertyName = joinCondition.getProperty2Name();
+ String leftPropertyName = joinCondition.getProperty1Name();
+ String rightPropertyName = joinCondition.getProperty2Name();
- ValueFactory<String> stringFactory = context.getExecutionContext().getValueFactories().getStringFactory();
Schemata schemata = context.getSchemata();
Schemata.Table leftTable = schemata.getTable(leftSelectorName);
- Schemata.Column leftColumn = leftTable.getColumn(stringFactory.create(leftPropertyName));
- PropertyType leftType = leftColumn.getPropertyType();
+ Schemata.Column leftColumn = leftTable.getColumn(leftPropertyName);
+ String leftType = leftColumn.getPropertyType();
Schemata.Table rightTable = schemata.getTable(rightSelectorName);
- Schemata.Column rightColumn = rightTable.getColumn(stringFactory.create(rightPropertyName));
- PropertyType rightType = rightColumn.getPropertyType();
+ Schemata.Column rightColumn = rightTable.getColumn(rightPropertyName);
+ String rightType = rightColumn.getPropertyType();
- return leftType == rightType ? (Comparator<Object>)leftType.getComparator() : ValueComparators.OBJECT_COMPARATOR;
+ TypeSystem typeSystem = context.getTypeSystem();
+ if (leftType.equals(rightType)) {
+ TypeFactory<?> typeFactory = typeSystem.getTypeFactory(leftType);
+ if (typeFactory != null) {
+ return (Comparator<Object>)typeFactory.getComparator();
+ }
+ }
+ return typeSystem.getDefaultComparator();
}
throw new IllegalArgumentException();
}
Modified: trunk/dna-graph/src/main/java/org/jboss/dna/graph/query/process/ProcessingComponent.java
===================================================================
--- trunk/dna-graph/src/main/java/org/jboss/dna/graph/query/process/ProcessingComponent.java 2009-11-24 17:44:29 UTC (rev 1339)
+++ trunk/dna-graph/src/main/java/org/jboss/dna/graph/query/process/ProcessingComponent.java 2009-11-24 17:46:37 UTC (rev 1340)
@@ -29,11 +29,7 @@
import net.jcip.annotations.NotThreadSafe;
import org.jboss.dna.common.collection.Problems;
import org.jboss.dna.graph.Location;
-import org.jboss.dna.graph.property.Binary;
-import org.jboss.dna.graph.property.Name;
import org.jboss.dna.graph.property.Path;
-import org.jboss.dna.graph.property.PropertyType;
-import org.jboss.dna.graph.property.ValueFactory;
import org.jboss.dna.graph.query.QueryContext;
import org.jboss.dna.graph.query.QueryResults.Columns;
import org.jboss.dna.graph.query.model.DynamicOperand;
@@ -45,7 +41,9 @@
import org.jboss.dna.graph.query.model.NodeName;
import org.jboss.dna.graph.query.model.NodePath;
import org.jboss.dna.graph.query.model.PropertyValue;
+import org.jboss.dna.graph.query.model.TypeSystem;
import org.jboss.dna.graph.query.model.UpperCase;
+import org.jboss.dna.graph.query.model.TypeSystem.TypeFactory;
import org.jboss.dna.graph.query.validate.Schemata.Column;
import org.jboss.dna.graph.query.validate.Schemata.Table;
@@ -126,7 +124,7 @@
*
* @return the property type; never null
*/
- PropertyType getExpectedType();
+ String getExpectedType();
/**
* Perform the dynamic evaluation to obtain the desired result.
@@ -151,18 +149,17 @@
assert operand != null;
assert columns != null;
assert context != null;
- final ValueFactory<String> stringFactory = context.getExecutionContext().getValueFactories().getStringFactory();
if (operand instanceof PropertyValue) {
PropertyValue propValue = (PropertyValue)operand;
- Name propertyName = propValue.getPropertyName();
+ String propertyName = propValue.getPropertyName();
String selectorName = propValue.getSelectorName().getName();
final int index = columns.getColumnIndexForProperty(selectorName, propertyName);
// Find the expected property type of the value ...
Table table = context.getSchemata().getTable(propValue.getSelectorName());
- Column schemaColumn = table.getColumn(stringFactory.create(propertyName));
- final PropertyType expectedType = schemaColumn.getPropertyType();
+ Column schemaColumn = table.getColumn(propertyName);
+ final String expectedType = schemaColumn.getPropertyType();
return new DynamicOperation() {
- public PropertyType getExpectedType() {
+ public String getExpectedType() {
return expectedType;
}
@@ -171,25 +168,27 @@
}
};
}
+ final TypeSystem typeSystem = context.getTypeSystem();
+ final TypeFactory<String> stringFactory = typeSystem.getStringFactory();
if (operand instanceof Length) {
Length length = (Length)operand;
PropertyValue value = length.getPropertyValue();
- Name propertyName = value.getPropertyName();
+ String propertyName = value.getPropertyName();
String selectorName = value.getSelectorName().getName();
final int index = columns.getColumnIndexForProperty(selectorName, propertyName);
+ // Find the expected property type of the value ...
+ Table table = context.getSchemata().getTable(value.getSelectorName());
+ Column schemaColumn = table.getColumn(propertyName);
+ final String expectedType = schemaColumn.getPropertyType();
+ final TypeFactory<?> typeFactory = typeSystem.getTypeFactory(expectedType);
return new DynamicOperation() {
- public PropertyType getExpectedType() {
- return PropertyType.LONG; // length is always LONG
+ public String getExpectedType() {
+ return typeSystem.getLongFactory().getTypeName(); // length is always LONG
}
public Object evaluate( Object[] tuple ) {
Object value = tuple[index];
- // Determine the length ...
- if (value instanceof Binary) {
- return ((Binary)value).getStream();
- }
- String result = stringFactory.create(value);
- return result != null ? result.length() : null;
+ return typeFactory.length(typeFactory.create(value));
}
};
}
@@ -197,8 +196,8 @@
LowerCase lowerCase = (LowerCase)operand;
final DynamicOperation delegate = createDynamicOperation(context, columns, lowerCase.getOperand());
return new DynamicOperation() {
- public PropertyType getExpectedType() {
- return PropertyType.STRING;
+ public String getExpectedType() {
+ return stringFactory.getTypeName();
}
public Object evaluate( Object[] tuple ) {
@@ -211,8 +210,8 @@
UpperCase upperCase = (UpperCase)operand;
final DynamicOperation delegate = createDynamicOperation(context, columns, upperCase.getOperand());
return new DynamicOperation() {
- public PropertyType getExpectedType() {
- return PropertyType.STRING;
+ public String getExpectedType() {
+ return stringFactory.getTypeName();
}
public Object evaluate( Object[] tuple ) {
@@ -225,8 +224,8 @@
NodeDepth nodeDepth = (NodeDepth)operand;
final int locationIndex = columns.getLocationIndex(nodeDepth.getSelectorName().getName());
return new DynamicOperation() {
- public PropertyType getExpectedType() {
- return PropertyType.LONG;
+ public String getExpectedType() {
+ return typeSystem.getLongFactory().getTypeName(); // depth is always LONG
}
public Object evaluate( Object[] tuple ) {
@@ -242,16 +241,15 @@
NodePath nodePath = (NodePath)operand;
final int locationIndex = columns.getLocationIndex(nodePath.getSelectorName().getName());
return new DynamicOperation() {
- public PropertyType getExpectedType() {
- return PropertyType.PATH;
+ public String getExpectedType() {
+ return stringFactory.getTypeName();
}
public Object evaluate( Object[] tuple ) {
Location location = (Location)tuple[locationIndex];
if (location == null) return null;
- Path path = location.getPath();
- assert path != null;
- return path;
+ assert location.getPath() != null;
+ return stringFactory.create(location.getPath());
}
};
}
@@ -259,8 +257,8 @@
NodeName nodeName = (NodeName)operand;
final int locationIndex = columns.getLocationIndex(nodeName.getSelectorName().getName());
return new DynamicOperation() {
- public PropertyType getExpectedType() {
- return PropertyType.STRING;
+ public String getExpectedType() {
+ return stringFactory.getTypeName();
}
public Object evaluate( Object[] tuple ) {
@@ -276,8 +274,8 @@
NodeLocalName nodeName = (NodeLocalName)operand;
final int locationIndex = columns.getLocationIndex(nodeName.getSelectorName().getName());
return new DynamicOperation() {
- public PropertyType getExpectedType() {
- return PropertyType.STRING;
+ public String getExpectedType() {
+ return stringFactory.getTypeName();
}
public Object evaluate( Object[] tuple ) {
@@ -296,8 +294,8 @@
if (index < 0) {
// No full-text search score for this selector, so return 0.0d;
return new DynamicOperation() {
- public PropertyType getExpectedType() {
- return PropertyType.DOUBLE;
+ public String getExpectedType() {
+ return typeSystem.getDoubleFactory().getTypeName();
}
public Object evaluate( Object[] tuple ) {
@@ -306,8 +304,8 @@
};
}
return new DynamicOperation() {
- public PropertyType getExpectedType() {
- return PropertyType.DOUBLE;
+ public String getExpectedType() {
+ return typeSystem.getDoubleFactory().getTypeName();
}
public Object evaluate( Object[] tuple ) {
Modified: trunk/dna-graph/src/main/java/org/jboss/dna/graph/query/process/QueryResultColumns.java
===================================================================
--- trunk/dna-graph/src/main/java/org/jboss/dna/graph/query/process/QueryResultColumns.java 2009-11-24 17:44:29 UTC (rev 1339)
+++ trunk/dna-graph/src/main/java/org/jboss/dna/graph/query/process/QueryResultColumns.java 2009-11-24 17:46:37 UTC (rev 1340)
@@ -35,7 +35,6 @@
import net.jcip.annotations.Immutable;
import org.jboss.dna.graph.GraphI18n;
import org.jboss.dna.graph.Location;
-import org.jboss.dna.graph.property.Name;
import org.jboss.dna.graph.query.QueryResults.Columns;
import org.jboss.dna.graph.query.model.Column;
@@ -66,7 +65,7 @@
private final Map<String, Integer> locationIndexBySelectorName;
private final Map<String, Integer> locationIndexByColumnName;
private final Map<Integer, Integer> locationIndexByColumnIndex;
- private final Map<String, Map<Name, Integer>> columnIndexByPropertyNameBySelectorName;
+ private final Map<String, Map<String, Integer>> columnIndexByPropertyNameBySelectorName;
private final Map<String, Integer> fullTextSearchScoreIndexBySelectorName;
/**
@@ -88,7 +87,7 @@
this.locationIndexBySelectorName = new HashMap<String, Integer>();
this.locationIndexByColumnIndex = new HashMap<Integer, Integer>();
this.locationIndexByColumnName = new HashMap<String, Integer>();
- this.columnIndexByPropertyNameBySelectorName = new HashMap<String, Map<Name, Integer>>();
+ this.columnIndexByPropertyNameBySelectorName = new HashMap<String, Map<String, Integer>>();
List<String> selectorNames = new ArrayList<String>(columnCount);
List<String> names = new ArrayList<String>(columnCount);
for (int i = 0, max = this.columns.size(); i != max; ++i) {
@@ -110,9 +109,9 @@
locationIndexByColumnIndex.put(new Integer(i), selectorIndex);
locationIndexByColumnName.put(columnName, selectorIndex);
// Insert the entry by selector name and property name ...
- Map<Name, Integer> byPropertyName = columnIndexByPropertyNameBySelectorName.get(selectorName);
+ Map<String, Integer> byPropertyName = columnIndexByPropertyNameBySelectorName.get(selectorName);
if (byPropertyName == null) {
- byPropertyName = new HashMap<Name, Integer>();
+ byPropertyName = new HashMap<String, Integer>();
columnIndexByPropertyNameBySelectorName.put(selectorName, byPropertyName);
}
byPropertyName.put(column.getPropertyName(), new Integer(i));
@@ -159,7 +158,7 @@
this.locationIndexBySelectorName = new HashMap<String, Integer>();
this.locationIndexByColumnIndex = new HashMap<Integer, Integer>();
this.locationIndexByColumnName = new HashMap<String, Integer>();
- this.columnIndexByPropertyNameBySelectorName = new HashMap<String, Map<Name, Integer>>();
+ this.columnIndexByPropertyNameBySelectorName = new HashMap<String, Map<String, Integer>>();
this.selectorNames = new ArrayList<String>(columns.size());
List<String> names = new ArrayList<String>(columns.size());
for (int i = 0, max = this.columns.size(); i != max; ++i) {
@@ -180,9 +179,9 @@
locationIndexByColumnIndex.put(new Integer(0), selectorIndex);
locationIndexByColumnName.put(columnName, selectorIndex);
// Insert the entry by selector name and property name ...
- Map<Name, Integer> byPropertyName = columnIndexByPropertyNameBySelectorName.get(selectorName);
+ Map<String, Integer> byPropertyName = columnIndexByPropertyNameBySelectorName.get(selectorName);
if (byPropertyName == null) {
- byPropertyName = new HashMap<Name, Integer>();
+ byPropertyName = new HashMap<String, Integer>();
columnIndexByPropertyNameBySelectorName.put(selectorName, byPropertyName);
}
byPropertyName.put(column.getPropertyName(), columnIndex);
@@ -336,7 +335,7 @@
*
* @see org.jboss.dna.graph.query.QueryResults.Columns#getPropertyNameForColumn(int)
*/
- public Name getPropertyNameForColumn( int columnIndex ) {
+ public String getPropertyNameForColumn( int columnIndex ) {
return columns.get(columnIndex).getPropertyName();
}
@@ -345,7 +344,7 @@
*
* @see org.jboss.dna.graph.query.QueryResults.Columns#getPropertyNameForColumn(java.lang.String)
*/
- public Name getPropertyNameForColumn( String columnName ) {
+ public String getPropertyNameForColumn( String columnName ) {
Column result = columnsByName.get(columnName);
if (result == null) {
throw new NoSuchElementException(GraphI18n.columnDoesNotExistInQuery.text(columnName));
@@ -369,12 +368,11 @@
/**
* {@inheritDoc}
*
- * @see org.jboss.dna.graph.query.QueryResults.Columns#getColumnIndexForProperty(java.lang.String,
- * org.jboss.dna.graph.property.Name)
+ * @see org.jboss.dna.graph.query.QueryResults.Columns#getColumnIndexForProperty(java.lang.String, java.lang.String)
*/
public int getColumnIndexForProperty( String selectorName,
- Name propertyName ) {
- Map<Name, Integer> byPropertyName = columnIndexByPropertyNameBySelectorName.get(selectorName);
+ String propertyName ) {
+ Map<String, Integer> byPropertyName = columnIndexByPropertyNameBySelectorName.get(selectorName);
if (byPropertyName == null) {
throw new NoSuchElementException(GraphI18n.selectorDoesNotExistInQuery.text(selectorName));
}
Modified: trunk/dna-graph/src/main/java/org/jboss/dna/graph/query/process/QueryResults.java
===================================================================
--- trunk/dna-graph/src/main/java/org/jboss/dna/graph/query/process/QueryResults.java 2009-11-24 17:44:29 UTC (rev 1339)
+++ trunk/dna-graph/src/main/java/org/jboss/dna/graph/query/process/QueryResults.java 2009-11-24 17:46:37 UTC (rev 1340)
@@ -29,14 +29,12 @@
import net.jcip.annotations.Immutable;
import org.jboss.dna.common.collection.Problems;
import org.jboss.dna.common.util.StringUtil;
-import org.jboss.dna.graph.ExecutionContext;
import org.jboss.dna.graph.GraphI18n;
import org.jboss.dna.graph.Location;
-import org.jboss.dna.graph.property.Binary;
-import org.jboss.dna.graph.property.ValueFactory;
import org.jboss.dna.graph.query.QueryContext;
import org.jboss.dna.graph.query.model.QueryCommand;
-import com.sun.org.apache.xerces.internal.impl.dv.util.Base64;
+import org.jboss.dna.graph.query.model.TypeSystem;
+import org.jboss.dna.graph.query.model.TypeSystem.TypeFactory;
/**
* The resulting output of a query.
@@ -93,10 +91,10 @@
/**
* {@inheritDoc}
*
- * @see org.jboss.dna.graph.query.QueryResults#getContext()
+ * @see org.jboss.dna.graph.query.QueryResults#getTypeSystem()
*/
- public ExecutionContext getContext() {
- return context.getExecutionContext();
+ public TypeSystem getTypeSystem() {
+ return context.getTypeSystem();
}
/**
@@ -219,12 +217,11 @@
*/
public void toString( StringBuilder sb,
int maxTuples ) {
- ValueFactory<String> stringFactory = context.getExecutionContext().getValueFactories().getStringFactory();
- int[] columnWidths = determineColumnWidths(Integer.MAX_VALUE, true, stringFactory);
+ int[] columnWidths = determineColumnWidths(Integer.MAX_VALUE, true);
printDelimiterLine(sb, columnWidths, true);
printHeader(sb, columnWidths);
printDelimiterLine(sb, columnWidths, true);
- printLines(sb, columnWidths, stringFactory, maxTuples);
+ printLines(sb, columnWidths, maxTuples);
printDelimiterLine(sb, columnWidths, false);
}
@@ -233,12 +230,10 @@
*
* @param maxWidth the maximum width; must be positive
* @param useData true if the data should be used to compute the length, or false if just the column names should be used
- * @param stringFactory the value factory for creating strings; may not be null
* @return the array of widths for each column, excluding any decorating characters; never null
*/
protected int[] determineColumnWidths( int maxWidth,
- boolean useData,
- ValueFactory<String> stringFactory ) {
+ boolean useData ) {
assert maxWidth > 0;
int tupleLength = columns.getTupleSize();
int[] columnWidths = new int[tupleLength + 1]; // +1 for the row number column
@@ -246,7 +241,7 @@
columnWidths[i] = 0;
}
// Determine the width of the first column that shows the row number ...
- String rowNumber = stringFactory.create(getTuples().size());
+ String rowNumber = Integer.toString(getTuples().size());
columnWidths[0] = rowNumber.length();
// Compute the column names ...
@@ -259,7 +254,7 @@
if (useData) {
for (Object[] tuple : getTuples()) {
for (int i = 0, j = 1; i != tupleLength; ++i, ++j) {
- String valueStr = stringOf(tuple[i], stringFactory);
+ String valueStr = stringOf(tuple[i]);
if (valueStr == null) continue;
columnWidths[j] = Math.max(Math.min(maxWidth, valueStr.length()), columnWidths[j]);
}
@@ -268,14 +263,10 @@
return columnWidths;
}
- protected String stringOf( Object value,
- ValueFactory<String> stringFactory ) {
- if (value instanceof Binary) {
- // Just print out the SHA-1 hash in Base64, plus length
- Binary binary = (Binary)value;
- return "(Binary,length=" + binary.getSize() + ",SHA1=" + Base64.encode(binary.getHash()) + ")";
- }
- return stringFactory.create(value);
+ protected String stringOf( Object value ) {
+ if (value == null) return null;
+ TypeFactory<?> typeFactory = context.getTypeSystem().getTypeFactory(value);
+ return typeFactory.asReadableString(value);
}
protected void printHeader( StringBuilder sb,
@@ -296,7 +287,6 @@
protected void printLines( StringBuilder sb,
int[] columnWidths,
- ValueFactory<String> stringFactory,
int maxRowsToPrint ) {
int rowNumber = 1;
int tupleLength = columns.getTupleSize();
@@ -304,13 +294,13 @@
if (maxRowsToPrint > tuples.size()) {
// Print all tuples ...
for (Object[] tuple : getTuples()) {
- printTuple(sb, columnWidths, stringFactory, rowNumber, tupleLength, tuple);
+ printTuple(sb, columnWidths, rowNumber, tupleLength, tuple);
++rowNumber;
}
} else {
// Print max number of rows ...
for (Object[] tuple : getTuples()) {
- printTuple(sb, columnWidths, stringFactory, rowNumber, tupleLength, tuple);
+ printTuple(sb, columnWidths, rowNumber, tupleLength, tuple);
if (rowNumber >= maxRowsToPrint) break;
++rowNumber;
}
@@ -321,14 +311,12 @@
/**
* @param sb
* @param columnWidths
- * @param stringFactory
* @param rowNumber
* @param tupleLength
* @param tuple
*/
private final void printTuple( StringBuilder sb,
int[] columnWidths,
- ValueFactory<String> stringFactory,
int rowNumber,
int tupleLength,
Object[] tuple ) {
@@ -336,7 +324,7 @@
sb.append("| ").append(StringUtil.justifyLeft(Integer.toString(rowNumber), columnWidths[0], ' ')).append(' ');
// Print the remaining columns ...
for (int i = 0, j = 1; i != tupleLength; ++i, ++j) {
- String valueStr = stringOf(tuple[i], stringFactory);
+ String valueStr = stringOf(tuple[i]);
valueStr = StringUtil.justifyLeft(valueStr, columnWidths[j], ' ');
sb.append('|').append(' ').append(valueStr).append(' ');
}
Modified: trunk/dna-graph/src/main/java/org/jboss/dna/graph/query/process/SelectComponent.java
===================================================================
--- trunk/dna-graph/src/main/java/org/jboss/dna/graph/query/process/SelectComponent.java 2009-11-24 17:44:29 UTC (rev 1339)
+++ trunk/dna-graph/src/main/java/org/jboss/dna/graph/query/process/SelectComponent.java 2009-11-24 17:46:37 UTC (rev 1340)
@@ -30,10 +30,6 @@
import java.util.Map;
import java.util.regex.Pattern;
import org.jboss.dna.graph.Location;
-import org.jboss.dna.graph.property.Name;
-import org.jboss.dna.graph.property.Path;
-import org.jboss.dna.graph.property.PropertyType;
-import org.jboss.dna.graph.property.ValueFactory;
import org.jboss.dna.graph.query.QueryContext;
import org.jboss.dna.graph.query.QueryResults.Columns;
import org.jboss.dna.graph.query.model.And;
@@ -50,6 +46,8 @@
import org.jboss.dna.graph.query.model.PropertyExistence;
import org.jboss.dna.graph.query.model.SameNode;
import org.jboss.dna.graph.query.model.StaticOperand;
+import org.jboss.dna.graph.query.model.TypeSystem;
+import org.jboss.dna.graph.query.model.TypeSystem.TypeFactory;
/**
*/
@@ -147,6 +145,9 @@
* @see SelectComponent#SelectComponent(ProcessingComponent, Constraint, Map, Analyzer)
*/
public static interface Analyzer {
+
+ int length( Object value );
+
/**
* Determine whether the node specified by the location is the same node as that supplied by the path. This determines if
* the nodes at the supplied location and path are the same node.
@@ -156,9 +157,19 @@
* @return true if the node given by the {@link Location} is also accessible at the supplied path, or false otherwise
*/
boolean isSameNode( Location location,
- Path accessibleAtPath );
+ String accessibleAtPath );
/**
+ * Determine whether the node specified by the location is a descendant of that supplied by the path.
+ *
+ * @param location the location of the node; never null
+ * @param ancestorPath the path of the ancestor node
+ * @return true if the node given by the {@link Location} is also accessible at the supplied path, or false otherwise
+ */
+ boolean isDescendantOf( Location location,
+ String ancestorPath );
+
+ /**
* Determine whether the node at the supplied location has the named property.
*
* @param location the location of the node; never null
@@ -166,7 +177,7 @@
* @return true if the node at the supplied {@link Location} does contain the property, or false if it does not
*/
boolean hasProperty( Location location,
- Name propertyName );
+ String propertyName );
/**
* Determine whether the node at the supplied location satisfies the supplied full-text query.
@@ -187,7 +198,7 @@
* @return the full-text search score of the node, or 0.0d if the node does not satisfy the full-text query
*/
double hasFullText( Location location,
- Name propertyName,
+ String propertyName,
String fullTextQuery );
}
@@ -258,7 +269,7 @@
if (constraint instanceof ChildNode) {
ChildNode childConstraint = (ChildNode)constraint;
final int locationIndex = columns.getLocationIndex(childConstraint.getSelectorName().getName());
- final Path parentPath = childConstraint.getParentPath();
+ final String parentPath = childConstraint.getParentPath();
return new ConstraintChecker() {
public boolean satisfiesConstraints( Object[] tuple ) {
Location location = (Location)tuple[locationIndex];
@@ -270,19 +281,19 @@
if (constraint instanceof DescendantNode) {
DescendantNode descendantNode = (DescendantNode)constraint;
final int locationIndex = columns.getLocationIndex(descendantNode.getSelectorName().getName());
- final Path ancestorPath = descendantNode.getAncestorPath();
+ final String ancestorPath = descendantNode.getAncestorPath();
return new ConstraintChecker() {
public boolean satisfiesConstraints( Object[] tuple ) {
Location location = (Location)tuple[locationIndex];
assert location.hasPath();
- return location.getPath().isDecendantOf(ancestorPath);
+ return analyzer.isDescendantOf(location, ancestorPath);
}
};
}
if (constraint instanceof SameNode) {
SameNode sameNode = (SameNode)constraint;
final int locationIndex = columns.getLocationIndex(sameNode.getSelectorName().getName());
- final Path path = sameNode.getPath();
+ final String path = sameNode.getPath();
if (analyzer != null) {
return new ConstraintChecker() {
public boolean satisfiesConstraints( Object[] tuple ) {
@@ -295,14 +306,14 @@
public boolean satisfiesConstraints( Object[] tuple ) {
Location location = (Location)tuple[locationIndex];
assert location.hasPath();
- return location.getPath().isSameAs(path);
+ return location.toString().equals(path);
}
};
}
if (constraint instanceof PropertyExistence) {
PropertyExistence propertyExistance = (PropertyExistence)constraint;
String selectorName = propertyExistance.getSelectorName().getName();
- final Name propertyName = propertyExistance.getPropertyName();
+ final String propertyName = propertyExistance.getPropertyName();
if (analyzer != null) {
final int locationIndex = columns.getLocationIndex(selectorName);
return new ConstraintChecker() {
@@ -332,7 +343,7 @@
}
};
}
- final Name propertyName = search.getPropertyName(); // may be null
+ final String propertyName = search.getPropertyName(); // may be null
final int scoreIndex = columns.getFullTextSearchScoreIndexFor(selectorName);
assert scoreIndex >= 0 : "Columns do not have room for the search scores";
if (propertyName != null) {
@@ -373,12 +384,11 @@
};
}
if (constraint instanceof Comparison) {
- final ValueFactory<String> stringFactory = context.getExecutionContext().getValueFactories().getStringFactory();
Comparison comparison = (Comparison)constraint;
// Create the correct dynamic operation ...
final DynamicOperation dynamicOperation = createDynamicOperation(context, columns, comparison.getOperand1());
- final PropertyType expectedType = dynamicOperation.getExpectedType();
+ final String expectedType = dynamicOperation.getExpectedType();
// Determine the literal value ...
StaticOperand staticOperand = comparison.getOperand2();
@@ -392,9 +402,13 @@
literalValue = literal.getValue();
}
// Create the correct comparator ...
- final Comparator<Object> comparator = (Comparator<Object>)expectedType.getComparator();
+ final TypeSystem typeSystem = context.getTypeSystem();
+ final TypeFactory<?> typeFactory = typeSystem.getTypeFactory(expectedType);
+ assert typeFactory != null;
+ final Comparator<Object> comparator = (Comparator<Object>)typeFactory.getComparator();
+ assert comparator != null;
// Create the correct operation ...
- ValueFactory<?> literalFactory = context.getExecutionContext().getValueFactories().getValueFactory(expectedType);
+ final TypeFactory<?> literalFactory = typeSystem.getTypeFactory(expectedType);
final Object rhs = literalFactory.create(literalValue);
switch (comparison.getOperator()) {
case EQUAL_TO:
@@ -435,12 +449,12 @@
};
case LIKE:
// Convert the LIKE expression to a regular expression
- final Pattern pattern = createRegexFromLikeExpression(stringFactory.create(rhs));
+ final Pattern pattern = createRegexFromLikeExpression(typeSystem.asString(rhs));
return new ConstraintChecker() {
public boolean satisfiesConstraints( Object[] tuples ) {
Object tupleValue = dynamicOperation.evaluate(tuples);
if (tupleValue == null) return false;
- String value = stringFactory.create(tupleValue);
+ String value = typeSystem.asString(tupleValue);
return pattern.matcher(value).matches();
}
};
Modified: trunk/dna-graph/src/main/java/org/jboss/dna/graph/query/process/SortValuesComponent.java
===================================================================
--- trunk/dna-graph/src/main/java/org/jboss/dna/graph/query/process/SortValuesComponent.java 2009-11-24 17:44:29 UTC (rev 1339)
+++ trunk/dna-graph/src/main/java/org/jboss/dna/graph/query/process/SortValuesComponent.java 2009-11-24 17:46:37 UTC (rev 1340)
@@ -31,6 +31,8 @@
import org.jboss.dna.graph.query.QueryResults.Columns;
import org.jboss.dna.graph.query.model.Order;
import org.jboss.dna.graph.query.model.Ordering;
+import org.jboss.dna.graph.query.model.TypeSystem;
+import org.jboss.dna.graph.query.model.TypeSystem.TypeFactory;
import org.jboss.dna.graph.query.plan.PlanNode.Type;
/**
@@ -105,7 +107,11 @@
assert context != null;
assert ordering != null;
final DynamicOperation operation = createDynamicOperation(context, columns, ordering.getOperand());
- final Comparator<Object> typeComparator = (Comparator<Object>)operation.getExpectedType().getComparator();
+ final TypeSystem typeSystem = context.getTypeSystem();
+ final TypeFactory<?> typeFactory = typeSystem.getTypeFactory(operation.getExpectedType());
+ assert typeFactory != null;
+ final Comparator<Object> typeComparator = (Comparator<Object>)typeFactory.getComparator();
+ assert typeComparator != null;
if (ordering.getOrder() == Order.DESCENDING) {
return new Comparator<Object[]>() {
public int compare( Object[] tuple1,
Modified: trunk/dna-graph/src/main/java/org/jboss/dna/graph/query/validate/ImmutableColumn.java
===================================================================
--- trunk/dna-graph/src/main/java/org/jboss/dna/graph/query/validate/ImmutableColumn.java 2009-11-24 17:44:29 UTC (rev 1339)
+++ trunk/dna-graph/src/main/java/org/jboss/dna/graph/query/validate/ImmutableColumn.java 2009-11-24 17:46:37 UTC (rev 1340)
@@ -24,7 +24,6 @@
package org.jboss.dna.graph.query.validate;
import net.jcip.annotations.Immutable;
-import org.jboss.dna.graph.property.PropertyType;
import org.jboss.dna.graph.query.validate.Schemata.Column;
@Immutable
@@ -34,19 +33,21 @@
private final boolean fullTextSearchable;
private final String name;
- private final PropertyType type;
+ private final String type;
protected ImmutableColumn( String name,
- PropertyType type ) {
+ String type ) {
this(name, type, DEFAULT_FULL_TEXT_SEARCHABLE);
}
protected ImmutableColumn( String name,
- PropertyType type,
+ String type,
boolean fullTextSearchable ) {
this.name = name;
- this.type = type != null ? type : PropertyType.STRING;
+ this.type = type;
this.fullTextSearchable = fullTextSearchable;
+ assert this.name != null;
+ assert this.type != null;
}
/**
@@ -63,7 +64,7 @@
*
* @see org.jboss.dna.graph.query.validate.Schemata.Column#getPropertyType()
*/
- public PropertyType getPropertyType() {
+ public String getPropertyType() {
return type;
}
@@ -83,6 +84,6 @@
*/
@Override
public String toString() {
- return this.name + "(" + type.getName() + ")";
+ return this.name + "(" + type + ")";
}
}
Modified: trunk/dna-graph/src/main/java/org/jboss/dna/graph/query/validate/ImmutableSchemata.java
===================================================================
--- trunk/dna-graph/src/main/java/org/jboss/dna/graph/query/validate/ImmutableSchemata.java 2009-11-24 17:44:29 UTC (rev 1339)
+++ trunk/dna-graph/src/main/java/org/jboss/dna/graph/query/validate/ImmutableSchemata.java 2009-11-24 17:46:37 UTC (rev 1340)
@@ -34,13 +34,11 @@
import net.jcip.annotations.NotThreadSafe;
import org.jboss.dna.common.text.ParsingException;
import org.jboss.dna.common.util.CheckArg;
-import org.jboss.dna.graph.ExecutionContext;
import org.jboss.dna.graph.GraphI18n;
-import org.jboss.dna.graph.property.PropertyType;
-import org.jboss.dna.graph.property.ValueFactory;
import org.jboss.dna.graph.query.QueryContext;
import org.jboss.dna.graph.query.model.QueryCommand;
import org.jboss.dna.graph.query.model.SelectorName;
+import org.jboss.dna.graph.query.model.TypeSystem;
import org.jboss.dna.graph.query.model.Visitors;
import org.jboss.dna.graph.query.parse.InvalidQueryException;
import org.jboss.dna.graph.query.parse.SqlQueryParser;
@@ -58,13 +56,13 @@
/**
* Obtain a new instance for building Schemata objects.
*
- * @param context the execution context that can be used when building the schema
+ * @param typeSystem the type system that this schemata should use
* @return the new builder; never null
* @throws IllegalArgumentException if the context is null
*/
- public static Builder createBuilder( ExecutionContext context ) {
- CheckArg.isNotNull(context, "context");
- return new Builder(context);
+ public static Builder createBuilder( TypeSystem typeSystem ) {
+ CheckArg.isNotNull(typeSystem, "typeSystem");
+ return new Builder(typeSystem);
}
/**
@@ -73,17 +71,17 @@
@NotThreadSafe
public static class Builder {
- private final ExecutionContext context;
+ private final TypeSystem typeSystem;
private final Map<SelectorName, ImmutableTable> tables = new HashMap<SelectorName, ImmutableTable>();
private final Map<SelectorName, QueryCommand> viewDefinitions = new HashMap<SelectorName, QueryCommand>();
- protected Builder( ExecutionContext context ) {
- this.context = context;
+ protected Builder( TypeSystem typeSystem ) {
+ this.typeSystem = typeSystem;
}
/**
- * Add a table with the supplied name and column names. Each column will be given a type of {@link PropertyType#STRING}.
- * The table will also overwrite any existing table definition with the same name.
+ * Add a table with the supplied name and column names. Each column will be given a default type. The table will also
+ * overwrite any existing table definition with the same name.
*
* @param name the name of the new table
* @param columnNames the names of the columns.
@@ -99,7 +97,7 @@
int i = 0;
for (String columnName : columnNames) {
CheckArg.isNotEmpty(columnName, "columnName[" + (i++) + "]");
- columns.add(new ImmutableColumn(columnName, PropertyType.STRING));
+ columns.add(new ImmutableColumn(columnName, typeSystem.getDefaultType()));
}
ImmutableTable table = new ImmutableTable(new SelectorName(name), columns);
tables.put(table.getName(), table);
@@ -119,7 +117,7 @@
*/
public Builder addTable( String name,
String[] columnNames,
- PropertyType[] types ) {
+ String[] types ) {
CheckArg.isNotEmpty(name, "name");
CheckArg.isNotEmpty(columnNames, "columnNames");
CheckArg.isNotEmpty(types, "types");
@@ -137,144 +135,6 @@
}
/**
- * Add a table with the supplied name and single column name and type. The table will also overwrite any existing table
- * definition with the same name.
- *
- * @param name the name of the new table
- * @param column1Name the name of the single column
- * @param column1Type the type for the single column
- * @return this builder, for convenience in method chaining; never null
- * @throws IllegalArgumentException if the table name is null or empty, the column name is null or empty, or if the type
- * is null
- */
- public Builder addTable( String name,
- String column1Name,
- PropertyType column1Type ) {
- CheckArg.isNotEmpty(name, "name");
- CheckArg.isNotNull(column1Name, "column1Name");
- CheckArg.isNotNull(column1Type, "column1Type");
- List<Column> columns = new ArrayList<Column>();
- columns.add(new ImmutableColumn(column1Name, column1Type));
- ImmutableTable table = new ImmutableTable(new SelectorName(name), columns);
- tables.put(table.getName(), table);
- return this;
- }
-
- /**
- * Add a table with the supplied name and two column names and types. The table will also overwrite any existing table
- * definition with the same name.
- *
- * @param name the name of the new table
- * @param column1Name the name of the first column
- * @param column1Type the type for the first column
- * @param column2Name the name of the second column
- * @param column2Type the type for the second column
- * @return this builder, for convenience in method chaining; never null
- * @throws IllegalArgumentException if the table name is null or empty, any column name is null or empty, or any of the
- * types is null
- */
- public Builder addTable( String name,
- String column1Name,
- PropertyType column1Type,
- String column2Name,
- PropertyType column2Type ) {
- CheckArg.isNotEmpty(name, "name");
- CheckArg.isNotNull(column1Name, "column1Name");
- CheckArg.isNotNull(column1Type, "column1Type");
- CheckArg.isNotNull(column2Name, "column2Name");
- CheckArg.isNotNull(column2Type, "column2Type");
- List<Column> columns = new ArrayList<Column>();
- columns.add(new ImmutableColumn(column1Name, column1Type));
- columns.add(new ImmutableColumn(column2Name, column2Type));
- ImmutableTable table = new ImmutableTable(new SelectorName(name), columns);
- tables.put(table.getName(), table);
- return this;
- }
-
- /**
- * Add a table with the supplied name and three column names and types. The table will also overwrite any existing table
- * definition with the same name.
- *
- * @param name the name of the new table
- * @param column1Name the name of the first column
- * @param column1Type the type for the first column
- * @param column2Name the name of the second column
- * @param column2Type the type for the second column
- * @param column3Name the name of the third column
- * @param column3Type the type for the third column
- * @return this builder, for convenience in method chaining; never null
- * @throws IllegalArgumentException if the table name is null or empty, any column name is null or empty, or any of the
- * types is null
- */
- public Builder addTable( String name,
- String column1Name,
- PropertyType column1Type,
- String column2Name,
- PropertyType column2Type,
- String column3Name,
- PropertyType column3Type ) {
- CheckArg.isNotEmpty(name, "name");
- CheckArg.isNotNull(column1Name, "column1Name");
- CheckArg.isNotNull(column1Type, "column1Type");
- CheckArg.isNotNull(column2Name, "column2Name");
- CheckArg.isNotNull(column2Type, "column2Type");
- CheckArg.isNotNull(column3Name, "column3Name");
- CheckArg.isNotNull(column3Type, "column3Type");
- List<Column> columns = new ArrayList<Column>();
- columns.add(new ImmutableColumn(column1Name, column1Type));
- columns.add(new ImmutableColumn(column2Name, column2Type));
- columns.add(new ImmutableColumn(column3Name, column3Type));
- ImmutableTable table = new ImmutableTable(new SelectorName(name), columns);
- tables.put(table.getName(), table);
- return this;
- }
-
- /**
- * Add a table with the supplied name and four column names and types. The table will also overwrite any existing table
- * definition with the same name.
- *
- * @param name the name of the new table
- * @param column1Name the name of the first column
- * @param column1Type the type for the first column
- * @param column2Name the name of the second column
- * @param column2Type the type for the second column
- * @param column3Name the name of the third column
- * @param column3Type the type for the third column
- * @param column4Name the name of the fourth column
- * @param column4Type the type for the fourth column
- * @return this builder, for convenience in method chaining; never null
- * @throws IllegalArgumentException if the table name is null or empty, any column name is null or empty, or any of the
- * types is null
- */
- public Builder addTable( String name,
- String column1Name,
- PropertyType column1Type,
- String column2Name,
- PropertyType column2Type,
- String column3Name,
- PropertyType column3Type,
- String column4Name,
- PropertyType column4Type ) {
- CheckArg.isNotEmpty(name, "name");
- CheckArg.isNotNull(column1Name, "column1Name");
- CheckArg.isNotNull(column1Type, "column1Type");
- CheckArg.isNotNull(column2Name, "column2Name");
- CheckArg.isNotNull(column2Type, "column2Type");
- CheckArg.isNotNull(column3Name, "column3Name");
- CheckArg.isNotNull(column3Type, "column3Type");
- CheckArg.isNotNull(column4Name, "column4Name");
- CheckArg.isNotNull(column4Type, "column4Type");
- List<Column> columns = new ArrayList<Column>();
- columns.add(new ImmutableColumn(column1Name, column1Type));
- columns.add(new ImmutableColumn(column2Name, column2Type));
- columns.add(new ImmutableColumn(column3Name, column3Type));
- columns.add(new ImmutableColumn(column4Name, column4Type));
- ImmutableTable table = new ImmutableTable(new SelectorName(name), columns);
- tables.put(table.getName(), table);
- return this;
- }
-
- /**
* Add a view with the supplied name and SQL string definition. The column names and types will be inferred from the
* source table(s) and views(s) used in the definition.
*
@@ -289,7 +149,7 @@
CheckArg.isNotEmpty(name, "name");
CheckArg.isNotEmpty(definition, "definition");
SqlQueryParser parser = new SqlQueryParser();
- QueryCommand command = parser.parseQuery(definition, context);
+ QueryCommand command = parser.parseQuery(definition, typeSystem);
this.viewDefinitions.put(new SelectorName(name), command);
return this;
}
@@ -324,7 +184,7 @@
*/
public Builder addColumn( String tableName,
String columnName,
- PropertyType type ) {
+ String type ) {
CheckArg.isNotEmpty(tableName, "tableName");
CheckArg.isNotEmpty(columnName, "columnName");
CheckArg.isNotNull(type, "type");
@@ -345,7 +205,7 @@
*/
public Builder addColumn( String tableName,
String columnName,
- PropertyType type,
+ String type,
boolean fullTextSearchable ) {
CheckArg.isNotEmpty(tableName, "tableName");
CheckArg.isNotEmpty(columnName, "columnName");
@@ -381,11 +241,11 @@
ImmutableTable table = null;
if (existing == null) {
List<Column> columns = new ArrayList<Column>();
- columns.add(new ImmutableColumn(columnName, PropertyType.STRING, true));
+ columns.add(new ImmutableColumn(columnName, typeSystem.getDefaultType(), true));
table = new ImmutableTable(selector, columns);
} else {
Column column = existing.getColumn(columnName);
- PropertyType type = PropertyType.STRING;
+ String type = typeSystem.getDefaultType();
if (column != null) {
type = column.getPropertyType();
}
@@ -438,7 +298,6 @@
// Make a copy of the view definitions, and create the views ...
Map<SelectorName, QueryCommand> definitions = new HashMap<SelectorName, QueryCommand>(viewDefinitions);
- ValueFactory<String> stringFactory = context.getValueFactories().getStringFactory();
boolean added = false;
do {
added = false;
@@ -446,7 +305,7 @@
for (SelectorName name : viewNames) {
QueryCommand command = definitions.get(name);
// Create the canonical plan for the definition ...
- QueryContext queryContext = new QueryContext(context, schemata);
+ QueryContext queryContext = new QueryContext(schemata, typeSystem);
CanonicalPlanner planner = new CanonicalPlanner();
PlanNode plan = planner.createPlan(queryContext, command);
if (queryContext.getProblems().hasErrors()) continue;
@@ -465,7 +324,7 @@
Table source = schemata.getTable(column.getSelectorName());
if (source == null) break;
String viewColumnName = column.getColumnName();
- String sourceColumnName = stringFactory.create(column.getPropertyName()); // getColumnName() returns alias
+ String sourceColumnName = column.getPropertyName(); // getColumnName() returns alias
Column sourceColumn = source.getColumn(sourceColumnName);
if (sourceColumn == null) {
throw new InvalidQueryException(Visitors.readable(command),
Modified: trunk/dna-graph/src/main/java/org/jboss/dna/graph/query/validate/ImmutableTable.java
===================================================================
--- trunk/dna-graph/src/main/java/org/jboss/dna/graph/query/validate/ImmutableTable.java 2009-11-24 17:44:29 UTC (rev 1339)
+++ trunk/dna-graph/src/main/java/org/jboss/dna/graph/query/validate/ImmutableTable.java 2009-11-24 17:46:37 UTC (rev 1340)
@@ -33,7 +33,6 @@
import java.util.Map;
import java.util.Set;
import net.jcip.annotations.Immutable;
-import org.jboss.dna.graph.property.PropertyType;
import org.jboss.dna.graph.query.model.SelectorName;
import org.jboss.dna.graph.query.validate.Schemata.Column;
import org.jboss.dna.graph.query.validate.Schemata.Key;
@@ -181,14 +180,14 @@
}
public ImmutableTable withColumn( String name,
- PropertyType type ) {
+ String type ) {
List<Column> newColumns = new LinkedList<Column>(columns);
newColumns.add(new ImmutableColumn(name, type));
return new ImmutableTable(getName(), newColumns);
}
public ImmutableTable withColumn( String name,
- PropertyType type,
+ String type,
boolean fullTextSearchable ) {
List<Column> newColumns = new LinkedList<Column>(columns);
newColumns.add(new ImmutableColumn(name, type, fullTextSearchable));
Modified: trunk/dna-graph/src/main/java/org/jboss/dna/graph/query/validate/Schemata.java
===================================================================
--- trunk/dna-graph/src/main/java/org/jboss/dna/graph/query/validate/Schemata.java 2009-11-24 17:44:29 UTC (rev 1339)
+++ trunk/dna-graph/src/main/java/org/jboss/dna/graph/query/validate/Schemata.java 2009-11-24 17:46:37 UTC (rev 1340)
@@ -28,7 +28,6 @@
import java.util.Map;
import java.util.Set;
import net.jcip.annotations.Immutable;
-import org.jboss.dna.graph.property.PropertyType;
import org.jboss.dna.graph.query.model.QueryCommand;
import org.jboss.dna.graph.query.model.SelectorName;
@@ -159,7 +158,7 @@
*
* @return the property type; never null
*/
- PropertyType getPropertyType();
+ String getPropertyType();
/**
* Get whether the column can be used in a full-text search.
Modified: trunk/dna-graph/src/main/java/org/jboss/dna/graph/query/validate/Validator.java
===================================================================
--- trunk/dna-graph/src/main/java/org/jboss/dna/graph/query/validate/Validator.java 2009-11-24 17:44:29 UTC (rev 1339)
+++ trunk/dna-graph/src/main/java/org/jboss/dna/graph/query/validate/Validator.java 2009-11-24 17:46:37 UTC (rev 1340)
@@ -26,7 +26,6 @@
import java.util.Map;
import org.jboss.dna.common.collection.Problems;
import org.jboss.dna.graph.GraphI18n;
-import org.jboss.dna.graph.property.Name;
import org.jboss.dna.graph.query.QueryContext;
import org.jboss.dna.graph.query.model.AllNodes;
import org.jboss.dna.graph.query.model.ChildNode;
@@ -302,10 +301,6 @@
verify(obj.getSelector2Name());
}
- protected String string( Name name ) {
- return context.getExecutionContext().getValueFactories().getStringFactory().create(name);
- }
-
protected Table verify( SelectorName selectorName ) {
Table table = selectorsByName.get(selectorName);
if (table == null) {
@@ -323,15 +318,15 @@
}
protected Schemata.Column verify( SelectorName selectorName,
- Name propertyName ) {
+ String propertyName ) {
Table table = selectorsByName.get(selectorName);
if (table == null) {
problems.addError(GraphI18n.tableDoesNotExist, selectorName.getName());
return null;
}
- Schemata.Column column = table.getColumn(string(propertyName));
+ Schemata.Column column = table.getColumn(propertyName);
if (column == null) {
- problems.addError(GraphI18n.columnDoesNotExistOnTable, string(propertyName), selectorName.getName());
+ problems.addError(GraphI18n.columnDoesNotExistOnTable, propertyName, selectorName.getName());
}
return column;
}
Modified: trunk/dna-graph/src/main/java/org/jboss/dna/graph/search/SearchEngine.java
===================================================================
--- trunk/dna-graph/src/main/java/org/jboss/dna/graph/search/SearchEngine.java 2009-11-24 17:44:29 UTC (rev 1339)
+++ trunk/dna-graph/src/main/java/org/jboss/dna/graph/search/SearchEngine.java 2009-11-24 17:46:37 UTC (rev 1340)
@@ -366,7 +366,7 @@
CheckArg.isNotNull(workspaceName, "workspaceName");
CheckArg.isNotNull(query, "query");
CheckArg.isNotNull(schemata, "schemata");
- QueryContext queryContext = new QueryContext(context, schemata);
+ QueryContext queryContext = new QueryContext(schemata, context.getValueFactories().getTypeSystem());
Query queryActivity = queryContent(queryContext, query);
getWorkspace(workspaceName).execute(false, queryActivity);
return queryActivity.getResults();
Modified: trunk/dna-graph/src/test/java/org/jboss/dna/graph/query/QueryBuilderTest.java
===================================================================
--- trunk/dna-graph/src/test/java/org/jboss/dna/graph/query/QueryBuilderTest.java 2009-11-24 17:44:29 UTC (rev 1339)
+++ trunk/dna-graph/src/test/java/org/jboss/dna/graph/query/QueryBuilderTest.java 2009-11-24 17:46:37 UTC (rev 1340)
@@ -37,19 +37,17 @@
*/
public class QueryBuilderTest {
- private ExecutionContext context;
private QueryBuilder builder;
private QueryCommand query;
@Before
public void beforeEach() {
- context = new ExecutionContext();
- builder = new QueryBuilder(context);
+ builder = new QueryBuilder(new ExecutionContext().getValueFactories().getTypeSystem());
}
protected void assertThatSql( QueryCommand query,
Matcher<String> expected ) {
- assertThat(Visitors.readable(query, context), expected);
+ assertThat(Visitors.readable(query), expected);
}
@Test
@@ -332,19 +330,19 @@
@Test
public void shouldBuildQueryWithChildConstraint() {
query = builder.selectStar().from("table AS nodes").where().isChild("nodes", "/parent/path").end().query();
- assertThatSql(query, is("SELECT * FROM table AS nodes WHERE ISCHILDNODE(nodes,'/parent/path')"));
+ assertThatSql(query, is("SELECT * FROM table AS nodes WHERE ISCHILDNODE(nodes,/parent/path)"));
}
@Test
public void shouldBuildQueryWithDescendantConstraint() {
query = builder.selectStar().from("table AS nodes").where().isBelowPath("nodes", "/parent/path").end().query();
- assertThatSql(query, is("SELECT * FROM table AS nodes WHERE ISDESCENDANTNODE(nodes,'/parent/path')"));
+ assertThatSql(query, is("SELECT * FROM table AS nodes WHERE ISDESCENDANTNODE(nodes,/parent/path)"));
}
@Test
public void shouldBuildQueryWithSameNodeConstraint() {
query = builder.selectStar().from("table AS nodes").where().isSameNode("nodes", "/other/path").end().query();
- assertThatSql(query, is("SELECT * FROM table AS nodes WHERE ISSAMENODE(nodes,'/other/path')"));
+ assertThatSql(query, is("SELECT * FROM table AS nodes WHERE ISSAMENODE(nodes,/other/path)"));
}
@Test
Modified: trunk/dna-graph/src/test/java/org/jboss/dna/graph/query/model/AbstractQueryObjectTest.java
===================================================================
--- trunk/dna-graph/src/test/java/org/jboss/dna/graph/query/model/AbstractQueryObjectTest.java 2009-11-24 17:44:29 UTC (rev 1339)
+++ trunk/dna-graph/src/test/java/org/jboss/dna/graph/query/model/AbstractQueryObjectTest.java 2009-11-24 17:46:37 UTC (rev 1340)
@@ -24,8 +24,6 @@
package org.jboss.dna.graph.query.model;
import org.jboss.dna.graph.ExecutionContext;
-import org.jboss.dna.graph.property.Name;
-import org.jboss.dna.graph.property.Path;
import org.junit.Before;
/**
@@ -40,14 +38,6 @@
context = new ExecutionContext();
}
- protected Name name( String name ) {
- return context.getValueFactories().getNameFactory().create(name);
- }
-
- protected Path path( String name ) {
- return context.getValueFactories().getPathFactory().create(name);
- }
-
protected SelectorName selector( String name ) {
return new SelectorName(name);
}
Modified: trunk/dna-graph/src/test/java/org/jboss/dna/graph/query/model/QueryTest.java
===================================================================
--- trunk/dna-graph/src/test/java/org/jboss/dna/graph/query/model/QueryTest.java 2009-11-24 17:44:29 UTC (rev 1339)
+++ trunk/dna-graph/src/test/java/org/jboss/dna/graph/query/model/QueryTest.java 2009-11-24 17:46:37 UTC (rev 1340)
@@ -120,10 +120,10 @@
public void shouldConstructReadableString() {
source = new NamedSelector(selector("nt:unstructured"));
columns = Collections.singletonList(new Column(selector("selector1")));
- constraint = new PropertyExistence(selector("selector1"), name("jcr:uuid"));
+ constraint = new PropertyExistence(selector("selector1"), "jcr:uuid");
orderings = Collections.singletonList(new Ordering(new NodeName(selector("selector1")), Order.ASCENDING));
query = new Query(source, constraint, orderings, columns, limits, distinct);
- assertThat(Visitors.readable(query, context),
+ assertThat(Visitors.readable(query),
is("SELECT selector1.* FROM nt:unstructured WHERE selector1.jcr:uuid IS NOT NULL ORDER BY NAME(selector1) ASC"));
}
@@ -131,11 +131,11 @@
public void shouldConstructReadableStringWithLimits() {
source = new NamedSelector(selector("nt:unstructured"));
columns = Collections.singletonList(new Column(selector("selector1")));
- constraint = new PropertyExistence(selector("selector1"), name("jcr:uuid"));
+ constraint = new PropertyExistence(selector("selector1"), "jcr:uuid");
orderings = Collections.singletonList(new Ordering(new NodeName(selector("selector1")), Order.ASCENDING));
limits = new Limit(10, 100);
query = new Query(source, constraint, orderings, columns, limits, distinct);
- assertThat(Visitors.readable(query, context),
+ assertThat(Visitors.readable(query),
is("SELECT selector1.* FROM nt:unstructured WHERE selector1.jcr:uuid IS NOT NULL ORDER BY NAME(selector1) ASC LIMIT 10 OFFSET 100"));
}
@@ -143,10 +143,10 @@
public void shouldConstructReadableStringWithNoColumns() {
source = new NamedSelector(selector("nt:unstructured"));
columns = Collections.emptyList();
- constraint = new PropertyExistence(selector("selector1"), name("jcr:uuid"));
+ constraint = new PropertyExistence(selector("selector1"), "jcr:uuid");
orderings = Collections.singletonList(new Ordering(new NodeName(selector("selector1")), Order.ASCENDING));
query = new Query(source, constraint, orderings, columns, limits, distinct);
- assertThat(Visitors.readable(query, context),
+ assertThat(Visitors.readable(query),
is("SELECT * FROM nt:unstructured WHERE selector1.jcr:uuid IS NOT NULL ORDER BY NAME(selector1) ASC"));
}
@@ -154,11 +154,10 @@
public void shouldConstructReadableStringWithNoOrderings() {
source = new NamedSelector(selector("nt:unstructured"));
columns = Collections.singletonList(new Column(selector("selector1")));
- constraint = new PropertyExistence(selector("selector1"), name("jcr:uuid"));
+ constraint = new PropertyExistence(selector("selector1"), "jcr:uuid");
orderings = Collections.emptyList();
query = new Query(source, constraint, orderings, columns, limits, distinct);
- assertThat(Visitors.readable(query, context),
- is("SELECT selector1.* FROM nt:unstructured WHERE selector1.jcr:uuid IS NOT NULL"));
+ assertThat(Visitors.readable(query), is("SELECT selector1.* FROM nt:unstructured WHERE selector1.jcr:uuid IS NOT NULL"));
}
@Test
@@ -168,7 +167,7 @@
constraint = null;
orderings = Collections.singletonList(new Ordering(new NodeName(selector("selector1")), Order.ASCENDING));
query = new Query(source, constraint, orderings, columns, limits, distinct);
- assertThat(Visitors.readable(query, context), is("SELECT selector1.* FROM nt:unstructured ORDER BY NAME(selector1) ASC"));
+ assertThat(Visitors.readable(query), is("SELECT selector1.* FROM nt:unstructured ORDER BY NAME(selector1) ASC"));
}
@Test
@@ -179,11 +178,11 @@
orderings = Collections.emptyList();
distinct = true;
query = new Query(source, constraint, orderings, columns, limits, distinct);
- assertThat(Visitors.readable(query, context), is("SELECT DISTINCT * FROM nt:unstructured"));
+ assertThat(Visitors.readable(query), is("SELECT DISTINCT * FROM nt:unstructured"));
source = new AllNodes();
query = new Query(source, constraint, orderings, columns, limits, distinct);
- assertThat(Visitors.readable(query, context), is("SELECT DISTINCT * FROM __ALLNODES__"));
+ assertThat(Visitors.readable(query), is("SELECT DISTINCT * FROM __ALLNODES__"));
}
@Test
@@ -193,10 +192,10 @@
constraint = null;
orderings = Collections.emptyList();
query = new Query(source, constraint, orderings, columns, limits, distinct);
- assertThat(Visitors.readable(query, context), is("SELECT * FROM nt:unstructured"));
+ assertThat(Visitors.readable(query), is("SELECT * FROM nt:unstructured"));
source = new AllNodes();
query = new Query(source, constraint, orderings, columns, limits, distinct);
- assertThat(Visitors.readable(query, context), is("SELECT * FROM __ALLNODES__"));
+ assertThat(Visitors.readable(query), is("SELECT * FROM __ALLNODES__"));
}
}
Modified: trunk/dna-graph/src/test/java/org/jboss/dna/graph/query/model/SetQueryTest.java
===================================================================
--- trunk/dna-graph/src/test/java/org/jboss/dna/graph/query/model/SetQueryTest.java 2009-11-24 17:44:29 UTC (rev 1339)
+++ trunk/dna-graph/src/test/java/org/jboss/dna/graph/query/model/SetQueryTest.java 2009-11-24 17:46:37 UTC (rev 1340)
@@ -74,7 +74,7 @@
right = new Query(new NamedSelector(selector("B")));
operation = SetQuery.Operation.UNION;
query = new SetQuery(left, operation, right, all);
- assertThat(Visitors.readable(query, context), is("SELECT * FROM A UNION SELECT * FROM B"));
+ assertThat(Visitors.readable(query), is("SELECT * FROM A UNION SELECT * FROM B"));
}
@Test
@@ -84,7 +84,7 @@
operation = SetQuery.Operation.UNION;
all = true;
query = new SetQuery(left, operation, right, all);
- assertThat(Visitors.readable(query, context), is("SELECT * FROM A UNION ALL SELECT * FROM B"));
+ assertThat(Visitors.readable(query), is("SELECT * FROM A UNION ALL SELECT * FROM B"));
}
@Test
@@ -93,7 +93,7 @@
right = new Query(new NamedSelector(selector("B")));
operation = SetQuery.Operation.INTERSECT;
query = new SetQuery(left, operation, right, all);
- assertThat(Visitors.readable(query, context), is("SELECT * FROM A INTERSECT SELECT * FROM B"));
+ assertThat(Visitors.readable(query), is("SELECT * FROM A INTERSECT SELECT * FROM B"));
}
@Test
@@ -103,7 +103,7 @@
operation = SetQuery.Operation.INTERSECT;
all = true;
query = new SetQuery(left, operation, right, all);
- assertThat(Visitors.readable(query, context), is("SELECT * FROM A INTERSECT ALL SELECT * FROM B"));
+ assertThat(Visitors.readable(query), is("SELECT * FROM A INTERSECT ALL SELECT * FROM B"));
}
@Test
@@ -112,7 +112,7 @@
right = new Query(new NamedSelector(selector("B")));
operation = SetQuery.Operation.EXCEPT;
query = new SetQuery(left, operation, right, all);
- assertThat(Visitors.readable(query, context), is("SELECT * FROM A EXCEPT SELECT * FROM B"));
+ assertThat(Visitors.readable(query), is("SELECT * FROM A EXCEPT SELECT * FROM B"));
}
@Test
@@ -122,6 +122,6 @@
operation = SetQuery.Operation.EXCEPT;
all = true;
query = new SetQuery(left, operation, right, all);
- assertThat(Visitors.readable(query, context), is("SELECT * FROM A EXCEPT ALL SELECT * FROM B"));
+ assertThat(Visitors.readable(query), is("SELECT * FROM A EXCEPT ALL SELECT * FROM B"));
}
}
Modified: trunk/dna-graph/src/test/java/org/jboss/dna/graph/query/optimize/AddAccessNodesTest.java
===================================================================
--- trunk/dna-graph/src/test/java/org/jboss/dna/graph/query/optimize/AddAccessNodesTest.java 2009-11-24 17:44:29 UTC (rev 1339)
+++ trunk/dna-graph/src/test/java/org/jboss/dna/graph/query/optimize/AddAccessNodesTest.java 2009-11-24 17:46:37 UTC (rev 1340)
@@ -47,7 +47,7 @@
@Before
public void beforeEach() {
- context = new QueryContext(new ExecutionContext(), mock(Schemata.class));
+ context = new QueryContext(mock(Schemata.class), new ExecutionContext().getValueFactories().getTypeSystem());
rule = AddAccessNodes.INSTANCE;
}
Modified: trunk/dna-graph/src/test/java/org/jboss/dna/graph/query/optimize/ChooseJoinAlgorithmTest.java
===================================================================
--- trunk/dna-graph/src/test/java/org/jboss/dna/graph/query/optimize/ChooseJoinAlgorithmTest.java 2009-11-24 17:44:29 UTC (rev 1339)
+++ trunk/dna-graph/src/test/java/org/jboss/dna/graph/query/optimize/ChooseJoinAlgorithmTest.java 2009-11-24 17:46:37 UTC (rev 1340)
@@ -54,7 +54,7 @@
@Before
public void beforeEach() {
- context = new QueryContext(new ExecutionContext(), mock(Schemata.class));
+ context = new QueryContext(mock(Schemata.class), new ExecutionContext().getValueFactories().getTypeSystem());
bestRule = ChooseJoinAlgorithm.USE_BEST_JOIN_ALGORITHM;
nestedRule = ChooseJoinAlgorithm.USE_ONLY_NESTED_JOIN_ALGORITHM;
}
Modified: trunk/dna-graph/src/test/java/org/jboss/dna/graph/query/optimize/PushSelectCriteriaTest.java
===================================================================
--- trunk/dna-graph/src/test/java/org/jboss/dna/graph/query/optimize/PushSelectCriteriaTest.java 2009-11-24 17:44:29 UTC (rev 1339)
+++ trunk/dna-graph/src/test/java/org/jboss/dna/graph/query/optimize/PushSelectCriteriaTest.java 2009-11-24 17:46:37 UTC (rev 1340)
@@ -49,7 +49,7 @@
@Before
public void beforeEach() {
- context = new QueryContext(new ExecutionContext(), mock(Schemata.class));
+ context = new QueryContext(mock(Schemata.class), new ExecutionContext().getValueFactories().getTypeSystem());
rule = PushSelectCriteria.INSTANCE;
}
Modified: trunk/dna-graph/src/test/java/org/jboss/dna/graph/query/optimize/ReplaceViewsTest.java
===================================================================
--- trunk/dna-graph/src/test/java/org/jboss/dna/graph/query/optimize/ReplaceViewsTest.java 2009-11-24 17:44:29 UTC (rev 1339)
+++ trunk/dna-graph/src/test/java/org/jboss/dna/graph/query/optimize/ReplaceViewsTest.java 2009-11-24 17:46:37 UTC (rev 1340)
@@ -29,7 +29,6 @@
import java.util.LinkedList;
import java.util.List;
import org.jboss.dna.graph.ExecutionContext;
-import org.jboss.dna.graph.property.Name;
import org.jboss.dna.graph.query.AbstractQueryTest;
import org.jboss.dna.graph.query.QueryContext;
import org.jboss.dna.graph.query.model.Column;
@@ -38,6 +37,7 @@
import org.jboss.dna.graph.query.model.Operator;
import org.jboss.dna.graph.query.model.PropertyValue;
import org.jboss.dna.graph.query.model.SelectorName;
+import org.jboss.dna.graph.query.model.TypeSystem;
import org.jboss.dna.graph.query.plan.PlanNode;
import org.jboss.dna.graph.query.plan.PlanNode.Property;
import org.jboss.dna.graph.query.plan.PlanNode.Type;
@@ -58,15 +58,15 @@
@Before
public void beforeEach() {
- ExecutionContext execContext = new ExecutionContext();
+ TypeSystem typeSystem = new ExecutionContext().getValueFactories().getTypeSystem();
rule = ReplaceViews.INSTANCE;
- builder = ImmutableSchemata.createBuilder(execContext);
+ builder = ImmutableSchemata.createBuilder(typeSystem);
builder.addTable("t1", "c11", "c12", "c13");
builder.addTable("t2", "c21", "c22", "c23");
builder.addView("v1", "SELECT c11, c12 FROM t1 WHERE c13 < CAST('3' AS LONG)");
builder.addView("v2", "SELECT t1.c11, t1.c12, t2.c23 FROM t1 JOIN t2 ON t1.c11 = t2.c21");
schemata = builder.build();
- context = new QueryContext(execContext, schemata);
+ context = new QueryContext(schemata, typeSystem);
}
/**
@@ -124,7 +124,7 @@
PlanNode viewSelect = new PlanNode(Type.SELECT, viewProject, selector("t1"));
PlanNode viewSource = new PlanNode(Type.SOURCE, viewSelect, selector("t1"));
viewProject.setProperty(Property.PROJECT_COLUMNS, columns(column("t1", "c11"), column("t1", "c12")));
- viewSelect.setProperty(Property.SELECT_CRITERIA, new Comparison(new PropertyValue(selector("t1"), name("c13")),
+ viewSelect.setProperty(Property.SELECT_CRITERIA, new Comparison(new PropertyValue(selector("t1"), "c13"),
Operator.LESS_THAN, new Literal(3L)));
viewSource.setProperty(Property.SOURCE_NAME, selector("t1"));
viewSource.setProperty(Property.SOURCE_COLUMNS, schemata.getTable(selector("t1")).getColumns());
@@ -145,16 +145,12 @@
protected Column column( String table,
String columnName ) {
- return new Column(new SelectorName(table), name(columnName), columnName);
+ return new Column(new SelectorName(table), columnName, columnName);
}
protected Column column( String table,
String columnName,
String alias ) {
- return new Column(new SelectorName(table), name(columnName), alias);
+ return new Column(new SelectorName(table), columnName, alias);
}
-
- protected Name name( String name ) {
- return context.getExecutionContext().getValueFactories().getNameFactory().create(name);
- }
}
Modified: trunk/dna-graph/src/test/java/org/jboss/dna/graph/query/optimize/RewriteAsRangeCriteriaTest.java
===================================================================
--- trunk/dna-graph/src/test/java/org/jboss/dna/graph/query/optimize/RewriteAsRangeCriteriaTest.java 2009-11-24 17:44:29 UTC (rev 1339)
+++ trunk/dna-graph/src/test/java/org/jboss/dna/graph/query/optimize/RewriteAsRangeCriteriaTest.java 2009-11-24 17:46:37 UTC (rev 1340)
@@ -30,7 +30,6 @@
import static org.mockito.Mockito.mock;
import java.util.LinkedList;
import org.jboss.dna.graph.ExecutionContext;
-import org.jboss.dna.graph.property.Name;
import org.jboss.dna.graph.query.AbstractQueryTest;
import org.jboss.dna.graph.query.QueryContext;
import org.jboss.dna.graph.query.model.Between;
@@ -60,7 +59,7 @@
rule = RewriteAsRangeCriteria.INSTANCE;
rules = new LinkedList<OptimizerRule>();
rules.add(rule);
- context = new QueryContext(new ExecutionContext(), mock(Schemata.class));
+ context = new QueryContext(mock(Schemata.class), new ExecutionContext().getValueFactories().getTypeSystem());
}
protected void print( PlanNode node ) {
@@ -99,11 +98,11 @@
PlanNode select3 = new PlanNode(Type.SELECT, select2, selector("t1"));
PlanNode source = new PlanNode(Type.SOURCE, select3, selector("t1"));
source.setProperty(Property.SOURCE_NAME, selector("t1"));
- select1.setProperty(Property.SELECT_CRITERIA, new Comparison(new PropertyValue(selector("t1"), name("c2")),
- Operator.EQUAL_TO, new Literal(100L)));
- select2.setProperty(Property.SELECT_CRITERIA, new Comparison(new PropertyValue(selector("t1"), name("c1")),
- Operator.LESS_THAN, new Literal(3L)));
- select3.setProperty(Property.SELECT_CRITERIA, new Comparison(new PropertyValue(selector("t1"), name("c1")),
+ select1.setProperty(Property.SELECT_CRITERIA, new Comparison(new PropertyValue(selector("t1"), "c2"), Operator.EQUAL_TO,
+ new Literal(100L)));
+ select2.setProperty(Property.SELECT_CRITERIA, new Comparison(new PropertyValue(selector("t1"), "c1"), Operator.LESS_THAN,
+ new Literal(3L)));
+ select3.setProperty(Property.SELECT_CRITERIA, new Comparison(new PropertyValue(selector("t1"), "c1"),
Operator.GREATER_THAN, new Literal(1L)));
// Execute the rule ...
@@ -160,11 +159,11 @@
PlanNode select3 = new PlanNode(Type.SELECT, select2, selector("t1"));
PlanNode source = new PlanNode(Type.SOURCE, select3, selector("t1"));
source.setProperty(Property.SOURCE_NAME, selector("t1"));
- select1.setProperty(Property.SELECT_CRITERIA, new Comparison(new PropertyValue(selector("t1"), name("c2")),
- Operator.EQUAL_TO, new Literal(100L)));
- select2.setProperty(Property.SELECT_CRITERIA, new Comparison(new PropertyValue(selector("t1"), name("c1")),
+ select1.setProperty(Property.SELECT_CRITERIA, new Comparison(new PropertyValue(selector("t1"), "c2"), Operator.EQUAL_TO,
+ new Literal(100L)));
+ select2.setProperty(Property.SELECT_CRITERIA, new Comparison(new PropertyValue(selector("t1"), "c1"),
Operator.LESS_THAN_OR_EQUAL_TO, new Literal(3L)));
- select3.setProperty(Property.SELECT_CRITERIA, new Comparison(new PropertyValue(selector("t1"), name("c1")),
+ select3.setProperty(Property.SELECT_CRITERIA, new Comparison(new PropertyValue(selector("t1"), "c1"),
Operator.GREATER_THAN_OR_EQUAL_TO, new Literal(1L)));
// Execute the rule ...
@@ -222,12 +221,12 @@
PlanNode select3 = new PlanNode(Type.SELECT, select2, selector("t1"));
PlanNode source = new PlanNode(Type.SOURCE, select3, selector("t1"));
source.setProperty(Property.SOURCE_NAME, selector("t1"));
- select1.setProperty(Property.SELECT_CRITERIA, new Comparison(new PropertyValue(selector("t1"), name("c2")),
- Operator.EQUAL_TO, new Literal(100L)));
- select2.setProperty(Property.SELECT_CRITERIA, new Comparison(new PropertyValue(selector("t1"), name("c1")),
+ select1.setProperty(Property.SELECT_CRITERIA, new Comparison(new PropertyValue(selector("t1"), "c2"), Operator.EQUAL_TO,
+ new Literal(100L)));
+ select2.setProperty(Property.SELECT_CRITERIA, new Comparison(new PropertyValue(selector("t1"), "c1"),
Operator.GREATER_THAN, new Literal(3L)));
- select3.setProperty(Property.SELECT_CRITERIA, new Comparison(new PropertyValue(selector("t1"), name("c1")),
- Operator.LESS_THAN, new Literal(1L)));
+ select3.setProperty(Property.SELECT_CRITERIA, new Comparison(new PropertyValue(selector("t1"), "c1"), Operator.LESS_THAN,
+ new Literal(1L)));
// Execute the rule ...
print(access);
@@ -273,11 +272,11 @@
PlanNode select3 = new PlanNode(Type.SELECT, select2, selector("t1"));
PlanNode source = new PlanNode(Type.SOURCE, select3, selector("t1"));
source.setProperty(Property.SOURCE_NAME, selector("t1"));
- select1.setProperty(Property.SELECT_CRITERIA, new Comparison(new PropertyValue(selector("t1"), name("c2")),
- Operator.EQUAL_TO, new Literal(100L)));
- select2.setProperty(Property.SELECT_CRITERIA, new Comparison(new PropertyValue(selector("t1"), name("c1")),
+ select1.setProperty(Property.SELECT_CRITERIA, new Comparison(new PropertyValue(selector("t1"), "c2"), Operator.EQUAL_TO,
+ new Literal(100L)));
+ select2.setProperty(Property.SELECT_CRITERIA, new Comparison(new PropertyValue(selector("t1"), "c1"),
Operator.GREATER_THAN_OR_EQUAL_TO, new Literal(3L)));
- select3.setProperty(Property.SELECT_CRITERIA, new Comparison(new PropertyValue(selector("t1"), name("c1")),
+ select3.setProperty(Property.SELECT_CRITERIA, new Comparison(new PropertyValue(selector("t1"), "c1"),
Operator.LESS_THAN_OR_EQUAL_TO, new Literal(1L)));
// Execute the rule ...
@@ -323,11 +322,11 @@
PlanNode select3 = new PlanNode(Type.SELECT, select2, selector("t1"));
PlanNode source = new PlanNode(Type.SOURCE, select3, selector("t1"));
source.setProperty(Property.SOURCE_NAME, selector("t1"));
- select1.setProperty(Property.SELECT_CRITERIA, new Comparison(new PropertyValue(selector("t1"), name("c2")),
- Operator.EQUAL_TO, new Literal(100L)));
- select2.setProperty(Property.SELECT_CRITERIA, new Comparison(new PropertyValue(selector("t1"), name("c1")),
+ select1.setProperty(Property.SELECT_CRITERIA, new Comparison(new PropertyValue(selector("t1"), "c2"), Operator.EQUAL_TO,
+ new Literal(100L)));
+ select2.setProperty(Property.SELECT_CRITERIA, new Comparison(new PropertyValue(selector("t1"), "c1"),
Operator.LESS_THAN_OR_EQUAL_TO, new Literal(3L)));
- select3.setProperty(Property.SELECT_CRITERIA, new Comparison(new PropertyValue(selector("t1"), name("c1")),
+ select3.setProperty(Property.SELECT_CRITERIA, new Comparison(new PropertyValue(selector("t1"), "c1"),
Operator.GREATER_THAN_OR_EQUAL_TO, new Literal(3L)));
// Execute the rule ...
@@ -384,11 +383,11 @@
PlanNode select3 = new PlanNode(Type.SELECT, select2, selector("t1"));
PlanNode source = new PlanNode(Type.SOURCE, select3, selector("t1"));
source.setProperty(Property.SOURCE_NAME, selector("t1"));
- select1.setProperty(Property.SELECT_CRITERIA, new Comparison(new PropertyValue(selector("t1"), name("c2")),
- Operator.EQUAL_TO, new Literal(100L)));
- select2.setProperty(Property.SELECT_CRITERIA, new Comparison(new PropertyValue(selector("t1"), name("c1")),
- Operator.LESS_THAN, new Literal(3L)));
- select3.setProperty(Property.SELECT_CRITERIA, new Comparison(new PropertyValue(selector("t1"), name("c1")),
+ select1.setProperty(Property.SELECT_CRITERIA, new Comparison(new PropertyValue(selector("t1"), "c2"), Operator.EQUAL_TO,
+ new Literal(100L)));
+ select2.setProperty(Property.SELECT_CRITERIA, new Comparison(new PropertyValue(selector("t1"), "c1"), Operator.LESS_THAN,
+ new Literal(3L)));
+ select3.setProperty(Property.SELECT_CRITERIA, new Comparison(new PropertyValue(selector("t1"), "c1"),
Operator.GREATER_THAN, new Literal(3L)));
// Execute the rule ...
@@ -410,8 +409,4 @@
}
return node;
}
-
- protected Name name( String name ) {
- return context.getExecutionContext().getValueFactories().getNameFactory().create(name);
- }
}
Modified: trunk/dna-graph/src/test/java/org/jboss/dna/graph/query/optimize/RightOuterToLeftOuterJoinsTest.java
===================================================================
--- trunk/dna-graph/src/test/java/org/jboss/dna/graph/query/optimize/RightOuterToLeftOuterJoinsTest.java 2009-11-24 17:44:29 UTC (rev 1339)
+++ trunk/dna-graph/src/test/java/org/jboss/dna/graph/query/optimize/RightOuterToLeftOuterJoinsTest.java 2009-11-24 17:46:37 UTC (rev 1340)
@@ -49,7 +49,7 @@
@Before
public void beforeEach() {
- context = new QueryContext(new ExecutionContext(), mock(Schemata.class));
+ context = new QueryContext(mock(Schemata.class), new ExecutionContext().getValueFactories().getTypeSystem());
rule = RightOuterToLeftOuterJoins.INSTANCE;
}
Modified: trunk/dna-graph/src/test/java/org/jboss/dna/graph/query/optimize/RuleBasedOptimizerTest.java
===================================================================
--- trunk/dna-graph/src/test/java/org/jboss/dna/graph/query/optimize/RuleBasedOptimizerTest.java 2009-11-24 17:44:29 UTC (rev 1339)
+++ trunk/dna-graph/src/test/java/org/jboss/dna/graph/query/optimize/RuleBasedOptimizerTest.java 2009-11-24 17:46:37 UTC (rev 1340)
@@ -32,7 +32,6 @@
import org.jboss.dna.common.collection.Problems;
import org.jboss.dna.graph.ExecutionContext;
import org.jboss.dna.graph.GraphI18n;
-import org.jboss.dna.graph.property.Name;
import org.jboss.dna.graph.query.AbstractQueryTest;
import org.jboss.dna.graph.query.QueryContext;
import org.jboss.dna.graph.query.model.Column;
@@ -46,6 +45,7 @@
import org.jboss.dna.graph.query.model.QueryCommand;
import org.jboss.dna.graph.query.model.SelectorName;
import org.jboss.dna.graph.query.model.SetCriteria;
+import org.jboss.dna.graph.query.model.TypeSystem;
import org.jboss.dna.graph.query.parse.SqlQueryParser;
import org.jboss.dna.graph.query.plan.CanonicalPlanner;
import org.jboss.dna.graph.query.plan.JoinAlgorithm;
@@ -72,8 +72,8 @@
@Before
public void beforeEach() {
- ExecutionContext execContext = new ExecutionContext();
- ImmutableSchemata.Builder builder = ImmutableSchemata.createBuilder(execContext);
+ TypeSystem typeSystem = new ExecutionContext().getValueFactories().getTypeSystem();
+ ImmutableSchemata.Builder builder = ImmutableSchemata.createBuilder(typeSystem);
builder.addTable("t1", "c11", "c12", "c13");
builder.addTable("t2", "c21", "c22", "c23");
builder.addTable("all", "a1", "a2", "a3", "a4", "primaryType", "mixins");
@@ -88,7 +88,7 @@
builder.addView("type2",
"SELECT all.a3, all.a4 FROM all WHERE all.primaryType IN ('t2','t0') AND all.mixins IN ('t4','t5')");
Schemata schemata = builder.build();
- context = new QueryContext(execContext, schemata);
+ context = new QueryContext(schemata, typeSystem);
node = new PlanNode(Type.ACCESS);
@@ -191,8 +191,8 @@
PlanNode project = new PlanNode(Type.PROJECT, expected, selector("t1"));
project.setProperty(Property.PROJECT_COLUMNS, columns(column("t1", "c11"), column("t1", "c12")));
PlanNode select = new PlanNode(Type.SELECT, project, selector("t1"));
- select.setProperty(Property.SELECT_CRITERIA, new Comparison(new PropertyValue(selector("t1"), name("c13")),
- Operator.LESS_THAN, new Literal(3L)));
+ select.setProperty(Property.SELECT_CRITERIA, new Comparison(new PropertyValue(selector("t1"), "c13"), Operator.LESS_THAN,
+ new Literal(3L)));
PlanNode source = new PlanNode(Type.SOURCE, select, selector("t1"));
source.setProperty(Property.SOURCE_NAME, selector("t1"));
source.setProperty(Property.SOURCE_COLUMNS, context.getSchemata().getTable(selector("t1")).getColumns());
@@ -210,7 +210,7 @@
PlanNode join = new PlanNode(Type.JOIN, project, selector("t2"), selector("t1"));
join.setProperty(Property.JOIN_ALGORITHM, JoinAlgorithm.NESTED_LOOP);
join.setProperty(Property.JOIN_TYPE, JoinType.INNER);
- join.setProperty(Property.JOIN_CONDITION, new EquiJoinCondition(selector("t1"), name("c11"), selector("t2"), name("c21")));
+ join.setProperty(Property.JOIN_CONDITION, new EquiJoinCondition(selector("t1"), "c11", selector("t2"), "c21"));
PlanNode leftAccess = new PlanNode(Type.ACCESS, join, selector("t1"));
PlanNode leftProject = new PlanNode(Type.PROJECT, leftAccess, selector("t1"));
@@ -239,13 +239,13 @@
PlanNode project = new PlanNode(Type.PROJECT, access, selector("t1"));
project.setProperty(Property.PROJECT_COLUMNS, columns(column("t1", "c11", "c1")));
PlanNode select1 = new PlanNode(Type.SELECT, project, selector("t1"));
- select1.setProperty(Property.SELECT_CRITERIA, new Comparison(new PropertyValue(selector("t1"), name("c11")),
- Operator.EQUAL_TO, new Literal('x')));
+ select1.setProperty(Property.SELECT_CRITERIA, new Comparison(new PropertyValue(selector("t1"), "c11"), Operator.EQUAL_TO,
+ new Literal('x')));
PlanNode select2 = new PlanNode(Type.SELECT, select1, selector("t1"));
- select2.setProperty(Property.SELECT_CRITERIA, new Comparison(new PropertyValue(selector("t1"), name("c12")),
- Operator.EQUAL_TO, new Literal('y')));
+ select2.setProperty(Property.SELECT_CRITERIA, new Comparison(new PropertyValue(selector("t1"), "c12"), Operator.EQUAL_TO,
+ new Literal('y')));
PlanNode select3 = new PlanNode(Type.SELECT, select2, selector("t1"));
- select3.setProperty(Property.SELECT_CRITERIA, new Comparison(new PropertyValue(selector("t1"), name("c13")),
+ select3.setProperty(Property.SELECT_CRITERIA, new Comparison(new PropertyValue(selector("t1"), "c13"),
Operator.LESS_THAN, new Literal(3L)));
PlanNode source = new PlanNode(Type.SOURCE, select3, selector("t1"));
source.setProperty(Property.SOURCE_NAME, selector("t1"));
@@ -265,16 +265,16 @@
PlanNode join = new PlanNode(Type.JOIN, project, selector("t2"), selector("t1"));
join.setProperty(Property.JOIN_ALGORITHM, JoinAlgorithm.NESTED_LOOP);
join.setProperty(Property.JOIN_TYPE, JoinType.INNER);
- join.setProperty(Property.JOIN_CONDITION, new EquiJoinCondition(selector("t1"), name("c11"), selector("t2"), name("c21")));
+ join.setProperty(Property.JOIN_CONDITION, new EquiJoinCondition(selector("t1"), "c11", selector("t2"), "c21"));
PlanNode leftAccess = new PlanNode(Type.ACCESS, join, selector("t1"));
PlanNode leftProject = new PlanNode(Type.PROJECT, leftAccess, selector("t1"));
leftProject.setProperty(Property.PROJECT_COLUMNS, columns(column("t1", "c11")));
PlanNode leftSelect1 = new PlanNode(Type.SELECT, leftProject, selector("t1"));
- leftSelect1.setProperty(Property.SELECT_CRITERIA, new Comparison(new PropertyValue(selector("t1"), name("c11")),
+ leftSelect1.setProperty(Property.SELECT_CRITERIA, new Comparison(new PropertyValue(selector("t1"), "c11"),
Operator.EQUAL_TO, new Literal('x')));
PlanNode leftSelect2 = new PlanNode(Type.SELECT, leftSelect1, selector("t1"));
- leftSelect2.setProperty(Property.SELECT_CRITERIA, new Comparison(new PropertyValue(selector("t1"), name("c12")),
+ leftSelect2.setProperty(Property.SELECT_CRITERIA, new Comparison(new PropertyValue(selector("t1"), "c12"),
Operator.EQUAL_TO, new Literal('y')));
PlanNode leftSource = new PlanNode(Type.SOURCE, leftSelect2, selector("t1"));
leftSource.setProperty(Property.SOURCE_NAME, selector("t1"));
@@ -284,7 +284,7 @@
PlanNode rightProject = new PlanNode(Type.PROJECT, rightAccess, selector("t2"));
rightProject.setProperty(Property.PROJECT_COLUMNS, columns(column("t2", "c21")));
PlanNode rightSelect1 = new PlanNode(Type.SELECT, rightProject, selector("t2"));
- rightSelect1.setProperty(Property.SELECT_CRITERIA, new Comparison(new PropertyValue(selector("t2"), name("c21")),
+ rightSelect1.setProperty(Property.SELECT_CRITERIA, new Comparison(new PropertyValue(selector("t2"), "c21"),
Operator.EQUAL_TO, new Literal('x')));
PlanNode rightSource = new PlanNode(Type.SOURCE, rightSelect1, selector("t2"));
rightSource.setProperty(Property.SOURCE_NAME, selector("t2"));
@@ -303,12 +303,12 @@
PlanNode project = new PlanNode(Type.PROJECT, access, selector("all"));
project.setProperty(Property.PROJECT_COLUMNS, columns(column("all", "a1", "a"), column("all", "a2", "b")));
PlanNode select1 = new PlanNode(Type.SELECT, project, selector("all"));
- select1.setProperty(Property.SELECT_CRITERIA, new FullTextSearch(selector("all"), name("a2"), "something"));
+ select1.setProperty(Property.SELECT_CRITERIA, new FullTextSearch(selector("all"), "a2", "something"));
PlanNode select2 = new PlanNode(Type.SELECT, select1, selector("all"));
- select2.setProperty(Property.SELECT_CRITERIA, new SetCriteria(new PropertyValue(selector("all"), name("primaryType")),
+ select2.setProperty(Property.SELECT_CRITERIA, new SetCriteria(new PropertyValue(selector("all"), "primaryType"),
new Literal("t1"), new Literal("t0")));
PlanNode select3 = new PlanNode(Type.SELECT, select2, selector("all"));
- select3.setProperty(Property.SELECT_CRITERIA, new SetCriteria(new PropertyValue(selector("all"), name("mixins")),
+ select3.setProperty(Property.SELECT_CRITERIA, new SetCriteria(new PropertyValue(selector("all"), "mixins"),
new Literal("t3"), new Literal("t4")));
PlanNode source = new PlanNode(Type.SOURCE, select3, selector("all"));
source.setProperty(Property.SOURCE_NAME, selector("all"));
@@ -331,18 +331,18 @@
column("all", "a3", "c"),
column("all", "a4", "d")));
PlanNode select1 = new PlanNode(Type.SELECT, project, selector("all"));
- select1.setProperty(Property.SELECT_CRITERIA, new FullTextSearch(selector("all"), name("a2"), "something"));
+ select1.setProperty(Property.SELECT_CRITERIA, new FullTextSearch(selector("all"), "a2", "something"));
PlanNode select2 = new PlanNode(Type.SELECT, select1, selector("all"));
- select2.setProperty(Property.SELECT_CRITERIA, new SetCriteria(new PropertyValue(selector("all"), name("primaryType")),
+ select2.setProperty(Property.SELECT_CRITERIA, new SetCriteria(new PropertyValue(selector("all"), "primaryType"),
new Literal("t1"), new Literal("t0")));
PlanNode select3 = new PlanNode(Type.SELECT, select2, selector("all"));
- select3.setProperty(Property.SELECT_CRITERIA, new SetCriteria(new PropertyValue(selector("all"), name("mixins")),
+ select3.setProperty(Property.SELECT_CRITERIA, new SetCriteria(new PropertyValue(selector("all"), "mixins"),
new Literal("t3"), new Literal("t4")));
PlanNode select4 = new PlanNode(Type.SELECT, select3, selector("all"));
- select4.setProperty(Property.SELECT_CRITERIA, new SetCriteria(new PropertyValue(selector("all"), name("primaryType")),
+ select4.setProperty(Property.SELECT_CRITERIA, new SetCriteria(new PropertyValue(selector("all"), "primaryType"),
new Literal("t2"), new Literal("t0")));
PlanNode select5 = new PlanNode(Type.SELECT, select4, selector("all"));
- select5.setProperty(Property.SELECT_CRITERIA, new SetCriteria(new PropertyValue(selector("all"), name("mixins")),
+ select5.setProperty(Property.SELECT_CRITERIA, new SetCriteria(new PropertyValue(selector("all"), "mixins"),
new Literal("t4"), new Literal("t5")));
PlanNode source = new PlanNode(Type.SOURCE, select5, selector("all"));
source.setProperty(Property.SOURCE_NAME, selector("all"));
@@ -364,21 +364,20 @@
column("all", "a3", "c"),
column("all", "a4", "d")));
PlanNode select1 = new PlanNode(Type.SELECT, project, selector("all"));
- select1.setProperty(Property.SELECT_CRITERIA, new FullTextSearch(selector("all"), name("a1"), "something"));
+ select1.setProperty(Property.SELECT_CRITERIA, new FullTextSearch(selector("all"), "a1", "something"));
PlanNode join = new PlanNode(Type.JOIN, select1, selector("all"));
join.setProperty(Property.JOIN_ALGORITHM, JoinAlgorithm.NESTED_LOOP);
join.setProperty(Property.JOIN_TYPE, JoinType.INNER);
- join.setProperty(Property.JOIN_CONDITION, new EquiJoinCondition(selector("all"), name("a2"), selector("all"), name("a3")));
+ join.setProperty(Property.JOIN_CONDITION, new EquiJoinCondition(selector("all"), "a2", selector("all"), "a3"));
PlanNode leftAccess = new PlanNode(Type.ACCESS, join, selector("all"));
PlanNode leftProject = new PlanNode(Type.PROJECT, leftAccess, selector("all"));
leftProject.setProperty(Property.PROJECT_COLUMNS, columns(column("all", "a1"), column("all", "a2")));
PlanNode leftSelect1 = new PlanNode(Type.SELECT, leftProject, selector("all"));
- leftSelect1.setProperty(Property.SELECT_CRITERIA,
- new SetCriteria(new PropertyValue(selector("all"), name("primaryType")), new Literal("t1"),
- new Literal("t0")));
+ leftSelect1.setProperty(Property.SELECT_CRITERIA, new SetCriteria(new PropertyValue(selector("all"), "primaryType"),
+ new Literal("t1"), new Literal("t0")));
PlanNode leftSelect2 = new PlanNode(Type.SELECT, leftSelect1, selector("all"));
- leftSelect2.setProperty(Property.SELECT_CRITERIA, new SetCriteria(new PropertyValue(selector("all"), name("mixins")),
+ leftSelect2.setProperty(Property.SELECT_CRITERIA, new SetCriteria(new PropertyValue(selector("all"), "mixins"),
new Literal("t3"), new Literal("t4")));
PlanNode leftSource = new PlanNode(Type.SOURCE, leftSelect2, selector("all"));
leftSource.setProperty(Property.SOURCE_NAME, selector("all"));
@@ -388,11 +387,10 @@
PlanNode rightProject = new PlanNode(Type.PROJECT, rightAccess, selector("all"));
rightProject.setProperty(Property.PROJECT_COLUMNS, columns(column("all", "a3"), column("all", "a4")));
PlanNode rightSelect1 = new PlanNode(Type.SELECT, rightProject, selector("all"));
- rightSelect1.setProperty(Property.SELECT_CRITERIA,
- new SetCriteria(new PropertyValue(selector("all"), name("primaryType")), new Literal("t2"),
- new Literal("t0")));
+ rightSelect1.setProperty(Property.SELECT_CRITERIA, new SetCriteria(new PropertyValue(selector("all"), "primaryType"),
+ new Literal("t2"), new Literal("t0")));
PlanNode rightSelect2 = new PlanNode(Type.SELECT, rightSelect1, selector("all"));
- rightSelect2.setProperty(Property.SELECT_CRITERIA, new SetCriteria(new PropertyValue(selector("all"), name("mixins")),
+ rightSelect2.setProperty(Property.SELECT_CRITERIA, new SetCriteria(new PropertyValue(selector("all"), "mixins"),
new Literal("t4"), new Literal("t5")));
PlanNode rightSource = new PlanNode(Type.SOURCE, rightSelect2, selector("all"));
rightSource.setProperty(Property.SOURCE_NAME, selector("all"));
@@ -415,18 +413,18 @@
column("all", "a3", "c"),
column("all", "a4", "d")));
PlanNode select1 = new PlanNode(Type.SELECT, project, selector("all"));
- select1.setProperty(Property.SELECT_CRITERIA, new FullTextSearch(selector("all"), name("a2"), "something"));
+ select1.setProperty(Property.SELECT_CRITERIA, new FullTextSearch(selector("all"), "a2", "something"));
PlanNode select2 = new PlanNode(Type.SELECT, select1, selector("all"));
- select2.setProperty(Property.SELECT_CRITERIA, new SetCriteria(new PropertyValue(selector("all"), name("primaryType")),
+ select2.setProperty(Property.SELECT_CRITERIA, new SetCriteria(new PropertyValue(selector("all"), "primaryType"),
new Literal("t1"), new Literal("t0")));
PlanNode select3 = new PlanNode(Type.SELECT, select2, selector("all"));
- select3.setProperty(Property.SELECT_CRITERIA, new SetCriteria(new PropertyValue(selector("all"), name("mixins")),
+ select3.setProperty(Property.SELECT_CRITERIA, new SetCriteria(new PropertyValue(selector("all"), "mixins"),
new Literal("t3"), new Literal("t4")));
PlanNode select4 = new PlanNode(Type.SELECT, select3, selector("all"));
- select4.setProperty(Property.SELECT_CRITERIA, new SetCriteria(new PropertyValue(selector("all"), name("primaryType")),
+ select4.setProperty(Property.SELECT_CRITERIA, new SetCriteria(new PropertyValue(selector("all"), "primaryType"),
new Literal("t2"), new Literal("t0")));
PlanNode select5 = new PlanNode(Type.SELECT, select4, selector("all"));
- select5.setProperty(Property.SELECT_CRITERIA, new SetCriteria(new PropertyValue(selector("all"), name("mixins")),
+ select5.setProperty(Property.SELECT_CRITERIA, new SetCriteria(new PropertyValue(selector("all"), "mixins"),
new Literal("t4"), new Literal("t5")));
PlanNode source = new PlanNode(Type.SOURCE, select5, selector("all"));
source.setProperty(Property.SOURCE_NAME, selector("all"));
@@ -446,21 +444,17 @@
protected Column column( String table,
String columnName ) {
- return new Column(new SelectorName(table), name(columnName), columnName);
+ return new Column(new SelectorName(table), columnName, columnName);
}
protected Column column( String table,
String columnName,
String alias ) {
- return new Column(new SelectorName(table), name(columnName), alias);
+ return new Column(new SelectorName(table), columnName, alias);
}
- protected Name name( String name ) {
- return context.getExecutionContext().getValueFactories().getNameFactory().create(name);
- }
-
protected PlanNode optimize( String sql ) {
- QueryCommand query = new SqlQueryParser().parseQuery(sql, context.getExecutionContext());
+ QueryCommand query = new SqlQueryParser().parseQuery(sql, context.getTypeSystem());
Problems problems = context.getProblems();
assertThat("Problems parsing query: " + sql + "\n" + problems, problems.hasErrors(), is(false));
PlanNode plan = new CanonicalPlanner().createPlan(context, query);
Modified: trunk/dna-graph/src/test/java/org/jboss/dna/graph/query/parse/QueryParsersTest.java
===================================================================
--- trunk/dna-graph/src/test/java/org/jboss/dna/graph/query/parse/QueryParsersTest.java 2009-11-24 17:44:29 UTC (rev 1339)
+++ trunk/dna-graph/src/test/java/org/jboss/dna/graph/query/parse/QueryParsersTest.java 2009-11-24 17:46:37 UTC (rev 1340)
@@ -27,6 +27,7 @@
import static org.junit.Assert.assertThat;
import org.jboss.dna.graph.ExecutionContext;
import org.jboss.dna.graph.query.model.QueryCommand;
+import org.jboss.dna.graph.query.model.TypeSystem;
import org.junit.Before;
import org.junit.Test;
@@ -138,7 +139,8 @@
@Test( expected = IllegalArgumentException.class )
public void shouldFailToParseUnknownLanguage() {
- parsers.parse(new ExecutionContext(), "unknown language", "This is a bogus query");
+ TypeSystem typeSystem = new ExecutionContext().getValueFactories().getTypeSystem();
+ parsers.parse(typeSystem, "unknown language", "This is a bogus query");
}
protected static class MockParser implements QueryParser {
@@ -161,10 +163,11 @@
/**
* {@inheritDoc}
*
- * @see org.jboss.dna.graph.query.parse.QueryParser#parseQuery(java.lang.String, org.jboss.dna.graph.ExecutionContext)
+ * @see org.jboss.dna.graph.query.parse.QueryParser#parseQuery(java.lang.String,
+ * org.jboss.dna.graph.query.model.TypeSystem)
*/
public QueryCommand parseQuery( String query,
- ExecutionContext context ) throws InvalidQueryException {
+ TypeSystem typeSystem ) throws InvalidQueryException {
throw new UnsupportedOperationException();
}
Modified: trunk/dna-graph/src/test/java/org/jboss/dna/graph/query/parse/SqlQueryParserTest.java
===================================================================
--- trunk/dna-graph/src/test/java/org/jboss/dna/graph/query/parse/SqlQueryParserTest.java 2009-11-24 17:44:29 UTC (rev 1339)
+++ trunk/dna-graph/src/test/java/org/jboss/dna/graph/query/parse/SqlQueryParserTest.java 2009-11-24 17:46:37 UTC (rev 1340)
@@ -38,6 +38,7 @@
import org.jboss.dna.graph.property.Binary;
import org.jboss.dna.graph.property.Name;
import org.jboss.dna.graph.property.Path;
+import org.jboss.dna.graph.property.PropertyType;
import org.jboss.dna.graph.query.model.And;
import org.jboss.dna.graph.query.model.Between;
import org.jboss.dna.graph.query.model.BindVariableName;
@@ -68,6 +69,7 @@
import org.jboss.dna.graph.query.model.SelectorName;
import org.jboss.dna.graph.query.model.Source;
import org.jboss.dna.graph.query.model.StaticOperand;
+import org.jboss.dna.graph.query.model.TypeSystem;
import org.jboss.dna.graph.query.model.UpperCase;
import org.jboss.dna.graph.query.model.FullTextSearch.Conjunction;
import org.jboss.dna.graph.query.model.FullTextSearch.Disjunction;
@@ -80,12 +82,12 @@
*/
public class SqlQueryParserTest {
- private ExecutionContext context;
+ private TypeSystem typeSystem;
private SqlQueryParser parser;
@Before
public void beforeEach() {
- context = new ExecutionContext();
+ typeSystem = new ExecutionContext().getValueFactories().getTypeSystem();
parser = new SqlQueryParser();
}
@@ -265,7 +267,7 @@
protected void assertParseConstraint( String expression ) {
NamedSelector selector = new NamedSelector(selectorName("tableA"));
- parser.parseConstraint(tokens(expression), context, selector);
+ parser.parseConstraint(tokens(expression), typeSystem, selector);
}
// ----------------------------------------------------------------------------------------------------------------
@@ -275,7 +277,7 @@
@Test
public void shouldParseConstraintFromStringWithValidBetweenExpressionUsing() {
NamedSelector selector = new NamedSelector(selectorName("tableA"));
- Constraint constraint = parser.parseConstraint(tokens("tableA.id BETWEEN 'lower' AND 'upper'"), context, selector);
+ Constraint constraint = parser.parseConstraint(tokens("tableA.id BETWEEN 'lower' AND 'upper'"), typeSystem, selector);
assertThat(constraint, is(instanceOf(Between.class)));
Between between = (Between)constraint;
assertThat(between.isLowerBoundIncluded(), is(true));
@@ -283,7 +285,7 @@
assertThat(between.getOperand(), is(instanceOf(PropertyValue.class)));
PropertyValue operand = (PropertyValue)between.getOperand();
assertThat(operand.getSelectorName(), is(selector.getName()));
- assertThat(operand.getPropertyName(), is(name("id")));
+ assertThat(operand.getPropertyName(), is("id"));
assertThat(between.getLowerBound(), is(instanceOf(Literal.class)));
assertThat(between.getLowerBound(), is(instanceOf(Literal.class)));
assertThat((Literal)between.getLowerBound(), is(literal("lower")));
@@ -294,7 +296,7 @@
public void shouldParseConstraintFromStringWithValidBetweenExpressionUsingExclusiveAndExclusive() {
NamedSelector selector = new NamedSelector(selectorName("tableA"));
Constraint constraint = parser.parseConstraint(tokens("tableA.id BETWEEN 'lower' EXCLUSIVE AND 'upper' EXCLUSIVE"),
- context,
+ typeSystem,
selector);
assertThat(constraint, is(instanceOf(Between.class)));
Between between = (Between)constraint;
@@ -303,7 +305,7 @@
assertThat(between.getOperand(), is(instanceOf(PropertyValue.class)));
PropertyValue operand = (PropertyValue)between.getOperand();
assertThat(operand.getSelectorName(), is(selector.getName()));
- assertThat(operand.getPropertyName(), is(name("id")));
+ assertThat(operand.getPropertyName(), is("id"));
assertThat(between.getLowerBound(), is(instanceOf(Literal.class)));
assertThat(between.getLowerBound(), is(instanceOf(Literal.class)));
assertThat((Literal)between.getLowerBound(), is(literal("lower")));
@@ -314,7 +316,7 @@
public void shouldParseConstraintFromStringWithValidBetweenExpressionUsingInclusiveAndExclusive() {
NamedSelector selector = new NamedSelector(selectorName("tableA"));
Constraint constraint = parser.parseConstraint(tokens("tableA.id BETWEEN 'lower' AND 'upper' EXCLUSIVE"),
- context,
+ typeSystem,
selector);
assertThat(constraint, is(instanceOf(Between.class)));
Between between = (Between)constraint;
@@ -323,7 +325,7 @@
assertThat(between.getOperand(), is(instanceOf(PropertyValue.class)));
PropertyValue operand = (PropertyValue)between.getOperand();
assertThat(operand.getSelectorName(), is(selector.getName()));
- assertThat(operand.getPropertyName(), is(name("id")));
+ assertThat(operand.getPropertyName(), is("id"));
assertThat(between.getLowerBound(), is(instanceOf(Literal.class)));
assertThat(between.getLowerBound(), is(instanceOf(Literal.class)));
assertThat((Literal)between.getLowerBound(), is(literal("lower")));
@@ -334,7 +336,7 @@
public void shouldParseConstraintFromStringWithValidBetweenExpressionUsingExclusiveAndInclusive() {
NamedSelector selector = new NamedSelector(selectorName("tableA"));
Constraint constraint = parser.parseConstraint(tokens("tableA.id BETWEEN 'lower' EXCLUSIVE AND 'upper'"),
- context,
+ typeSystem,
selector);
assertThat(constraint, is(instanceOf(Between.class)));
Between between = (Between)constraint;
@@ -343,7 +345,7 @@
assertThat(between.getOperand(), is(instanceOf(PropertyValue.class)));
PropertyValue operand = (PropertyValue)between.getOperand();
assertThat(operand.getSelectorName(), is(selector.getName()));
- assertThat(operand.getPropertyName(), is(name("id")));
+ assertThat(operand.getPropertyName(), is("id"));
assertThat(between.getLowerBound(), is(instanceOf(Literal.class)));
assertThat(between.getLowerBound(), is(instanceOf(Literal.class)));
assertThat((Literal)between.getLowerBound(), is(literal("lower")));
@@ -353,7 +355,7 @@
@Test
public void shouldParseConstraintFromStringWithValidNotBetweenExpression() {
NamedSelector selector = new NamedSelector(selectorName("tableA"));
- Constraint constraint = parser.parseConstraint(tokens("tableA.id NOT BETWEEN 'lower' AND 'upper'"), context, selector);
+ Constraint constraint = parser.parseConstraint(tokens("tableA.id NOT BETWEEN 'lower' AND 'upper'"), typeSystem, selector);
assertThat(constraint, is(instanceOf(Not.class)));
constraint = ((Not)constraint).getConstraint();
assertThat(constraint, is(instanceOf(Between.class)));
@@ -363,7 +365,7 @@
assertThat(between.getOperand(), is(instanceOf(PropertyValue.class)));
PropertyValue operand = (PropertyValue)between.getOperand();
assertThat(operand.getSelectorName(), is(selector.getName()));
- assertThat(operand.getPropertyName(), is(name("id")));
+ assertThat(operand.getPropertyName(), is("id"));
assertThat(between.getLowerBound(), is(instanceOf(Literal.class)));
assertThat(between.getLowerBound(), is(instanceOf(Literal.class)));
assertThat((Literal)between.getLowerBound(), is(literal("lower")));
@@ -377,28 +379,28 @@
@Test
public void shouldParseConstraintFromStringWithOuterParentheses() {
NamedSelector selector = new NamedSelector(selectorName("tableA"));
- Constraint constraint = parser.parseConstraint(tokens("( ISSAMENODE('/a/b') )"), context, selector);
+ Constraint constraint = parser.parseConstraint(tokens("( ISSAMENODE('/a/b') )"), typeSystem, selector);
assertThat(constraint, is(instanceOf(SameNode.class)));
SameNode same = (SameNode)constraint;
assertThat(same.getSelectorName(), is(selectorName("tableA")));
- assertThat(same.getPath(), is(path("/a/b")));
+ assertThat(same.getPath(), is("/a/b"));
}
@Test
public void shouldParseConstraintFromStringWithMultipleOuterParentheses() {
NamedSelector selector = new NamedSelector(selectorName("tableA"));
- Constraint constraint = parser.parseConstraint(tokens("((( ISSAMENODE('/a/b') )))"), context, selector);
+ Constraint constraint = parser.parseConstraint(tokens("((( ISSAMENODE('/a/b') )))"), typeSystem, selector);
assertThat(constraint, is(instanceOf(SameNode.class)));
SameNode same = (SameNode)constraint;
assertThat(same.getSelectorName(), is(selectorName("tableA")));
- assertThat(same.getPath(), is(path("/a/b")));
+ assertThat(same.getPath(), is("/a/b"));
}
@Test
public void shouldParseConstraintFromStringWithParenthesesAndConjunctionAndDisjunctions() {
NamedSelector selector = new NamedSelector(selectorName("tableA"));
Constraint constraint = parser.parseConstraint(tokens("ISSAMENODE('/a/b') OR (ISSAMENODE('/c/d') AND ISSAMENODE('/e/f'))"),
- context,
+ typeSystem,
selector);
assertThat(constraint, is(instanceOf(Or.class)));
Or or = (Or)constraint;
@@ -406,7 +408,7 @@
assertThat(or.getLeft(), is(instanceOf(SameNode.class)));
SameNode first = (SameNode)or.getLeft();
assertThat(first.getSelectorName(), is(selectorName("tableA")));
- assertThat(first.getPath(), is(path("/a/b")));
+ assertThat(first.getPath(), is("/a/b"));
assertThat(or.getRight(), is(instanceOf(And.class)));
And and = (And)or.getRight();
@@ -414,12 +416,12 @@
assertThat(and.getLeft(), is(instanceOf(SameNode.class)));
SameNode second = (SameNode)and.getLeft();
assertThat(second.getSelectorName(), is(selectorName("tableA")));
- assertThat(second.getPath(), is(path("/c/d")));
+ assertThat(second.getPath(), is("/c/d"));
assertThat(and.getRight(), is(instanceOf(SameNode.class)));
SameNode third = (SameNode)and.getRight();
assertThat(third.getSelectorName(), is(selectorName("tableA")));
- assertThat(third.getPath(), is(path("/e/f")));
+ assertThat(third.getPath(), is("/e/f"));
}
// ----------------------------------------------------------------------------------------------------------------
@@ -429,19 +431,21 @@
@Test
public void shouldParseConstraintFromStringWithAndExpressionWithNoParentheses() {
NamedSelector selector = new NamedSelector(selectorName("tableA"));
- Constraint constraint = parser.parseConstraint(tokens("ISSAMENODE('/a/b/c') AND CONTAINS(p1,term1)"), context, selector);
+ Constraint constraint = parser.parseConstraint(tokens("ISSAMENODE('/a/b/c') AND CONTAINS(p1,term1)"),
+ typeSystem,
+ selector);
assertThat(constraint, is(instanceOf(And.class)));
And and = (And)constraint;
assertThat(and.getLeft(), is(instanceOf(SameNode.class)));
SameNode same = (SameNode)and.getLeft();
assertThat(same.getSelectorName(), is(selectorName("tableA")));
- assertThat(same.getPath(), is(path("/a/b/c")));
+ assertThat(same.getPath(), is("/a/b/c"));
assertThat(and.getRight(), is(instanceOf(FullTextSearch.class)));
FullTextSearch search = (FullTextSearch)and.getRight();
assertThat(search.getSelectorName(), is(selectorName("tableA")));
- assertThat(search.getPropertyName(), is(name("p1")));
+ assertThat(search.getPropertyName(), is("p1"));
assertThat(search.getFullTextSearchExpression(), is("term1"));
}
@@ -449,7 +453,7 @@
public void shouldParseConstraintFromStringWithMultipleAndExpressions() {
NamedSelector selector = new NamedSelector(selectorName("tableA"));
Constraint constraint = parser.parseConstraint(tokens("ISSAMENODE('/a/b/c') AND CONTAINS(p1,term1) AND CONTAINS(p2,term2)"),
- context,
+ typeSystem,
selector);
assertThat(constraint, is(instanceOf(And.class)));
And and = (And)constraint;
@@ -457,7 +461,7 @@
assertThat(and.getLeft(), is(instanceOf(SameNode.class)));
SameNode same = (SameNode)and.getLeft();
assertThat(same.getSelectorName(), is(selectorName("tableA")));
- assertThat(same.getPath(), is(path("/a/b/c")));
+ assertThat(same.getPath(), is("/a/b/c"));
assertThat(and.getRight(), is(instanceOf(And.class)));
And secondAnd = (And)and.getRight();
@@ -465,20 +469,20 @@
assertThat(secondAnd.getLeft(), is(instanceOf(FullTextSearch.class)));
FullTextSearch search1 = (FullTextSearch)secondAnd.getLeft();
assertThat(search1.getSelectorName(), is(selectorName("tableA")));
- assertThat(search1.getPropertyName(), is(name("p1")));
+ assertThat(search1.getPropertyName(), is("p1"));
assertThat(search1.getFullTextSearchExpression(), is("term1"));
assertThat(secondAnd.getRight(), is(instanceOf(FullTextSearch.class)));
FullTextSearch search2 = (FullTextSearch)secondAnd.getRight();
assertThat(search2.getSelectorName(), is(selectorName("tableA")));
- assertThat(search2.getPropertyName(), is(name("p2")));
+ assertThat(search2.getPropertyName(), is("p2"));
assertThat(search2.getFullTextSearchExpression(), is("term2"));
}
@Test( expected = ParsingException.class )
public void shouldFailToParseConstraintFromStringWithAndExpressionWithNoSecondConstraint() {
NamedSelector selector = new NamedSelector(selectorName("tableA"));
- parser.parseConstraint(tokens("ISSAMENODE('/a/b/c') AND WHAT THE HECK IS THIS"), context, selector);
+ parser.parseConstraint(tokens("ISSAMENODE('/a/b/c') AND WHAT THE HECK IS THIS"), typeSystem, selector);
}
// ----------------------------------------------------------------------------------------------------------------
@@ -488,19 +492,19 @@
@Test
public void shouldParseConstraintFromStringWithOrExpressionWithNoParentheses() {
NamedSelector selector = new NamedSelector(selectorName("tableA"));
- Constraint constraint = parser.parseConstraint(tokens("ISSAMENODE('/a/b/c') OR CONTAINS(p1,term1)"), context, selector);
+ Constraint constraint = parser.parseConstraint(tokens("ISSAMENODE('/a/b/c') OR CONTAINS(p1,term1)"), typeSystem, selector);
assertThat(constraint, is(instanceOf(Or.class)));
Or or = (Or)constraint;
assertThat(or.getLeft(), is(instanceOf(SameNode.class)));
SameNode same = (SameNode)or.getLeft();
assertThat(same.getSelectorName(), is(selectorName("tableA")));
- assertThat(same.getPath(), is(path("/a/b/c")));
+ assertThat(same.getPath(), is("/a/b/c"));
assertThat(or.getRight(), is(instanceOf(FullTextSearch.class)));
FullTextSearch search = (FullTextSearch)or.getRight();
assertThat(search.getSelectorName(), is(selectorName("tableA")));
- assertThat(search.getPropertyName(), is(name("p1")));
+ assertThat(search.getPropertyName(), is("p1"));
assertThat(search.getFullTextSearchExpression(), is("term1"));
}
@@ -508,7 +512,7 @@
@Test( expected = ParsingException.class )
public void shouldFailToParseConstraintFromStringWithOrExpressionWithNoSecondConstraint() {
NamedSelector selector = new NamedSelector(selectorName("tableA"));
- parser.parseConstraint(tokens("ISSAMENODE('/a/b/c') OR WHAT THE HECK IS THIS"), context, selector);
+ parser.parseConstraint(tokens("ISSAMENODE('/a/b/c') OR WHAT THE HECK IS THIS"), typeSystem, selector);
}
// ----------------------------------------------------------------------------------------------------------------
@@ -517,23 +521,23 @@
@Test
public void shouldParseConstraintFromStringWithNotSameNodeExpression() {
- Constraint constraint = parser.parseConstraint(tokens("NOT(ISSAMENODE(tableA,'/a/b/c'))"), context, mock(Source.class));
+ Constraint constraint = parser.parseConstraint(tokens("NOT(ISSAMENODE(tableA,'/a/b/c'))"), typeSystem, mock(Source.class));
assertThat(constraint, is(instanceOf(Not.class)));
Not not = (Not)constraint;
assertThat(not.getConstraint(), is(instanceOf(SameNode.class)));
SameNode same = (SameNode)not.getConstraint();
assertThat(same.getSelectorName(), is(selectorName("tableA")));
- assertThat(same.getPath(), is(path("/a/b/c")));
+ assertThat(same.getPath(), is("/a/b/c"));
}
@Test( expected = ParsingException.class )
public void shouldFailToParseConstraintFromStringWithNotConstraintWithOutOpeningParenthesis() {
- parser.parseConstraint(tokens("NOT CONTAINS(propertyA 'term1 term2 -term3')"), context, mock(Source.class));
+ parser.parseConstraint(tokens("NOT CONTAINS(propertyA 'term1 term2 -term3')"), typeSystem, mock(Source.class));
}
@Test( expected = ParsingException.class )
public void shouldFailToParseConstraintFromStringWithNotConstraintWithOutClosingParenthesis() {
- parser.parseConstraint(tokens("NOT( CONTAINS(propertyA 'term1 term2 -term3') BLAH"), context, mock(Source.class));
+ parser.parseConstraint(tokens("NOT( CONTAINS(propertyA 'term1 term2 -term3') BLAH"), typeSystem, mock(Source.class));
}
// ----------------------------------------------------------------------------------------------------------------
@@ -543,30 +547,30 @@
@Test
public void shouldParseConstraintFromStringWithIsContainsExpressionWithPropertyAndNoSelectorNameOnlyIfThereIsOneSelectorSource() {
NamedSelector selector = new NamedSelector(selectorName("tableA"));
- Constraint constraint = parser.parseConstraint(tokens("CONTAINS(propertyA,'term1 term2 -term3')"), context, selector);
+ Constraint constraint = parser.parseConstraint(tokens("CONTAINS(propertyA,'term1 term2 -term3')"), typeSystem, selector);
assertThat(constraint, is(instanceOf(FullTextSearch.class)));
FullTextSearch search = (FullTextSearch)constraint;
assertThat(search.getSelectorName(), is(selectorName("tableA")));
- assertThat(search.getPropertyName(), is(name("propertyA")));
+ assertThat(search.getPropertyName(), is("propertyA"));
assertThat(search.getFullTextSearchExpression(), is("term1 term2 -term3"));
}
@Test
public void shouldParseConstraintFromStringWithIsContainsExpressionWithSelectorNameAndProperty() {
Constraint constraint = parser.parseConstraint(tokens("CONTAINS(tableA.propertyA,'term1 term2 -term3')"),
- context,
+ typeSystem,
mock(Source.class));
assertThat(constraint, is(instanceOf(FullTextSearch.class)));
FullTextSearch search = (FullTextSearch)constraint;
assertThat(search.getSelectorName(), is(selectorName("tableA")));
- assertThat(search.getPropertyName(), is(name("propertyA")));
+ assertThat(search.getPropertyName(), is("propertyA"));
assertThat(search.getFullTextSearchExpression(), is("term1 term2 -term3"));
}
@Test
public void shouldParseConstraintFromStringWithIsContainsExpressionWithSelectorNameAndAnyProperty() {
Constraint constraint = parser.parseConstraint(tokens("CONTAINS(tableA.*,'term1 term2 -term3')"),
- context,
+ typeSystem,
mock(Source.class));
assertThat(constraint, is(instanceOf(FullTextSearch.class)));
FullTextSearch search = (FullTextSearch)constraint;
@@ -577,22 +581,22 @@
@Test( expected = ParsingException.class )
public void shouldFailToParseConstraintFromStringWithContainsExpressionWithNoCommaAfterSelectorName() {
- parser.parseConstraint(tokens("CONTAINS(propertyA 'term1 term2 -term3')"), context, mock(Source.class));
+ parser.parseConstraint(tokens("CONTAINS(propertyA 'term1 term2 -term3')"), typeSystem, mock(Source.class));
}
@Test( expected = ParsingException.class )
public void shouldFailToParseConstraintFromStringWithContainsExpressionWithNoClosingParenthesis() {
- parser.parseConstraint(tokens("CONTAINS(propertyA,'term1 term2 -term3' OTHER"), context, mock(Source.class));
+ parser.parseConstraint(tokens("CONTAINS(propertyA,'term1 term2 -term3' OTHER"), typeSystem, mock(Source.class));
}
@Test( expected = ParsingException.class )
public void shouldFailToParseConstraintFromStringWithContainsExpressionWithNoOpeningParenthesis() {
- parser.parseConstraint(tokens("CONTAINS propertyA,'term1 term2 -term3')"), context, mock(Source.class));
+ parser.parseConstraint(tokens("CONTAINS propertyA,'term1 term2 -term3')"), typeSystem, mock(Source.class));
}
@Test( expected = ParsingException.class )
public void shouldFailToParseConstraintFromStringWithContainsExpressionWithNoSelectorNameIfSourceIsNotSelector() {
- parser.parseConstraint(tokens("CONTAINS(propertyA,'term1 term2 -term3')"), context, mock(Join.class));
+ parser.parseConstraint(tokens("CONTAINS(propertyA,'term1 term2 -term3')"), typeSystem, mock(Join.class));
}
// ----------------------------------------------------------------------------------------------------------------
@@ -602,40 +606,40 @@
@Test
public void shouldParseConstraintFromStringWithIsSameNodeExpressionWithPathOnlyIfThereIsOneSelectorSource() {
NamedSelector selector = new NamedSelector(selectorName("tableA"));
- Constraint constraint = parser.parseConstraint(tokens("ISSAMENODE('/a/b/c')"), context, selector);
+ Constraint constraint = parser.parseConstraint(tokens("ISSAMENODE('/a/b/c')"), typeSystem, selector);
assertThat(constraint, is(instanceOf(SameNode.class)));
SameNode same = (SameNode)constraint;
assertThat(same.getSelectorName(), is(selectorName("tableA")));
- assertThat(same.getPath(), is(path("/a/b/c")));
+ assertThat(same.getPath(), is("/a/b/c"));
}
@Test
public void shouldParseConstraintFromStringWithIsSameNodeExpressionWithSelectorNameAndPath() {
- Constraint constraint = parser.parseConstraint(tokens("ISSAMENODE(tableA,'/a/b/c')"), context, mock(Source.class));
+ Constraint constraint = parser.parseConstraint(tokens("ISSAMENODE(tableA,'/a/b/c')"), typeSystem, mock(Source.class));
assertThat(constraint, is(instanceOf(SameNode.class)));
SameNode same = (SameNode)constraint;
assertThat(same.getSelectorName(), is(selectorName("tableA")));
- assertThat(same.getPath(), is(path("/a/b/c")));
+ assertThat(same.getPath(), is("/a/b/c"));
}
@Test( expected = ParsingException.class )
public void shouldFailToParseConstraintFromStringWithIsSameNodeExpressionWithNoCommaAfterSelectorName() {
- parser.parseConstraint(tokens("ISSAMENODE(tableA '/a/b/c')"), context, mock(Source.class));
+ parser.parseConstraint(tokens("ISSAMENODE(tableA '/a/b/c')"), typeSystem, mock(Source.class));
}
@Test( expected = ParsingException.class )
public void shouldFailToParseConstraintFromStringWithIsSameNodeExpressionWithNoClosingParenthesis() {
- parser.parseConstraint(tokens("ISSAMENODE(tableA,'/a/b/c' AND"), context, mock(Source.class));
+ parser.parseConstraint(tokens("ISSAMENODE(tableA,'/a/b/c' AND"), typeSystem, mock(Source.class));
}
@Test( expected = ParsingException.class )
public void shouldFailToParseConstraintFromStringWithIsSameNodeExpressionWithNoOpeningParenthesis() {
- parser.parseConstraint(tokens("ISSAMENODE tableA,'/a/b/c')"), context, mock(Source.class));
+ parser.parseConstraint(tokens("ISSAMENODE tableA,'/a/b/c')"), typeSystem, mock(Source.class));
}
@Test( expected = ParsingException.class )
public void shouldFailToParseConstraintFromStringWithIsSameNodeExpressionWithNoSelectorNameIfSourceIsNotSelector() {
- parser.parseConstraint(tokens("ISSAMENODE('/a/b/c')"), context, mock(Join.class));
+ parser.parseConstraint(tokens("ISSAMENODE('/a/b/c')"), typeSystem, mock(Join.class));
}
// ----------------------------------------------------------------------------------------------------------------
@@ -645,40 +649,40 @@
@Test
public void shouldParseConstraintFromStringWithIsChildNodeExpressionWithPathOnlyIfThereIsOneSelectorSource() {
NamedSelector selector = new NamedSelector(selectorName("tableA"));
- Constraint constraint = parser.parseConstraint(tokens("ISCHILDNODE('/a/b/c')"), context, selector);
+ Constraint constraint = parser.parseConstraint(tokens("ISCHILDNODE('/a/b/c')"), typeSystem, selector);
assertThat(constraint, is(instanceOf(ChildNode.class)));
ChildNode child = (ChildNode)constraint;
assertThat(child.getSelectorName(), is(selectorName("tableA")));
- assertThat(child.getParentPath(), is(path("/a/b/c")));
+ assertThat(child.getParentPath(), is("/a/b/c"));
}
@Test
public void shouldParseConstraintFromStringWithIsChildNodeExpressionWithSelectorNameAndPath() {
- Constraint constraint = parser.parseConstraint(tokens("ISCHILDNODE(tableA,'/a/b/c')"), context, mock(Source.class));
+ Constraint constraint = parser.parseConstraint(tokens("ISCHILDNODE(tableA,'/a/b/c')"), typeSystem, mock(Source.class));
assertThat(constraint, is(instanceOf(ChildNode.class)));
ChildNode child = (ChildNode)constraint;
assertThat(child.getSelectorName(), is(selectorName("tableA")));
- assertThat(child.getParentPath(), is(path("/a/b/c")));
+ assertThat(child.getParentPath(), is("/a/b/c"));
}
@Test( expected = ParsingException.class )
public void shouldFailToParseConstraintFromStringWithIsChildNodeExpressionWithNoCommaAfterSelectorName() {
- parser.parseConstraint(tokens("ISCHILDNODE(tableA '/a/b/c')"), context, mock(Source.class));
+ parser.parseConstraint(tokens("ISCHILDNODE(tableA '/a/b/c')"), typeSystem, mock(Source.class));
}
@Test( expected = ParsingException.class )
public void shouldFailToParseConstraintFromStringWithIsChildNodeExpressionWithNoClosingParenthesis() {
- parser.parseConstraint(tokens("ISCHILDNODE(tableA,'/a/b/c' AND"), context, mock(Source.class));
+ parser.parseConstraint(tokens("ISCHILDNODE(tableA,'/a/b/c' AND"), typeSystem, mock(Source.class));
}
@Test( expected = ParsingException.class )
public void shouldFailToParseConstraintFromStringWithIsChildNodeExpressionWithNoOpeningParenthesis() {
- parser.parseConstraint(tokens("ISCHILDNODE tableA,'/a/b/c')"), context, mock(Source.class));
+ parser.parseConstraint(tokens("ISCHILDNODE tableA,'/a/b/c')"), typeSystem, mock(Source.class));
}
@Test( expected = ParsingException.class )
public void shouldFailToParseConstraintFromStringWithIsChildNodeExpressionWithNoSelectorNameIfSourceIsNotSelector() {
- parser.parseConstraint(tokens("ISCHILDNODE('/a/b/c')"), context, mock(Join.class));
+ parser.parseConstraint(tokens("ISCHILDNODE('/a/b/c')"), typeSystem, mock(Join.class));
}
// ----------------------------------------------------------------------------------------------------------------
@@ -688,40 +692,42 @@
@Test
public void shouldParseConstraintFromStringWithIsDescendantNodeExpressionWithPathOnlyIfThereIsOneSelectorSource() {
NamedSelector selector = new NamedSelector(selectorName("tableA"));
- Constraint constraint = parser.parseConstraint(tokens("ISDESCENDANTNODE('/a/b/c')"), context, selector);
+ Constraint constraint = parser.parseConstraint(tokens("ISDESCENDANTNODE('/a/b/c')"), typeSystem, selector);
assertThat(constraint, is(instanceOf(DescendantNode.class)));
DescendantNode descendant = (DescendantNode)constraint;
assertThat(descendant.getSelectorName(), is(selectorName("tableA")));
- assertThat(descendant.getAncestorPath(), is(path("/a/b/c")));
+ assertThat(descendant.getAncestorPath(), is("/a/b/c"));
}
@Test
public void shouldParseConstraintFromStringWithIsDescendantNodeExpressionWithSelectorNameAndPath() {
- Constraint constraint = parser.parseConstraint(tokens("ISDESCENDANTNODE(tableA,'/a/b/c')"), context, mock(Source.class));
+ Constraint constraint = parser.parseConstraint(tokens("ISDESCENDANTNODE(tableA,'/a/b/c')"),
+ typeSystem,
+ mock(Source.class));
assertThat(constraint, is(instanceOf(DescendantNode.class)));
DescendantNode descendant = (DescendantNode)constraint;
assertThat(descendant.getSelectorName(), is(selectorName("tableA")));
- assertThat(descendant.getAncestorPath(), is(path("/a/b/c")));
+ assertThat(descendant.getAncestorPath(), is("/a/b/c"));
}
@Test( expected = ParsingException.class )
public void shouldFailToParseConstraintFromStringWithIsDescendantNodeExpressionWithNoCommaAfterSelectorName() {
- parser.parseConstraint(tokens("ISDESCENDANTNODE(tableA '/a/b/c')"), context, mock(Source.class));
+ parser.parseConstraint(tokens("ISDESCENDANTNODE(tableA '/a/b/c')"), typeSystem, mock(Source.class));
}
@Test( expected = ParsingException.class )
public void shouldFailToParseConstraintFromStringWithIsDescendantNodeExpressionWithNoClosingParenthesis() {
- parser.parseConstraint(tokens("ISDESCENDANTNODE(tableA,'/a/b/c' AND"), context, mock(Source.class));
+ parser.parseConstraint(tokens("ISDESCENDANTNODE(tableA,'/a/b/c' AND"), typeSystem, mock(Source.class));
}
@Test( expected = ParsingException.class )
public void shouldFailToParseConstraintFromStringWithIsDescendantNodeExpressionWithNoOpeningParenthesis() {
- parser.parseConstraint(tokens("ISDESCENDANTNODE tableA,'/a/b/c')"), context, mock(Source.class));
+ parser.parseConstraint(tokens("ISDESCENDANTNODE tableA,'/a/b/c')"), typeSystem, mock(Source.class));
}
@Test( expected = ParsingException.class )
public void shouldFailToParseConstraintFromStringWithIsDescendantNodeExpressionWithNoSelectorNameIfSourceIsNotSelector() {
- parser.parseConstraint(tokens("ISDESCENDANTNODE('/a/b/c')"), context, mock(Join.class));
+ parser.parseConstraint(tokens("ISDESCENDANTNODE('/a/b/c')"), typeSystem, mock(Join.class));
}
// ----------------------------------------------------------------------------------------------------------------
@@ -730,14 +736,14 @@
@Test
public void shouldParseInClauseFromStringWithSingleValidLiteral() {
- List<StaticOperand> result = parser.parseInClause(tokens("IN ('value1')"), context);
+ List<StaticOperand> result = parser.parseInClause(tokens("IN ('value1')"), typeSystem);
assertThat(result.size(), is(1));
assertThat(result.get(0), is((StaticOperand)literal("value1")));
}
@Test
public void shouldParseInClauseFromStringWithTwoValidLiteral() {
- List<StaticOperand> result = parser.parseInClause(tokens("IN ('value1','value2')"), context);
+ List<StaticOperand> result = parser.parseInClause(tokens("IN ('value1','value2')"), typeSystem);
assertThat(result.size(), is(2));
assertThat(result.get(0), is((StaticOperand)literal("value1")));
assertThat(result.get(1), is((StaticOperand)literal("value2")));
@@ -745,7 +751,7 @@
@Test
public void shouldParseInClauseFromStringWithThreeValidLiteral() {
- List<StaticOperand> result = parser.parseInClause(tokens("IN ('value1','value2','value3')"), context);
+ List<StaticOperand> result = parser.parseInClause(tokens("IN ('value1','value2','value3')"), typeSystem);
assertThat(result.size(), is(3));
assertThat(result.get(0), is((StaticOperand)literal("value1")));
assertThat(result.get(1), is((StaticOperand)literal("value2")));
@@ -754,18 +760,19 @@
@Test
public void shouldParseInClauseFromStringWithSingleValidLiteralCast() {
- List<StaticOperand> result = parser.parseInClause(tokens("IN (CAST('value1' AS STRING))"), context);
+ List<StaticOperand> result = parser.parseInClause(tokens("IN (CAST('value1' AS STRING))"), typeSystem);
assertThat(result.size(), is(1));
assertThat(result.iterator().next(), is((StaticOperand)literal("value1")));
- result = parser.parseInClause(tokens("IN (CAST('3' AS LONG))"), context);
+ result = parser.parseInClause(tokens("IN (CAST('3' AS LONG))"), typeSystem);
assertThat(result.size(), is(1));
assertThat(result.iterator().next(), is((StaticOperand)literal(new Long(3))));
}
@Test
public void shouldParseInClauseFromStringWithMultipleValidLiteralCasts() {
- List<StaticOperand> result = parser.parseInClause(tokens("IN (CAST('value1' AS STRING),CAST('3' AS LONG),'4')"), context);
+ List<StaticOperand> result = parser.parseInClause(tokens("IN (CAST('value1' AS STRING),CAST('3' AS LONG),'4')"),
+ typeSystem);
assertThat(result.size(), is(3));
assertThat(result.get(0), is((StaticOperand)literal("value1")));
assertThat(result.get(1), is((StaticOperand)literal(new Long(3))));
@@ -840,7 +847,7 @@
@Test
public void shouldParserOrderByWithOneOrdering() {
- List<Ordering> orderBy = parser.parseOrderBy(tokens("ORDER BY NAME(tableA) ASC"), context, mock(Source.class));
+ List<Ordering> orderBy = parser.parseOrderBy(tokens("ORDER BY NAME(tableA) ASC"), typeSystem, mock(Source.class));
assertThat(orderBy.size(), is(1));
Ordering first = orderBy.get(0);
assertThat(first.getOperand(), is(instanceOf(NodeName.class)));
@@ -850,7 +857,7 @@
@Test
public void shouldParserOrderByWithTwoOrderings() {
List<Ordering> orderBy = parser.parseOrderBy(tokens("ORDER BY NAME(tableA) ASC, SCORE(tableB) DESC"),
- context,
+ typeSystem,
mock(Source.class));
assertThat(orderBy.size(), is(2));
Ordering first = orderBy.get(0);
@@ -864,7 +871,7 @@
@Test
public void shouldParserOrderByWithMultipleOrderings() {
List<Ordering> orderBy = parser.parseOrderBy(tokens("ORDER BY NAME(tableA) ASC, SCORE(tableB) DESC, LENGTH(tableC.id) ASC"),
- context,
+ typeSystem,
mock(Source.class));
assertThat(orderBy.size(), is(3));
Ordering first = orderBy.get(0);
@@ -880,12 +887,12 @@
@Test( expected = ParsingException.class )
public void shouldFailToParseOrderByIfCommaNotFollowedByAnotherOrdering() {
- parser.parseOrderBy(tokens("ORDER BY NAME(tableA) ASC, NOT A VALID ORDERING"), context, mock(Source.class));
+ parser.parseOrderBy(tokens("ORDER BY NAME(tableA) ASC, NOT A VALID ORDERING"), typeSystem, mock(Source.class));
}
@Test
public void shouldReturnNullFromParseOrderByWithoutOrderByKeywords() {
- assertThat(parser.parseOrderBy(tokens("NOT ORDER BY"), context, mock(Source.class)), is(nullValue()));
+ assertThat(parser.parseOrderBy(tokens("NOT ORDER BY"), typeSystem, mock(Source.class)), is(nullValue()));
}
// ----------------------------------------------------------------------------------------------------------------
@@ -894,21 +901,21 @@
@Test
public void shouldParseOrderingFromDynamicOperandFollowedByAscendingKeyword() {
- Ordering ordering = parser.parseOrdering(tokens("NAME(tableA) ASC"), context, mock(Source.class));
+ Ordering ordering = parser.parseOrdering(tokens("NAME(tableA) ASC"), typeSystem, mock(Source.class));
assertThat(ordering.getOperand(), is(instanceOf(NodeName.class)));
assertThat(ordering.getOrder(), is(Order.ASCENDING));
}
@Test
public void shouldParseOrderingFromDynamicOperandFollowedByDecendingKeyword() {
- Ordering ordering = parser.parseOrdering(tokens("NAME(tableA) DESC"), context, mock(Source.class));
+ Ordering ordering = parser.parseOrdering(tokens("NAME(tableA) DESC"), typeSystem, mock(Source.class));
assertThat(ordering.getOperand(), is(instanceOf(NodeName.class)));
assertThat(ordering.getOrder(), is(Order.DESCENDING));
}
@Test
public void shouldParseOrderingFromDynamicOperandAndDefaultToAscendingWhenNotFollowedByAscendingOrDescendingKeyword() {
- Ordering ordering = parser.parseOrdering(tokens("NAME(tableA) OTHER"), context, mock(Source.class));
+ Ordering ordering = parser.parseOrdering(tokens("NAME(tableA) OTHER"), typeSystem, mock(Source.class));
assertThat(ordering.getOperand(), is(instanceOf(NodeName.class)));
assertThat(ordering.getOrder(), is(Order.ASCENDING));
}
@@ -919,45 +926,47 @@
@Test
public void shouldParsePropertyExistanceFromPropertyNameWithSelectorNameAndPropertyNameFollowedByIsNotNull() {
- Constraint constraint = parser.parsePropertyExistance(tokens("tableA.property1 IS NOT NULL"), context, mock(Source.class));
+ Constraint constraint = parser.parsePropertyExistance(tokens("tableA.property1 IS NOT NULL"),
+ typeSystem,
+ mock(Source.class));
assertThat(constraint, is(instanceOf(PropertyExistence.class)));
PropertyExistence p = (PropertyExistence)constraint;
- assertThat(p.getPropertyName(), is(name("property1")));
+ assertThat(p.getPropertyName(), is("property1"));
assertThat(p.getSelectorName(), is(selectorName("tableA")));
}
@Test
public void shouldParsePropertyExistanceFromPropertyNameWithPropertyNameAndNoSelectorNameFollowedByIsNotNull() {
NamedSelector source = new NamedSelector(selectorName("tableA"));
- Constraint constraint = parser.parsePropertyExistance(tokens("property1 IS NOT NULL"), context, source);
+ Constraint constraint = parser.parsePropertyExistance(tokens("property1 IS NOT NULL"), typeSystem, source);
assertThat(constraint, is(instanceOf(PropertyExistence.class)));
PropertyExistence p = (PropertyExistence)constraint;
- assertThat(p.getPropertyName(), is(name("property1")));
+ assertThat(p.getPropertyName(), is("property1"));
assertThat(p.getSelectorName(), is(selectorName("tableA")));
}
@Test( expected = ParsingException.class )
public void shouldFailToParsePropertyExistanceFromPropertyNameWithNoSelectorNameIfSourceIsNotSelector() {
- parser.parsePropertyExistance(tokens("property1 IS NOT NULL"), context, mock(Source.class));
+ parser.parsePropertyExistance(tokens("property1 IS NOT NULL"), typeSystem, mock(Source.class));
}
@Test
public void shouldParseNotPropertyExistanceFromPropertyNameWithSelectorNameAndPropertyNameFollowedByIsNull() {
- Constraint constraint = parser.parsePropertyExistance(tokens("tableA.property1 IS NULL"), context, mock(Source.class));
+ Constraint constraint = parser.parsePropertyExistance(tokens("tableA.property1 IS NULL"), typeSystem, mock(Source.class));
assertThat(constraint, is(instanceOf(Not.class)));
Not not = (Not)constraint;
assertThat(not.getConstraint(), is(instanceOf(PropertyExistence.class)));
PropertyExistence p = (PropertyExistence)not.getConstraint();
- assertThat(p.getPropertyName(), is(name("property1")));
+ assertThat(p.getPropertyName(), is("property1"));
assertThat(p.getSelectorName(), is(selectorName("tableA")));
}
@Test
public void shouldReturnNullFromParsePropertyExistanceIfExpressionDoesNotMatchPattern() {
Source s = mock(Source.class);
- assertThat(parser.parsePropertyExistance(tokens("tableA WILL NOT"), context, s), is(nullValue()));
- assertThat(parser.parsePropertyExistance(tokens("tableA.property1 NOT NULL"), context, s), is(nullValue()));
- assertThat(parser.parsePropertyExistance(tokens("tableA.property1 IS NOT SOMETHING"), context, s), is(nullValue()));
+ assertThat(parser.parsePropertyExistance(tokens("tableA WILL NOT"), typeSystem, s), is(nullValue()));
+ assertThat(parser.parsePropertyExistance(tokens("tableA.property1 NOT NULL"), typeSystem, s), is(nullValue()));
+ assertThat(parser.parsePropertyExistance(tokens("tableA.property1 IS NOT SOMETHING"), typeSystem, s), is(nullValue()));
}
// ----------------------------------------------------------------------------------------------------------------
@@ -966,7 +975,7 @@
@Test
public void shouldParseStaticOperandFromStringWithBindVariable() {
- StaticOperand operand = parser.parseStaticOperand(tokens("$VAR"), context);
+ StaticOperand operand = parser.parseStaticOperand(tokens("$VAR"), typeSystem);
assertThat(operand, is(instanceOf(BindVariableName.class)));
BindVariableName var = (BindVariableName)operand;
assertThat(var.getVariableName(), is("VAR"));
@@ -974,20 +983,20 @@
@Test( expected = ParsingException.class )
public void shouldFailToParseStaticOperandFromStringWithBindVariableWithNoVariableName() {
- parser.parseStaticOperand(tokens("$"), context);
+ parser.parseStaticOperand(tokens("$"), typeSystem);
}
@Test( expected = ParsingException.class )
public void shouldFailToParseStaticOperandFromStringWithBindVariableWithCharactersThatAreNotFromNCName() {
- parser.parseStaticOperand(tokens("$#2VAR"), context);
+ parser.parseStaticOperand(tokens("$#2VAR"), typeSystem);
}
@Test
public void shouldParseStaticOperandFromStringWithLiteralValue() {
- StaticOperand operand = parser.parseStaticOperand(tokens("CAST(123 AS DOUBLE)"), context);
+ StaticOperand operand = parser.parseStaticOperand(tokens("CAST(123 AS DOUBLE)"), typeSystem);
assertThat(operand, is(instanceOf(Literal.class)));
Literal literal = (Literal)operand;
- assertThat((Double)literal.getValue(), is(context.getValueFactories().getDoubleFactory().create("123")));
+ assertThat((Double)literal.getValue(), is(typeSystem.getDoubleFactory().create("123")));
}
// ----------------------------------------------------------------------------------------------------------------
@@ -996,142 +1005,147 @@
@Test
public void shouldParseLiteralFromStringWithCastBooleanLiteralToString() {
- assertThat((String)parser.parseLiteral(tokens("CAST(true AS STRING)"), context).getValue(), is(Boolean.TRUE.toString()));
- assertThat((String)parser.parseLiteral(tokens("CAST(false AS STRING)"), context).getValue(), is(Boolean.FALSE.toString()));
- assertThat((String)parser.parseLiteral(tokens("CAST(TRUE AS STRING)"), context).getValue(), is(Boolean.TRUE.toString()));
- assertThat((String)parser.parseLiteral(tokens("CAST(FALSE AS STRING)"), context).getValue(), is(Boolean.FALSE.toString()));
- assertThat((String)parser.parseLiteral(tokens("CAST('true' AS stRinG)"), context).getValue(), is(Boolean.TRUE.toString()));
- assertThat((String)parser.parseLiteral(tokens("CAST(\"false\" AS string)"), context).getValue(),
+ assertThat((String)parser.parseLiteral(tokens("CAST(true AS STRING)"), typeSystem).getValue(),
+ is(Boolean.TRUE.toString()));
+ assertThat((String)parser.parseLiteral(tokens("CAST(false AS STRING)"), typeSystem).getValue(),
is(Boolean.FALSE.toString()));
+ assertThat((String)parser.parseLiteral(tokens("CAST(TRUE AS STRING)"), typeSystem).getValue(),
+ is(Boolean.TRUE.toString()));
+ assertThat((String)parser.parseLiteral(tokens("CAST(FALSE AS STRING)"), typeSystem).getValue(),
+ is(Boolean.FALSE.toString()));
+ assertThat((String)parser.parseLiteral(tokens("CAST('true' AS stRinG)"), typeSystem).getValue(),
+ is(Boolean.TRUE.toString()));
+ assertThat((String)parser.parseLiteral(tokens("CAST(\"false\" AS string)"), typeSystem).getValue(),
+ is(Boolean.FALSE.toString()));
}
@Test
public void shouldParseLiteralFromStringWithCastBooleanLiteralToBinary() {
- Binary binaryTrue = context.getValueFactories().getBinaryFactory().create(true);
- Binary binaryFalse = context.getValueFactories().getBinaryFactory().create(false);
- assertThat((Binary)parser.parseLiteral(tokens("CAST(true AS BINARY)"), context).getValue(), is(binaryTrue));
- assertThat((Binary)parser.parseLiteral(tokens("CAST(false AS BINARY)"), context).getValue(), is(binaryFalse));
- assertThat((Binary)parser.parseLiteral(tokens("CAST(TRUE AS BINARY)"), context).getValue(), is(binaryTrue));
- assertThat((Binary)parser.parseLiteral(tokens("CAST(FALSE AS BINARY)"), context).getValue(), is(binaryFalse));
- assertThat((Binary)parser.parseLiteral(tokens("CAST('true' AS biNarY)"), context).getValue(), is(binaryTrue));
- assertThat((Binary)parser.parseLiteral(tokens("CAST(\"false\" AS binary)"), context).getValue(), is(binaryFalse));
+ Binary binaryTrue = (Binary)typeSystem.getTypeFactory(PropertyType.BINARY.getName()).create(true);
+ Binary binaryFalse = (Binary)typeSystem.getTypeFactory(PropertyType.BINARY.getName()).create(false);
+ assertThat((Binary)parser.parseLiteral(tokens("CAST(true AS BINARY)"), typeSystem).getValue(), is(binaryTrue));
+ assertThat((Binary)parser.parseLiteral(tokens("CAST(false AS BINARY)"), typeSystem).getValue(), is(binaryFalse));
+ assertThat((Binary)parser.parseLiteral(tokens("CAST(TRUE AS BINARY)"), typeSystem).getValue(), is(binaryTrue));
+ assertThat((Binary)parser.parseLiteral(tokens("CAST(FALSE AS BINARY)"), typeSystem).getValue(), is(binaryFalse));
+ assertThat((Binary)parser.parseLiteral(tokens("CAST('true' AS biNarY)"), typeSystem).getValue(), is(binaryTrue));
+ assertThat((Binary)parser.parseLiteral(tokens("CAST(\"false\" AS binary)"), typeSystem).getValue(), is(binaryFalse));
}
@Test( expected = ParsingException.class )
public void shouldFailToParseLiteralFromStringWithCastBooleanLiteralToLong() {
- parser.parseLiteral(tokens("CAST(true AS LONG)"), context);
+ parser.parseLiteral(tokens("CAST(true AS LONG)"), typeSystem);
}
@Test( expected = ParsingException.class )
public void shouldFailToParseLiteralFromStringWithCastBooleanLiteralToDouble() {
- parser.parseLiteral(tokens("CAST(true AS DOUBLE)"), context);
+ parser.parseLiteral(tokens("CAST(true AS DOUBLE)"), typeSystem);
}
@Test( expected = ParsingException.class )
public void shouldFailToParseLiteralFromStringWithCastBooleanLiteralToDate() {
- parser.parseLiteral(tokens("CAST(true AS DATE)"), context);
+ parser.parseLiteral(tokens("CAST(true AS DATE)"), typeSystem);
}
@Test
public void shouldParseLiteralFromStringWithCastLongLiteralToString() {
- assertThat((String)parser.parseLiteral(tokens("CAST(123 AS STRING)"), context).getValue(), is("123"));
- assertThat((String)parser.parseLiteral(tokens("CAST(+123 AS STRING)"), context).getValue(), is("123"));
- assertThat((String)parser.parseLiteral(tokens("CAST(-123 AS STRING)"), context).getValue(), is("-123"));
- assertThat((String)parser.parseLiteral(tokens("CAST(0 AS STRING)"), context).getValue(), is("0"));
+ assertThat((String)parser.parseLiteral(tokens("CAST(123 AS STRING)"), typeSystem).getValue(), is("123"));
+ assertThat((String)parser.parseLiteral(tokens("CAST(+123 AS STRING)"), typeSystem).getValue(), is("123"));
+ assertThat((String)parser.parseLiteral(tokens("CAST(-123 AS STRING)"), typeSystem).getValue(), is("-123"));
+ assertThat((String)parser.parseLiteral(tokens("CAST(0 AS STRING)"), typeSystem).getValue(), is("0"));
}
@Test
public void shouldParseLiteralFromStringWithCastLongLiteralToLong() {
- assertThat((Long)parser.parseLiteral(tokens("CAST(123 AS LONG)"), context).getValue(), is(123L));
- assertThat((Long)parser.parseLiteral(tokens("CAST(+123 AS LONG)"), context).getValue(), is(123L));
- assertThat((Long)parser.parseLiteral(tokens("CAST(-123 AS LONG)"), context).getValue(), is(-123L));
- assertThat((Long)parser.parseLiteral(tokens("CAST(0 AS LONG)"), context).getValue(), is(0L));
+ assertThat((Long)parser.parseLiteral(tokens("CAST(123 AS LONG)"), typeSystem).getValue(), is(123L));
+ assertThat((Long)parser.parseLiteral(tokens("CAST(+123 AS LONG)"), typeSystem).getValue(), is(123L));
+ assertThat((Long)parser.parseLiteral(tokens("CAST(-123 AS LONG)"), typeSystem).getValue(), is(-123L));
+ assertThat((Long)parser.parseLiteral(tokens("CAST(0 AS LONG)"), typeSystem).getValue(), is(0L));
}
@Test
public void shouldParseLiteralFromStringWithCastDoubleLiteralToString() {
- assertThat((String)parser.parseLiteral(tokens("CAST(1.23 AS STRING)"), context).getValue(), is("1.23"));
- assertThat((String)parser.parseLiteral(tokens("CAST(+1.23 AS STRING)"), context).getValue(), is("1.23"));
- assertThat((String)parser.parseLiteral(tokens("CAST(-1.23 AS STRING)"), context).getValue(), is("-1.23"));
- assertThat((String)parser.parseLiteral(tokens("CAST(1.23e10 AS STRING)"), context).getValue(), is("1.23E10"));
- assertThat((String)parser.parseLiteral(tokens("CAST(1.23e+10 AS STRING)"), context).getValue(), is("1.23E10"));
- assertThat((String)parser.parseLiteral(tokens("CAST(1.23e-10 AS STRING)"), context).getValue(), is("1.23E-10"));
+ assertThat((String)parser.parseLiteral(tokens("CAST(1.23 AS STRING)"), typeSystem).getValue(), is("1.23"));
+ assertThat((String)parser.parseLiteral(tokens("CAST(+1.23 AS STRING)"), typeSystem).getValue(), is("1.23"));
+ assertThat((String)parser.parseLiteral(tokens("CAST(-1.23 AS STRING)"), typeSystem).getValue(), is("-1.23"));
+ assertThat((String)parser.parseLiteral(tokens("CAST(1.23e10 AS STRING)"), typeSystem).getValue(), is("1.23E10"));
+ assertThat((String)parser.parseLiteral(tokens("CAST(1.23e+10 AS STRING)"), typeSystem).getValue(), is("1.23E10"));
+ assertThat((String)parser.parseLiteral(tokens("CAST(1.23e-10 AS STRING)"), typeSystem).getValue(), is("1.23E-10"));
}
@Test
public void shouldParseLiteralFromStringWithCastDateLiteralToString() {
- assertThat((String)parser.parseLiteral(tokens("CAST(2009-03-22T03:22:45.345Z AS STRING)"), context).getValue(),
+ assertThat((String)parser.parseLiteral(tokens("CAST(2009-03-22T03:22:45.345Z AS STRING)"), typeSystem).getValue(),
is("2009-03-22T03:22:45.345Z"));
- assertThat((String)parser.parseLiteral(tokens("CAST(2009-03-22T03:22:45.345UTC AS STRING)"), context).getValue(),
+ assertThat((String)parser.parseLiteral(tokens("CAST(2009-03-22T03:22:45.345UTC AS STRING)"), typeSystem).getValue(),
is("2009-03-22T03:22:45.345Z"));
- assertThat((String)parser.parseLiteral(tokens("CAST(2009-03-22T03:22:45.3-01:00 AS STRING)"), context).getValue(),
+ assertThat((String)parser.parseLiteral(tokens("CAST(2009-03-22T03:22:45.3-01:00 AS STRING)"), typeSystem).getValue(),
is("2009-03-22T04:22:45.300Z"));
- assertThat((String)parser.parseLiteral(tokens("CAST(2009-03-22T03:22:45.345+01:00 AS STRING)"), context).getValue(),
+ assertThat((String)parser.parseLiteral(tokens("CAST(2009-03-22T03:22:45.345+01:00 AS STRING)"), typeSystem).getValue(),
is("2009-03-22T02:22:45.345Z"));
}
@Test
public void shouldParseLiteralFromStringWithCastStringLiteralToName() {
- assertThat((Name)parser.parseLiteral(tokens("CAST([dna:name] AS NAME)"), context).getValue(), is(name("dna:name")));
- assertThat((Name)parser.parseLiteral(tokens("CAST('dna:name' AS NAME)"), context).getValue(), is(name("dna:name")));
- assertThat((Name)parser.parseLiteral(tokens("CAST(\"dna:name\" AS NAME)"), context).getValue(), is(name("dna:name")));
+ assertThat((Name)parser.parseLiteral(tokens("CAST([dna:name] AS NAME)"), typeSystem).getValue(), is(name("dna:name")));
+ assertThat((Name)parser.parseLiteral(tokens("CAST('dna:name' AS NAME)"), typeSystem).getValue(), is(name("dna:name")));
+ assertThat((Name)parser.parseLiteral(tokens("CAST(\"dna:name\" AS NAME)"), typeSystem).getValue(), is(name("dna:name")));
}
@Test
public void shouldParseLiteralFromStringWithCastStringLiteralToPath() {
- assertThat((Path)parser.parseLiteral(tokens("CAST([/dna:name/a/b] AS PATH)"), context).getValue(),
+ assertThat((Path)parser.parseLiteral(tokens("CAST([/dna:name/a/b] AS PATH)"), typeSystem).getValue(),
is(path("/dna:name/a/b")));
}
@Test
public void shouldParseLiteralFromStringWithUncastLiteralValueAndRepresentValueAsStringRepresentation() {
- assertThat(parser.parseLiteral(tokens("true"), context).getValue(), is((Object)Boolean.TRUE.toString()));
- assertThat(parser.parseLiteral(tokens("false"), context).getValue(), is((Object)Boolean.FALSE.toString()));
- assertThat(parser.parseLiteral(tokens("TRUE"), context).getValue(), is((Object)Boolean.TRUE.toString()));
- assertThat(parser.parseLiteral(tokens("FALSE"), context).getValue(), is((Object)Boolean.FALSE.toString()));
- assertThat(parser.parseLiteral(tokens("123"), context).getValue(), is((Object)"123"));
- assertThat(parser.parseLiteral(tokens("+123"), context).getValue(), is((Object)"123"));
- assertThat(parser.parseLiteral(tokens("-123"), context).getValue(), is((Object)"-123"));
- assertThat(parser.parseLiteral(tokens("1.23"), context).getValue(), is((Object)"1.23"));
- assertThat(parser.parseLiteral(tokens("+1.23"), context).getValue(), is((Object)"1.23"));
- assertThat(parser.parseLiteral(tokens("-1.23"), context).getValue(), is((Object)"-1.23"));
- assertThat(parser.parseLiteral(tokens("1.23e10"), context).getValue(), is((Object)"1.23E10"));
- assertThat(parser.parseLiteral(tokens("1.23e+10"), context).getValue(), is((Object)"1.23E10"));
- assertThat(parser.parseLiteral(tokens("1.23e-10"), context).getValue(), is((Object)"1.23E-10"));
- assertThat(parser.parseLiteral(tokens("0"), context).getValue(), is((Object)"0"));
- assertThat(parser.parseLiteral(tokens("2009-03-22T03:22:45.345Z"), context).getValue(),
+ assertThat(parser.parseLiteral(tokens("true"), typeSystem).getValue(), is((Object)Boolean.TRUE.toString()));
+ assertThat(parser.parseLiteral(tokens("false"), typeSystem).getValue(), is((Object)Boolean.FALSE.toString()));
+ assertThat(parser.parseLiteral(tokens("TRUE"), typeSystem).getValue(), is((Object)Boolean.TRUE.toString()));
+ assertThat(parser.parseLiteral(tokens("FALSE"), typeSystem).getValue(), is((Object)Boolean.FALSE.toString()));
+ assertThat(parser.parseLiteral(tokens("123"), typeSystem).getValue(), is((Object)"123"));
+ assertThat(parser.parseLiteral(tokens("+123"), typeSystem).getValue(), is((Object)"123"));
+ assertThat(parser.parseLiteral(tokens("-123"), typeSystem).getValue(), is((Object)"-123"));
+ assertThat(parser.parseLiteral(tokens("1.23"), typeSystem).getValue(), is((Object)"1.23"));
+ assertThat(parser.parseLiteral(tokens("+1.23"), typeSystem).getValue(), is((Object)"1.23"));
+ assertThat(parser.parseLiteral(tokens("-1.23"), typeSystem).getValue(), is((Object)"-1.23"));
+ assertThat(parser.parseLiteral(tokens("1.23e10"), typeSystem).getValue(), is((Object)"1.23E10"));
+ assertThat(parser.parseLiteral(tokens("1.23e+10"), typeSystem).getValue(), is((Object)"1.23E10"));
+ assertThat(parser.parseLiteral(tokens("1.23e-10"), typeSystem).getValue(), is((Object)"1.23E-10"));
+ assertThat(parser.parseLiteral(tokens("0"), typeSystem).getValue(), is((Object)"0"));
+ assertThat(parser.parseLiteral(tokens("2009-03-22T03:22:45.345Z"), typeSystem).getValue(),
is((Object)"2009-03-22T03:22:45.345Z"));
- assertThat(parser.parseLiteral(tokens("2009-03-22T03:22:45.345UTC"), context).getValue(),
+ assertThat(parser.parseLiteral(tokens("2009-03-22T03:22:45.345UTC"), typeSystem).getValue(),
is((Object)"2009-03-22T03:22:45.345Z"));
- assertThat(parser.parseLiteral(tokens("2009-03-22T03:22:45.3-01:00"), context).getValue(),
+ assertThat(parser.parseLiteral(tokens("2009-03-22T03:22:45.3-01:00"), typeSystem).getValue(),
is((Object)"2009-03-22T04:22:45.300Z"));
- assertThat(parser.parseLiteral(tokens("2009-03-22T03:22:45.345+01:00"), context).getValue(),
+ assertThat(parser.parseLiteral(tokens("2009-03-22T03:22:45.345+01:00"), typeSystem).getValue(),
is((Object)"2009-03-22T02:22:45.345Z"));
}
@Test( expected = ParsingException.class )
public void shouldFailToParseLiteralFromStringWithCastAndNoEndingParenthesis() {
- parser.parseLiteral(tokens("CAST(123 AS STRING OTHER"), context);
+ parser.parseLiteral(tokens("CAST(123 AS STRING OTHER"), typeSystem);
}
@Test( expected = ParsingException.class )
public void shouldFailToParseLiteralFromStringWithCastAndNoOpeningParenthesis() {
- parser.parseLiteral(tokens("CAST 123 AS STRING) OTHER"), context);
+ parser.parseLiteral(tokens("CAST 123 AS STRING) OTHER"), typeSystem);
}
@Test( expected = ParsingException.class )
public void shouldFailToParseLiteralFromStringWithCastAndInvalidType() {
- parser.parseLiteral(tokens("CAST(123 AS FOOD) OTHER"), context);
+ parser.parseLiteral(tokens("CAST(123 AS FOOD) OTHER"), typeSystem);
}
@Test( expected = ParsingException.class )
public void shouldFailToParseLiteralFromStringWithCastAndNoAsKeyword() {
- parser.parseLiteral(tokens("CAST(123 STRING) OTHER"), context);
+ parser.parseLiteral(tokens("CAST(123 STRING) OTHER"), typeSystem);
}
@Test( expected = ParsingException.class )
public void shouldFailToParseLiteralFromStringWithCastAndNoLiteralValueBeforeAs() {
- parser.parseLiteral(tokens("CAST(AS STRING) OTHER"), context);
+ parser.parseLiteral(tokens("CAST(AS STRING) OTHER"), typeSystem);
}
// ----------------------------------------------------------------------------------------------------------------
@@ -1140,54 +1154,55 @@
@Test
public void shouldParseLiteralValueFromStringWithPositiveAndNegativeIntegerValues() {
- assertThat(parser.parseLiteralValue(tokens("123"), context), is("123"));
- assertThat(parser.parseLiteralValue(tokens("-123"), context), is("-123"));
- assertThat(parser.parseLiteralValue(tokens("- 123"), context), is("-123"));
- assertThat(parser.parseLiteralValue(tokens("+123"), context), is("123"));
- assertThat(parser.parseLiteralValue(tokens("+ 123"), context), is("123"));
- assertThat(parser.parseLiteralValue(tokens("0"), context), is("0"));
+ assertThat(parser.parseLiteralValue(tokens("123"), typeSystem), is("123"));
+ assertThat(parser.parseLiteralValue(tokens("-123"), typeSystem), is("-123"));
+ assertThat(parser.parseLiteralValue(tokens("- 123"), typeSystem), is("-123"));
+ assertThat(parser.parseLiteralValue(tokens("+123"), typeSystem), is("123"));
+ assertThat(parser.parseLiteralValue(tokens("+ 123"), typeSystem), is("123"));
+ assertThat(parser.parseLiteralValue(tokens("0"), typeSystem), is("0"));
}
@Test
public void shouldParseLiteralValueFromStringWithPositiveAndNegativeDecimalValues() {
- assertThat(parser.parseLiteralValue(tokens("1.23"), context), is("1.23"));
- assertThat(parser.parseLiteralValue(tokens("-1.23"), context), is("-1.23"));
- assertThat(parser.parseLiteralValue(tokens("+0.123"), context), is("0.123"));
+ assertThat(parser.parseLiteralValue(tokens("1.23"), typeSystem), is("1.23"));
+ assertThat(parser.parseLiteralValue(tokens("-1.23"), typeSystem), is("-1.23"));
+ assertThat(parser.parseLiteralValue(tokens("+0.123"), typeSystem), is("0.123"));
}
@Test
public void shouldParseLiteralValueFromStringWithPositiveAndNegativeDecimalValuesInScientificNotation() {
- assertThat(parser.parseLiteralValue(tokens("1.23"), context), is("1.23"));
- assertThat(parser.parseLiteralValue(tokens("1.23e10"), context), is("1.23E10"));
- assertThat(parser.parseLiteralValue(tokens("- 1.23e10"), context), is("-1.23E10"));
- assertThat(parser.parseLiteralValue(tokens("- 1.23e-10"), context), is("-1.23E-10"));
+ assertThat(parser.parseLiteralValue(tokens("1.23"), typeSystem), is("1.23"));
+ assertThat(parser.parseLiteralValue(tokens("1.23e10"), typeSystem), is("1.23E10"));
+ assertThat(parser.parseLiteralValue(tokens("- 1.23e10"), typeSystem), is("-1.23E10"));
+ assertThat(parser.parseLiteralValue(tokens("- 1.23e-10"), typeSystem), is("-1.23E-10"));
}
@Test
public void shouldParseLiteralValueFromStringWithBooleanValues() {
- assertThat(parser.parseLiteralValue(tokens("true"), context), is(Boolean.TRUE.toString()));
- assertThat(parser.parseLiteralValue(tokens("false"), context), is(Boolean.FALSE.toString()));
- assertThat(parser.parseLiteralValue(tokens("TRUE"), context), is(Boolean.TRUE.toString()));
- assertThat(parser.parseLiteralValue(tokens("FALSE"), context), is(Boolean.FALSE.toString()));
+ assertThat(parser.parseLiteralValue(tokens("true"), typeSystem), is(Boolean.TRUE.toString()));
+ assertThat(parser.parseLiteralValue(tokens("false"), typeSystem), is(Boolean.FALSE.toString()));
+ assertThat(parser.parseLiteralValue(tokens("TRUE"), typeSystem), is(Boolean.TRUE.toString()));
+ assertThat(parser.parseLiteralValue(tokens("FALSE"), typeSystem), is(Boolean.FALSE.toString()));
}
@Test
public void shouldParseLiteralValueFromStringWithDateValues() {
// sYYYY-MM-DDThh:mm:ss.sssTZD
- assertThat(parser.parseLiteralValue(tokens("2009-03-22T03:22:45.345Z"), context), is("2009-03-22T03:22:45.345Z"));
- assertThat(parser.parseLiteralValue(tokens("2009-03-22T03:22:45.345UTC"), context), is("2009-03-22T03:22:45.345Z"));
- assertThat(parser.parseLiteralValue(tokens("2009-03-22T03:22:45.3-01:00"), context), is("2009-03-22T04:22:45.300Z"));
- assertThat(parser.parseLiteralValue(tokens("2009-03-22T03:22:45.345+01:00"), context), is("2009-03-22T02:22:45.345Z"));
+ assertThat(parser.parseLiteralValue(tokens("2009-03-22T03:22:45.345Z"), typeSystem), is("2009-03-22T03:22:45.345Z"));
+ assertThat(parser.parseLiteralValue(tokens("2009-03-22T03:22:45.345UTC"), typeSystem), is("2009-03-22T03:22:45.345Z"));
+ assertThat(parser.parseLiteralValue(tokens("2009-03-22T03:22:45.3-01:00"), typeSystem), is("2009-03-22T04:22:45.300Z"));
+ assertThat(parser.parseLiteralValue(tokens("2009-03-22T03:22:45.345+01:00"), typeSystem), is("2009-03-22T02:22:45.345Z"));
- assertThat(parser.parseLiteralValue(tokens("-2009-03-22T03:22:45.345Z"), context), is("-2009-03-22T03:22:45.345Z"));
- assertThat(parser.parseLiteralValue(tokens("-2009-03-22T03:22:45.345UTC"), context), is("-2009-03-22T03:22:45.345Z"));
- assertThat(parser.parseLiteralValue(tokens("-2009-03-22T03:22:45.3-01:00"), context), is("-2009-03-22T04:22:45.300Z"));
- assertThat(parser.parseLiteralValue(tokens("-2009-03-22T03:22:45.345+01:00"), context), is("-2009-03-22T02:22:45.345Z"));
+ assertThat(parser.parseLiteralValue(tokens("-2009-03-22T03:22:45.345Z"), typeSystem), is("-2009-03-22T03:22:45.345Z"));
+ assertThat(parser.parseLiteralValue(tokens("-2009-03-22T03:22:45.345UTC"), typeSystem), is("-2009-03-22T03:22:45.345Z"));
+ assertThat(parser.parseLiteralValue(tokens("-2009-03-22T03:22:45.3-01:00"), typeSystem), is("-2009-03-22T04:22:45.300Z"));
+ assertThat(parser.parseLiteralValue(tokens("-2009-03-22T03:22:45.345+01:00"), typeSystem),
+ is("-2009-03-22T02:22:45.345Z"));
- assertThat(parser.parseLiteralValue(tokens("+2009-03-22T03:22:45.345Z"), context), is("2009-03-22T03:22:45.345Z"));
- assertThat(parser.parseLiteralValue(tokens("+2009-03-22T03:22:45.345UTC"), context), is("2009-03-22T03:22:45.345Z"));
- assertThat(parser.parseLiteralValue(tokens("+2009-03-22T03:22:45.3-01:00"), context), is("2009-03-22T04:22:45.300Z"));
- assertThat(parser.parseLiteralValue(tokens("+2009-03-22T03:22:45.345+01:00"), context), is("2009-03-22T02:22:45.345Z"));
+ assertThat(parser.parseLiteralValue(tokens("+2009-03-22T03:22:45.345Z"), typeSystem), is("2009-03-22T03:22:45.345Z"));
+ assertThat(parser.parseLiteralValue(tokens("+2009-03-22T03:22:45.345UTC"), typeSystem), is("2009-03-22T03:22:45.345Z"));
+ assertThat(parser.parseLiteralValue(tokens("+2009-03-22T03:22:45.3-01:00"), typeSystem), is("2009-03-22T04:22:45.300Z"));
+ assertThat(parser.parseLiteralValue(tokens("+2009-03-22T03:22:45.345+01:00"), typeSystem), is("2009-03-22T02:22:45.345Z"));
}
// ----------------------------------------------------------------------------------------------------------------
@@ -1196,58 +1211,61 @@
@Test
public void shouldParseLiteralValueFromQuotedStringWithPositiveAndNegativeIntegerValues() {
- assertThat(parser.parseLiteralValue(tokens("'123'"), context), is("123"));
- assertThat(parser.parseLiteralValue(tokens("'-123'"), context), is("-123"));
- assertThat(parser.parseLiteralValue(tokens("'- 123'"), context), is("- 123"));
- assertThat(parser.parseLiteralValue(tokens("'+123'"), context), is("+123"));
- assertThat(parser.parseLiteralValue(tokens("'+ 123'"), context), is("+ 123"));
- assertThat(parser.parseLiteralValue(tokens("'0'"), context), is("0"));
+ assertThat(parser.parseLiteralValue(tokens("'123'"), typeSystem), is("123"));
+ assertThat(parser.parseLiteralValue(tokens("'-123'"), typeSystem), is("-123"));
+ assertThat(parser.parseLiteralValue(tokens("'- 123'"), typeSystem), is("- 123"));
+ assertThat(parser.parseLiteralValue(tokens("'+123'"), typeSystem), is("+123"));
+ assertThat(parser.parseLiteralValue(tokens("'+ 123'"), typeSystem), is("+ 123"));
+ assertThat(parser.parseLiteralValue(tokens("'0'"), typeSystem), is("0"));
}
@Test
public void shouldParseLiteralValueFromQuotedStringWithPositiveAndNegativeDecimalValues() {
- assertThat(parser.parseLiteralValue(tokens("'1.23'"), context), is("1.23"));
- assertThat(parser.parseLiteralValue(tokens("'-1.23'"), context), is("-1.23"));
- assertThat(parser.parseLiteralValue(tokens("'+0.123'"), context), is("+0.123"));
+ assertThat(parser.parseLiteralValue(tokens("'1.23'"), typeSystem), is("1.23"));
+ assertThat(parser.parseLiteralValue(tokens("'-1.23'"), typeSystem), is("-1.23"));
+ assertThat(parser.parseLiteralValue(tokens("'+0.123'"), typeSystem), is("+0.123"));
}
@Test
public void shouldParseLiteralValueFromQuotedStringWithPositiveAndNegativeDecimalValuesInScientificNotation() {
- assertThat(parser.parseLiteralValue(tokens("'1.23'"), context), is("1.23"));
- assertThat(parser.parseLiteralValue(tokens("'1.23e10'"), context), is("1.23e10"));
- assertThat(parser.parseLiteralValue(tokens("'- 1.23e10'"), context), is("- 1.23e10"));
- assertThat(parser.parseLiteralValue(tokens("'- 1.23e-10'"), context), is("- 1.23e-10"));
+ assertThat(parser.parseLiteralValue(tokens("'1.23'"), typeSystem), is("1.23"));
+ assertThat(parser.parseLiteralValue(tokens("'1.23e10'"), typeSystem), is("1.23e10"));
+ assertThat(parser.parseLiteralValue(tokens("'- 1.23e10'"), typeSystem), is("- 1.23e10"));
+ assertThat(parser.parseLiteralValue(tokens("'- 1.23e-10'"), typeSystem), is("- 1.23e-10"));
}
@Test
public void shouldParseLiteralValueFromQuotedStringWithBooleanValues() {
- assertThat(parser.parseLiteralValue(tokens("'true'"), context), is("true"));
- assertThat(parser.parseLiteralValue(tokens("'false'"), context), is("false"));
- assertThat(parser.parseLiteralValue(tokens("'TRUE'"), context), is("TRUE"));
- assertThat(parser.parseLiteralValue(tokens("'FALSE'"), context), is("FALSE"));
+ assertThat(parser.parseLiteralValue(tokens("'true'"), typeSystem), is("true"));
+ assertThat(parser.parseLiteralValue(tokens("'false'"), typeSystem), is("false"));
+ assertThat(parser.parseLiteralValue(tokens("'TRUE'"), typeSystem), is("TRUE"));
+ assertThat(parser.parseLiteralValue(tokens("'FALSE'"), typeSystem), is("FALSE"));
}
@Test
public void shouldParseLiteralValueFromQuotedStringWithDateValues() {
// sYYYY-MM-DDThh:mm:ss.sssTZD
- assertThat(parser.parseLiteralValue(tokens("'2009-03-22T03:22:45.345Z'"), context), is("2009-03-22T03:22:45.345Z"));
- assertThat(parser.parseLiteralValue(tokens("'2009-03-22T03:22:45.345UTC'"), context), is("2009-03-22T03:22:45.345UTC"));
- assertThat(parser.parseLiteralValue(tokens("'2009-03-22T03:22:45.3-01:00'"), context), is("2009-03-22T03:22:45.3-01:00"));
- assertThat(parser.parseLiteralValue(tokens("'2009-03-22T03:22:45.345+01:00'"), context),
+ assertThat(parser.parseLiteralValue(tokens("'2009-03-22T03:22:45.345Z'"), typeSystem), is("2009-03-22T03:22:45.345Z"));
+ assertThat(parser.parseLiteralValue(tokens("'2009-03-22T03:22:45.345UTC'"), typeSystem), is("2009-03-22T03:22:45.345UTC"));
+ assertThat(parser.parseLiteralValue(tokens("'2009-03-22T03:22:45.3-01:00'"), typeSystem),
+ is("2009-03-22T03:22:45.3-01:00"));
+ assertThat(parser.parseLiteralValue(tokens("'2009-03-22T03:22:45.345+01:00'"), typeSystem),
is("2009-03-22T03:22:45.345+01:00"));
- assertThat(parser.parseLiteralValue(tokens("'-2009-03-22T03:22:45.345Z'"), context), is("-2009-03-22T03:22:45.345Z"));
- assertThat(parser.parseLiteralValue(tokens("'-2009-03-22T03:22:45.345UTC'"), context), is("-2009-03-22T03:22:45.345UTC"));
- assertThat(parser.parseLiteralValue(tokens("'-2009-03-22T03:22:45.3-01:00'"), context),
+ assertThat(parser.parseLiteralValue(tokens("'-2009-03-22T03:22:45.345Z'"), typeSystem), is("-2009-03-22T03:22:45.345Z"));
+ assertThat(parser.parseLiteralValue(tokens("'-2009-03-22T03:22:45.345UTC'"), typeSystem),
+ is("-2009-03-22T03:22:45.345UTC"));
+ assertThat(parser.parseLiteralValue(tokens("'-2009-03-22T03:22:45.3-01:00'"), typeSystem),
is("-2009-03-22T03:22:45.3-01:00"));
- assertThat(parser.parseLiteralValue(tokens("'-2009-03-22T03:22:45.345+01:00'"), context),
+ assertThat(parser.parseLiteralValue(tokens("'-2009-03-22T03:22:45.345+01:00'"), typeSystem),
is("-2009-03-22T03:22:45.345+01:00"));
- assertThat(parser.parseLiteralValue(tokens("'+2009-03-22T03:22:45.345Z'"), context), is("+2009-03-22T03:22:45.345Z"));
- assertThat(parser.parseLiteralValue(tokens("'+2009-03-22T03:22:45.345UTC'"), context), is("+2009-03-22T03:22:45.345UTC"));
- assertThat(parser.parseLiteralValue(tokens("'+2009-03-22T03:22:45.3-01:00'"), context),
+ assertThat(parser.parseLiteralValue(tokens("'+2009-03-22T03:22:45.345Z'"), typeSystem), is("+2009-03-22T03:22:45.345Z"));
+ assertThat(parser.parseLiteralValue(tokens("'+2009-03-22T03:22:45.345UTC'"), typeSystem),
+ is("+2009-03-22T03:22:45.345UTC"));
+ assertThat(parser.parseLiteralValue(tokens("'+2009-03-22T03:22:45.3-01:00'"), typeSystem),
is("+2009-03-22T03:22:45.3-01:00"));
- assertThat(parser.parseLiteralValue(tokens("'+2009-03-22T03:22:45.345+01:00'"), context),
+ assertThat(parser.parseLiteralValue(tokens("'+2009-03-22T03:22:45.345+01:00'"), typeSystem),
is("+2009-03-22T03:22:45.345+01:00"));
}
@@ -1257,30 +1275,30 @@
@Test
public void shouldParseDynamicOperandFromStringContainingLengthOfPropertyValue() {
- DynamicOperand operand = parser.parseDynamicOperand(tokens("LENGTH(tableA.property)"), context, mock(Source.class));
+ DynamicOperand operand = parser.parseDynamicOperand(tokens("LENGTH(tableA.property)"), typeSystem, mock(Source.class));
assertThat(operand, is(instanceOf(Length.class)));
Length length = (Length)operand;
- assertThat(length.getPropertyValue().getPropertyName(), is(name("property")));
+ assertThat(length.getPropertyValue().getPropertyName(), is("property"));
assertThat(length.getPropertyValue().getSelectorName(), is(selectorName("tableA")));
assertThat(length.getSelectorName(), is(selectorName("tableA")));
Source source = new NamedSelector(selectorName("tableA"));
- operand = parser.parseDynamicOperand(tokens("LENGTH(property)"), context, source);
+ operand = parser.parseDynamicOperand(tokens("LENGTH(property)"), typeSystem, source);
assertThat(operand, is(instanceOf(Length.class)));
length = (Length)operand;
- assertThat(length.getPropertyValue().getPropertyName(), is(name("property")));
+ assertThat(length.getPropertyValue().getPropertyName(), is("property"));
assertThat(length.getPropertyValue().getSelectorName(), is(selectorName("tableA")));
assertThat(length.getSelectorName(), is(selectorName("tableA")));
}
@Test( expected = ParsingException.class )
public void shouldFailToParseDynamicOperandFromStringContainingLengthWithoutClosingParenthesis() {
- parser.parseDynamicOperand(tokens("LENGTH(tableA.property other"), context, mock(Source.class));
+ parser.parseDynamicOperand(tokens("LENGTH(tableA.property other"), typeSystem, mock(Source.class));
}
@Test( expected = ParsingException.class )
public void shouldFailToParseDynamicOperandFromStringContainingLengthWithoutOpeningParenthesis() {
- parser.parseDynamicOperand(tokens("LENGTH tableA.property other"), context, mock(Source.class));
+ parser.parseDynamicOperand(tokens("LENGTH tableA.property other"), typeSystem, mock(Source.class));
}
// ----------------------------------------------------------------------------------------------------------------
@@ -1289,29 +1307,31 @@
@Test
public void shouldParseDynamicOperandFromStringContainingLowerOfAnotherDynamicOperand() {
- DynamicOperand operand = parser.parseDynamicOperand(tokens("LOWER(tableA.property)"), context, mock(Source.class));
+ DynamicOperand operand = parser.parseDynamicOperand(tokens("LOWER(tableA.property)"), typeSystem, mock(Source.class));
assertThat(operand, is(instanceOf(LowerCase.class)));
LowerCase lower = (LowerCase)operand;
assertThat(lower.getSelectorName(), is(selectorName("tableA")));
assertThat(lower.getOperand(), is(instanceOf(PropertyValue.class)));
PropertyValue value = (PropertyValue)lower.getOperand();
- assertThat(value.getPropertyName(), is(name("property")));
+ assertThat(value.getPropertyName(), is("property"));
assertThat(value.getSelectorName(), is(selectorName("tableA")));
Source source = new NamedSelector(selectorName("tableA"));
- operand = parser.parseDynamicOperand(tokens("LOWER(property)"), context, source);
+ operand = parser.parseDynamicOperand(tokens("LOWER(property)"), typeSystem, source);
assertThat(operand, is(instanceOf(LowerCase.class)));
lower = (LowerCase)operand;
assertThat(lower.getSelectorName(), is(selectorName("tableA")));
assertThat(lower.getOperand(), is(instanceOf(PropertyValue.class)));
value = (PropertyValue)lower.getOperand();
- assertThat(value.getPropertyName(), is(name("property")));
+ assertThat(value.getPropertyName(), is("property"));
assertThat(value.getSelectorName(), is(selectorName("tableA")));
}
@Test
public void shouldParseDynamicOperandFromStringContainingLowerOfUpperCaseOfAnotherOperand() {
- DynamicOperand operand = parser.parseDynamicOperand(tokens("LOWER(UPPER(tableA.property))"), context, mock(Source.class));
+ DynamicOperand operand = parser.parseDynamicOperand(tokens("LOWER(UPPER(tableA.property))"),
+ typeSystem,
+ mock(Source.class));
assertThat(operand, is(instanceOf(LowerCase.class)));
LowerCase lower = (LowerCase)operand;
assertThat(lower.getSelectorName(), is(selectorName("tableA")));
@@ -1320,18 +1340,18 @@
assertThat(upper.getSelectorName(), is(selectorName("tableA")));
assertThat(upper.getOperand(), is(instanceOf(PropertyValue.class)));
PropertyValue value = (PropertyValue)upper.getOperand();
- assertThat(value.getPropertyName(), is(name("property")));
+ assertThat(value.getPropertyName(), is("property"));
assertThat(value.getSelectorName(), is(selectorName("tableA")));
}
@Test( expected = ParsingException.class )
public void shouldFailToParseDynamicOperandFromStringContainingLowerWithoutClosingParenthesis() {
- parser.parseDynamicOperand(tokens("LOWER(tableA.property other"), context, mock(Source.class));
+ parser.parseDynamicOperand(tokens("LOWER(tableA.property other"), typeSystem, mock(Source.class));
}
@Test( expected = ParsingException.class )
public void shouldFailToParseDynamicOperandFromStringContainingLowerWithoutOpeningParenthesis() {
- parser.parseDynamicOperand(tokens("LOWER tableA.property other"), context, mock(Source.class));
+ parser.parseDynamicOperand(tokens("LOWER tableA.property other"), typeSystem, mock(Source.class));
}
// ----------------------------------------------------------------------------------------------------------------
@@ -1340,29 +1360,31 @@
@Test
public void shouldParseDynamicOperandFromStringContainingUpperOfAnotherDynamicOperand() {
- DynamicOperand operand = parser.parseDynamicOperand(tokens("UPPER(tableA.property)"), context, mock(Source.class));
+ DynamicOperand operand = parser.parseDynamicOperand(tokens("UPPER(tableA.property)"), typeSystem, mock(Source.class));
assertThat(operand, is(instanceOf(UpperCase.class)));
UpperCase upper = (UpperCase)operand;
assertThat(upper.getSelectorName(), is(selectorName("tableA")));
assertThat(upper.getOperand(), is(instanceOf(PropertyValue.class)));
PropertyValue value = (PropertyValue)upper.getOperand();
- assertThat(value.getPropertyName(), is(name("property")));
+ assertThat(value.getPropertyName(), is("property"));
assertThat(value.getSelectorName(), is(selectorName("tableA")));
Source source = new NamedSelector(selectorName("tableA"));
- operand = parser.parseDynamicOperand(tokens("UPPER(property)"), context, source);
+ operand = parser.parseDynamicOperand(tokens("UPPER(property)"), typeSystem, source);
assertThat(operand, is(instanceOf(UpperCase.class)));
upper = (UpperCase)operand;
assertThat(upper.getSelectorName(), is(selectorName("tableA")));
assertThat(upper.getOperand(), is(instanceOf(PropertyValue.class)));
value = (PropertyValue)upper.getOperand();
- assertThat(value.getPropertyName(), is(name("property")));
+ assertThat(value.getPropertyName(), is("property"));
assertThat(value.getSelectorName(), is(selectorName("tableA")));
}
@Test
public void shouldParseDynamicOperandFromStringContainingUpperOfLowerCaseOfAnotherOperand() {
- DynamicOperand operand = parser.parseDynamicOperand(tokens("UPPER(LOWER(tableA.property))"), context, mock(Source.class));
+ DynamicOperand operand = parser.parseDynamicOperand(tokens("UPPER(LOWER(tableA.property))"),
+ typeSystem,
+ mock(Source.class));
assertThat(operand, is(instanceOf(UpperCase.class)));
UpperCase upper = (UpperCase)operand;
assertThat(upper.getSelectorName(), is(selectorName("tableA")));
@@ -1371,18 +1393,18 @@
assertThat(lower.getSelectorName(), is(selectorName("tableA")));
assertThat(lower.getOperand(), is(instanceOf(PropertyValue.class)));
PropertyValue value = (PropertyValue)lower.getOperand();
- assertThat(value.getPropertyName(), is(name("property")));
+ assertThat(value.getPropertyName(), is("property"));
assertThat(value.getSelectorName(), is(selectorName("tableA")));
}
@Test( expected = ParsingException.class )
public void shouldFailToParseDynamicOperandFromStringContainingUpperWithoutClosingParenthesis() {
- parser.parseDynamicOperand(tokens("UPPER(tableA.property other"), context, mock(Source.class));
+ parser.parseDynamicOperand(tokens("UPPER(tableA.property other"), typeSystem, mock(Source.class));
}
@Test( expected = ParsingException.class )
public void shouldFailToParseDynamicOperandFromStringContainingUpperWithoutOpeningParenthesis() {
- parser.parseDynamicOperand(tokens("Upper tableA.property other"), context, mock(Source.class));
+ parser.parseDynamicOperand(tokens("Upper tableA.property other"), typeSystem, mock(Source.class));
}
// ----------------------------------------------------------------------------------------------------------------
@@ -1391,7 +1413,7 @@
@Test
public void shouldParseDynamicOperandFromStringContainingDepthOfSelector() {
- DynamicOperand operand = parser.parseDynamicOperand(tokens("DEPTH(tableA)"), context, mock(Source.class));
+ DynamicOperand operand = parser.parseDynamicOperand(tokens("DEPTH(tableA)"), typeSystem, mock(Source.class));
assertThat(operand, is(instanceOf(NodeDepth.class)));
NodeDepth depth = (NodeDepth)operand;
assertThat(depth.getSelectorName(), is(selectorName("tableA")));
@@ -1400,7 +1422,7 @@
@Test
public void shouldParseDynamicOperandFromStringContainingDepthWithNoSelectorOnlyIfThereIsOneSelectorAsSource() {
Source source = new NamedSelector(selectorName("tableA"));
- DynamicOperand operand = parser.parseDynamicOperand(tokens("DEPTH()"), context, source);
+ DynamicOperand operand = parser.parseDynamicOperand(tokens("DEPTH()"), typeSystem, source);
assertThat(operand, is(instanceOf(NodeDepth.class)));
NodeDepth depth = (NodeDepth)operand;
assertThat(depth.getSelectorName(), is(selectorName("tableA")));
@@ -1408,22 +1430,22 @@
@Test( expected = ParsingException.class )
public void shouldFailToParseDynamicOperandFromStringContainingDepthWithNoSelectorIfTheSourceIsNotASelector() {
- parser.parseDynamicOperand(tokens("DEPTH()"), context, mock(Source.class));
+ parser.parseDynamicOperand(tokens("DEPTH()"), typeSystem, mock(Source.class));
}
@Test( expected = ParsingException.class )
public void shouldFailToParseDynamicOperandFromStringContainingDepthWithSelectorNameAndProperty() {
- parser.parseDynamicOperand(tokens("DEPTH(tableA.property) other"), context, mock(Source.class));
+ parser.parseDynamicOperand(tokens("DEPTH(tableA.property) other"), typeSystem, mock(Source.class));
}
@Test( expected = ParsingException.class )
public void shouldFailToParseDynamicOperandFromStringContainingDepthWithoutClosingParenthesis() {
- parser.parseDynamicOperand(tokens("DEPTH(tableA other"), context, mock(Source.class));
+ parser.parseDynamicOperand(tokens("DEPTH(tableA other"), typeSystem, mock(Source.class));
}
@Test( expected = ParsingException.class )
public void shouldFailToParseDynamicOperandFromStringContainingDepthWithoutOpeningParenthesis() {
- parser.parseDynamicOperand(tokens("Depth tableA other"), context, mock(Source.class));
+ parser.parseDynamicOperand(tokens("Depth tableA other"), typeSystem, mock(Source.class));
}
// ----------------------------------------------------------------------------------------------------------------
@@ -1432,7 +1454,7 @@
@Test
public void shouldParseDynamicOperandFromStringContainingPathOfSelector() {
- DynamicOperand operand = parser.parseDynamicOperand(tokens("PATH(tableA)"), context, mock(Source.class));
+ DynamicOperand operand = parser.parseDynamicOperand(tokens("PATH(tableA)"), typeSystem, mock(Source.class));
assertThat(operand, is(instanceOf(NodePath.class)));
NodePath path = (NodePath)operand;
assertThat(path.getSelectorName(), is(selectorName("tableA")));
@@ -1441,7 +1463,7 @@
@Test
public void shouldParseDynamicOperandFromStringContainingPathWithNoSelectorOnlyIfThereIsOneSelectorAsSource() {
Source source = new NamedSelector(selectorName("tableA"));
- DynamicOperand operand = parser.parseDynamicOperand(tokens("PATH()"), context, source);
+ DynamicOperand operand = parser.parseDynamicOperand(tokens("PATH()"), typeSystem, source);
assertThat(operand, is(instanceOf(NodePath.class)));
NodePath path = (NodePath)operand;
assertThat(path.getSelectorName(), is(selectorName("tableA")));
@@ -1449,22 +1471,22 @@
@Test( expected = ParsingException.class )
public void shouldFailToParseDynamicOperandFromStringContainingPathWithNoSelectorIfTheSourceIsNotASelector() {
- parser.parseDynamicOperand(tokens("PATH()"), context, mock(Source.class));
+ parser.parseDynamicOperand(tokens("PATH()"), typeSystem, mock(Source.class));
}
@Test( expected = ParsingException.class )
public void shouldFailToParseDynamicOperandFromStringContainingPathWithSelectorNameAndProperty() {
- parser.parseDynamicOperand(tokens("PATH(tableA.property) other"), context, mock(Source.class));
+ parser.parseDynamicOperand(tokens("PATH(tableA.property) other"), typeSystem, mock(Source.class));
}
@Test( expected = ParsingException.class )
public void shouldFailToParseDynamicOperandFromStringContainingPathWithoutClosingParenthesis() {
- parser.parseDynamicOperand(tokens("PATH(tableA other"), context, mock(Source.class));
+ parser.parseDynamicOperand(tokens("PATH(tableA other"), typeSystem, mock(Source.class));
}
@Test( expected = ParsingException.class )
public void shouldFailToParseDynamicOperandFromStringContainingPathWithoutOpeningParenthesis() {
- parser.parseDynamicOperand(tokens("Path tableA other"), context, mock(Source.class));
+ parser.parseDynamicOperand(tokens("Path tableA other"), typeSystem, mock(Source.class));
}
// ----------------------------------------------------------------------------------------------------------------
@@ -1473,7 +1495,7 @@
@Test
public void shouldParseDynamicOperandFromStringContainingNameOfSelector() {
- DynamicOperand operand = parser.parseDynamicOperand(tokens("NAME(tableA)"), context, mock(Source.class));
+ DynamicOperand operand = parser.parseDynamicOperand(tokens("NAME(tableA)"), typeSystem, mock(Source.class));
assertThat(operand, is(instanceOf(NodeName.class)));
NodeName name = (NodeName)operand;
assertThat(name.getSelectorName(), is(selectorName("tableA")));
@@ -1482,7 +1504,7 @@
@Test
public void shouldParseDynamicOperandFromStringContainingNameWithNoSelectorOnlyIfThereIsOneSelectorAsSource() {
Source source = new NamedSelector(selectorName("tableA"));
- DynamicOperand operand = parser.parseDynamicOperand(tokens("NAME()"), context, source);
+ DynamicOperand operand = parser.parseDynamicOperand(tokens("NAME()"), typeSystem, source);
assertThat(operand, is(instanceOf(NodeName.class)));
NodeName name = (NodeName)operand;
assertThat(name.getSelectorName(), is(selectorName("tableA")));
@@ -1490,22 +1512,22 @@
@Test( expected = ParsingException.class )
public void shouldFailToParseDynamicOperandFromStringContainingNameWithNoSelectorIfTheSourceIsNotASelector() {
- parser.parseDynamicOperand(tokens("NAME()"), context, mock(Source.class));
+ parser.parseDynamicOperand(tokens("NAME()"), typeSystem, mock(Source.class));
}
@Test( expected = ParsingException.class )
public void shouldFailToParseDynamicOperandFromStringContainingNameWithSelectorNameAndProperty() {
- parser.parseDynamicOperand(tokens("NAME(tableA.property) other"), context, mock(Source.class));
+ parser.parseDynamicOperand(tokens("NAME(tableA.property) other"), typeSystem, mock(Source.class));
}
@Test( expected = ParsingException.class )
public void shouldFailToParseDynamicOperandFromStringContainingNameWithoutClosingParenthesis() {
- parser.parseDynamicOperand(tokens("NAME(tableA other"), context, mock(Source.class));
+ parser.parseDynamicOperand(tokens("NAME(tableA other"), typeSystem, mock(Source.class));
}
@Test( expected = ParsingException.class )
public void shouldFailToParseDynamicOperandFromStringContainingNameWithoutOpeningParenthesis() {
- parser.parseDynamicOperand(tokens("Name tableA other"), context, mock(Source.class));
+ parser.parseDynamicOperand(tokens("Name tableA other"), typeSystem, mock(Source.class));
}
// ----------------------------------------------------------------------------------------------------------------
@@ -1514,7 +1536,7 @@
@Test
public void shouldParseDynamicOperandFromStringContainingLocalNameOfSelector() {
- DynamicOperand operand = parser.parseDynamicOperand(tokens("LOCALNAME(tableA)"), context, mock(Source.class));
+ DynamicOperand operand = parser.parseDynamicOperand(tokens("LOCALNAME(tableA)"), typeSystem, mock(Source.class));
assertThat(operand, is(instanceOf(NodeLocalName.class)));
NodeLocalName name = (NodeLocalName)operand;
assertThat(name.getSelectorName(), is(selectorName("tableA")));
@@ -1523,7 +1545,7 @@
@Test
public void shouldParseDynamicOperandFromStringContainingLocalNameWithNoSelectorOnlyIfThereIsOneSelectorAsSource() {
Source source = new NamedSelector(selectorName("tableA"));
- DynamicOperand operand = parser.parseDynamicOperand(tokens("LOCALNAME()"), context, source);
+ DynamicOperand operand = parser.parseDynamicOperand(tokens("LOCALNAME()"), typeSystem, source);
assertThat(operand, is(instanceOf(NodeLocalName.class)));
NodeLocalName name = (NodeLocalName)operand;
assertThat(name.getSelectorName(), is(selectorName("tableA")));
@@ -1531,22 +1553,22 @@
@Test( expected = ParsingException.class )
public void shouldFailToParseDynamicOperandFromStringContainingLocalNameWithNoSelectorIfTheSourceIsNotASelector() {
- parser.parseDynamicOperand(tokens("LOCALNAME()"), context, mock(Source.class));
+ parser.parseDynamicOperand(tokens("LOCALNAME()"), typeSystem, mock(Source.class));
}
@Test( expected = ParsingException.class )
public void shouldFailToParseDynamicOperandFromStringContainingLocalNameWithSelectorNameAndProperty() {
- parser.parseDynamicOperand(tokens("LOCALNAME(tableA.property) other"), context, mock(Source.class));
+ parser.parseDynamicOperand(tokens("LOCALNAME(tableA.property) other"), typeSystem, mock(Source.class));
}
@Test( expected = ParsingException.class )
public void shouldFailToParseDynamicOperandFromStringContainingLocalNameWithoutClosingParenthesis() {
- parser.parseDynamicOperand(tokens("LOCALNAME(tableA other"), context, mock(Source.class));
+ parser.parseDynamicOperand(tokens("LOCALNAME(tableA other"), typeSystem, mock(Source.class));
}
@Test( expected = ParsingException.class )
public void shouldFailToParseDynamicOperandFromStringContainingLocalNameWithoutOpeningParenthesis() {
- parser.parseDynamicOperand(tokens("LocalName tableA other"), context, mock(Source.class));
+ parser.parseDynamicOperand(tokens("LocalName tableA other"), typeSystem, mock(Source.class));
}
// ----------------------------------------------------------------------------------------------------------------
@@ -1555,7 +1577,7 @@
@Test
public void shouldParseDynamicOperandFromStringContainingFullTextSearchScoreOfSelector() {
- DynamicOperand operand = parser.parseDynamicOperand(tokens("SCORE(tableA)"), context, mock(Source.class));
+ DynamicOperand operand = parser.parseDynamicOperand(tokens("SCORE(tableA)"), typeSystem, mock(Source.class));
assertThat(operand, is(instanceOf(FullTextSearchScore.class)));
FullTextSearchScore score = (FullTextSearchScore)operand;
assertThat(score.getSelectorName(), is(selectorName("tableA")));
@@ -1564,7 +1586,7 @@
@Test
public void shouldParseDynamicOperandFromStringContainingFullTextSearchScoreWithNoSelectorOnlyIfThereIsOneSelectorAsSource() {
Source source = new NamedSelector(selectorName("tableA"));
- DynamicOperand operand = parser.parseDynamicOperand(tokens("SCORE()"), context, source);
+ DynamicOperand operand = parser.parseDynamicOperand(tokens("SCORE()"), typeSystem, source);
assertThat(operand, is(instanceOf(FullTextSearchScore.class)));
FullTextSearchScore score = (FullTextSearchScore)operand;
assertThat(score.getSelectorName(), is(selectorName("tableA")));
@@ -1572,22 +1594,22 @@
@Test( expected = ParsingException.class )
public void shouldFailToParseDynamicOperandFromStringContainingFullTextSearchScoreWithNoSelectorIfTheSourceIsNotASelector() {
- parser.parseDynamicOperand(tokens("SCORE()"), context, mock(Source.class));
+ parser.parseDynamicOperand(tokens("SCORE()"), typeSystem, mock(Source.class));
}
@Test( expected = ParsingException.class )
public void shouldFailToParseDynamicOperandFromStringContainingFullTextSearchScoreWithWithSelectorNameAndProperty() {
- parser.parseDynamicOperand(tokens("SCORE(tableA.property) other"), context, mock(Source.class));
+ parser.parseDynamicOperand(tokens("SCORE(tableA.property) other"), typeSystem, mock(Source.class));
}
@Test( expected = ParsingException.class )
public void shouldFailToParseDynamicOperandFromStringContainingFullTextSearchScoreWithoutClosingParenthesis() {
- parser.parseDynamicOperand(tokens("SCORE(tableA other"), context, mock(Source.class));
+ parser.parseDynamicOperand(tokens("SCORE(tableA other"), typeSystem, mock(Source.class));
}
@Test( expected = ParsingException.class )
public void shouldFailToParseDynamicOperandFromStringContainingFullTextSearchScoreWithoutOpeningParenthesis() {
- parser.parseDynamicOperand(tokens("Score tableA other"), context, mock(Source.class));
+ parser.parseDynamicOperand(tokens("Score tableA other"), typeSystem, mock(Source.class));
}
// ----------------------------------------------------------------------------------------------------------------
@@ -1596,49 +1618,49 @@
@Test
public void shouldParseDynamicOperandFromStringWithUnquotedSelectorNameAndUnquotedPropertyName() {
- DynamicOperand operand = parser.parseDynamicOperand(tokens("tableA.property"), context, mock(Join.class));
+ DynamicOperand operand = parser.parseDynamicOperand(tokens("tableA.property"), typeSystem, mock(Join.class));
assertThat(operand, is(instanceOf(PropertyValue.class)));
PropertyValue value = (PropertyValue)operand;
- assertThat(value.getPropertyName(), is(name("property")));
+ assertThat(value.getPropertyName(), is("property"));
assertThat(value.getSelectorName(), is(selectorName("tableA")));
}
@Test
public void shouldParseDynamicOperandFromStringWithQuotedSelectorNameAndUnquotedPropertyName() {
- DynamicOperand operand = parser.parseDynamicOperand(tokens("[dna:tableA].property"), context, mock(Join.class));
+ DynamicOperand operand = parser.parseDynamicOperand(tokens("[dna:tableA].property"), typeSystem, mock(Join.class));
assertThat(operand, is(instanceOf(PropertyValue.class)));
PropertyValue value = (PropertyValue)operand;
- assertThat(value.getPropertyName(), is(name("property")));
+ assertThat(value.getPropertyName(), is("property"));
assertThat(value.getSelectorName(), is(selectorName("dna:tableA")));
}
@Test
public void shouldParseDynamicOperandFromStringWithQuotedSelectorNameAndQuotedPropertyName() {
- DynamicOperand operand = parser.parseDynamicOperand(tokens("[dna:tableA].[dna:property]"), context, mock(Join.class));
+ DynamicOperand operand = parser.parseDynamicOperand(tokens("[dna:tableA].[dna:property]"), typeSystem, mock(Join.class));
assertThat(operand, is(instanceOf(PropertyValue.class)));
PropertyValue value = (PropertyValue)operand;
- assertThat(value.getPropertyName(), is(name("dna:property")));
+ assertThat(value.getPropertyName(), is("dna:property"));
assertThat(value.getSelectorName(), is(selectorName("dna:tableA")));
}
@Test
public void shouldParseDynamicOperandFromStringWithOnlyPropertyNameIfSourceIsSelector() {
Source source = new NamedSelector(selectorName("tableA"));
- DynamicOperand operand = parser.parseDynamicOperand(tokens("property"), context, source);
+ DynamicOperand operand = parser.parseDynamicOperand(tokens("property"), typeSystem, source);
assertThat(operand, is(instanceOf(PropertyValue.class)));
PropertyValue value = (PropertyValue)operand;
- assertThat(value.getPropertyName(), is(name("property")));
+ assertThat(value.getPropertyName(), is("property"));
assertThat(value.getSelectorName(), is(selectorName("tableA")));
}
@Test( expected = ParsingException.class )
public void shouldFailToDynamicOperandValueFromStringWithOnlyPropertyNameIfSourceIsNotSelector() {
- parser.parsePropertyValue(tokens("property"), context, mock(Join.class));
+ parser.parsePropertyValue(tokens("property"), typeSystem, mock(Join.class));
}
@Test( expected = ParsingException.class )
public void shouldFailToParseDynamicOperandFromStringWithOnlySelectorNameAndPeriod() {
- parser.parsePropertyValue(tokens("tableA. "), context, mock(Join.class));
+ parser.parsePropertyValue(tokens("tableA. "), typeSystem, mock(Join.class));
}
// ----------------------------------------------------------------------------------------------------------------
@@ -1647,41 +1669,41 @@
@Test
public void shouldParsePropertyValueFromStringWithUnquotedSelectorNameAndUnquotedPropertyName() {
- PropertyValue value = parser.parsePropertyValue(tokens("tableA.property"), context, mock(Join.class));
- assertThat(value.getPropertyName(), is(name("property")));
+ PropertyValue value = parser.parsePropertyValue(tokens("tableA.property"), typeSystem, mock(Join.class));
+ assertThat(value.getPropertyName(), is("property"));
assertThat(value.getSelectorName(), is(selectorName("tableA")));
}
@Test
public void shouldParsePropertyValueFromStringWithQuotedSelectorNameAndUnquotedPropertyName() {
- PropertyValue value = parser.parsePropertyValue(tokens("[dna:tableA].property"), context, mock(Join.class));
- assertThat(value.getPropertyName(), is(name("property")));
+ PropertyValue value = parser.parsePropertyValue(tokens("[dna:tableA].property"), typeSystem, mock(Join.class));
+ assertThat(value.getPropertyName(), is("property"));
assertThat(value.getSelectorName(), is(selectorName("dna:tableA")));
}
@Test
public void shouldParsePropertyValueFromStringWithQuotedSelectorNameAndQuotedPropertyName() {
- PropertyValue value = parser.parsePropertyValue(tokens("[dna:tableA].[dna:property]"), context, mock(Join.class));
- assertThat(value.getPropertyName(), is(name("dna:property")));
+ PropertyValue value = parser.parsePropertyValue(tokens("[dna:tableA].[dna:property]"), typeSystem, mock(Join.class));
+ assertThat(value.getPropertyName(), is("dna:property"));
assertThat(value.getSelectorName(), is(selectorName("dna:tableA")));
}
@Test
public void shouldParsePropertyValueFromStringWithOnlyPropertyNameIfSourceIsSelector() {
Source source = new NamedSelector(selectorName("tableA"));
- PropertyValue value = parser.parsePropertyValue(tokens("property"), context, source);
- assertThat(value.getPropertyName(), is(name("property")));
+ PropertyValue value = parser.parsePropertyValue(tokens("property"), typeSystem, source);
+ assertThat(value.getPropertyName(), is("property"));
assertThat(value.getSelectorName(), is(selectorName("tableA")));
}
@Test( expected = ParsingException.class )
public void shouldFailToParsePropertyValueFromStringWithOnlyPropertyNameIfSourceIsNotSelector() {
- parser.parsePropertyValue(tokens("property"), context, mock(Join.class));
+ parser.parsePropertyValue(tokens("property"), typeSystem, mock(Join.class));
}
@Test( expected = ParsingException.class )
public void shouldFailToParsePropertyValueFromStringWithOnlySelectorNameAndPeriod() {
- parser.parsePropertyValue(tokens("tableA. "), context, mock(Join.class));
+ parser.parsePropertyValue(tokens("tableA. "), typeSystem, mock(Join.class));
}
// ----------------------------------------------------------------------------------------------------------------
@@ -1809,48 +1831,48 @@
@Test
public void shouldParseNameFromSingleQuotedString() {
- assertThat(parser.parseName(tokens("'jcr:name'"), context), is(name("jcr:name")));
+ assertThat(parser.parseName(tokens("'jcr:name'"), typeSystem), is("jcr:name"));
}
@Test
public void shouldParseNameFromDoubleQuotedString() {
- assertThat(parser.parseName(tokens("\"jcr:name\""), context), is(name("jcr:name")));
+ assertThat(parser.parseName(tokens("\"jcr:name\""), typeSystem), is("jcr:name"));
}
@Test
public void shouldParseNameFromBracketedString() {
- assertThat(parser.parseName(tokens("[jcr:name]"), context), is(name("jcr:name")));
+ assertThat(parser.parseName(tokens("[jcr:name]"), typeSystem), is("jcr:name"));
}
@Test
public void shouldParseNameFromUnquotedStringWithoutPrefix() {
- assertThat(parser.parseName(tokens("name"), context), is(name("name")));
+ assertThat(parser.parseName(tokens("name"), typeSystem), is("name"));
}
@Test
public void shouldParseNameFromSingleQuotedStringWithoutPrefix() {
- assertThat(parser.parseName(tokens("'name'"), context), is(name("name")));
+ assertThat(parser.parseName(tokens("'name'"), typeSystem), is("name"));
}
@Test
public void shouldParseNameFromDoubleQuotedStringWithoutPrefix() {
- assertThat(parser.parseName(tokens("\"name\""), context), is(name("name")));
+ assertThat(parser.parseName(tokens("\"name\""), typeSystem), is("name"));
}
@Test
public void shouldParseNameFromBracketedStringWithoutPrefix() {
- assertThat(parser.parseName(tokens("[name]"), context), is(name("name")));
+ assertThat(parser.parseName(tokens("[name]"), typeSystem), is("name"));
}
@Test
public void shouldParseNameFromBracketedAndQuotedStringWithoutPrefix() {
- assertThat(parser.parseName(tokens("['name']"), context), is(name("name")));
- assertThat(parser.parseName(tokens("[\"name\"]"), context), is(name("name")));
+ assertThat(parser.parseName(tokens("['name']"), typeSystem), is("name"));
+ assertThat(parser.parseName(tokens("[\"name\"]"), typeSystem), is("name"));
}
@Test( expected = ParsingException.class )
public void shouldFailToParseNameIfNoMoreTokens() {
- parser.parseName(tokens(" "), context);
+ parser.parseName(tokens(" "), typeSystem);
}
// ----------------------------------------------------------------------------------------------------------------
@@ -1860,22 +1882,22 @@
@Test
public void shouldParsePathFromUnquotedStringConsistingOfSql92Identifiers() {
String identifier = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_";
- assertThat(parser.parsePath(tokens(identifier), context), is(path(identifier)));
+ assertThat(parser.parsePath(tokens(identifier), typeSystem), is(identifier));
}
@Test
public void shouldParsePathFromSingleQuotedString() {
- assertThat(parser.parsePath(tokens("'/a/b/c/dna:something/d'"), context), is(path("/a/b/c/dna:something/d")));
+ assertThat(parser.parsePath(tokens("'/a/b/c/dna:something/d'"), typeSystem), is("/a/b/c/dna:something/d"));
}
@Test
public void shouldParsePathFromDoubleQuotedString() {
- assertThat(parser.parsePath(tokens("\"/a/b/c/dna:something/d\""), context), is(path("/a/b/c/dna:something/d")));
+ assertThat(parser.parsePath(tokens("\"/a/b/c/dna:something/d\""), typeSystem), is("/a/b/c/dna:something/d"));
}
@Test( expected = ParsingException.class )
public void shouldFailInParsePathIfNoMoreTokens() {
- parser.parsePath(tokens(" "), context);
+ parser.parsePath(tokens(" "), typeSystem);
}
// ----------------------------------------------------------------------------------------------------------------
@@ -1899,7 +1921,7 @@
// ----------------------------------------------------------------------------------------------------------------
protected void parse( String query ) {
- parser.parseQuery(query, context);
+ parser.parseQuery(query, typeSystem);
}
protected SelectorName selectorName( String name ) {
@@ -1907,11 +1929,11 @@
}
protected Name name( String name ) {
- return context.getValueFactories().getNameFactory().create(name);
+ return (Name)typeSystem.getTypeFactory(PropertyType.NAME.getName()).create(name);
}
protected Path path( String path ) {
- return context.getValueFactories().getPathFactory().create(path);
+ return (Path)typeSystem.getTypeFactory(PropertyType.PATH.getName()).create(path);
}
protected TokenStream tokens( String content ) {
Modified: trunk/dna-graph/src/test/java/org/jboss/dna/graph/query/plan/CanonicalPlannerTest.java
===================================================================
--- trunk/dna-graph/src/test/java/org/jboss/dna/graph/query/plan/CanonicalPlannerTest.java 2009-11-24 17:44:29 UTC (rev 1339)
+++ trunk/dna-graph/src/test/java/org/jboss/dna/graph/query/plan/CanonicalPlannerTest.java 2009-11-24 17:46:37 UTC (rev 1340)
@@ -35,6 +35,7 @@
import org.jboss.dna.graph.query.model.Column;
import org.jboss.dna.graph.query.model.QueryCommand;
import org.jboss.dna.graph.query.model.SelectorName;
+import org.jboss.dna.graph.query.model.TypeSystem;
import org.jboss.dna.graph.query.plan.PlanNode.Property;
import org.jboss.dna.graph.query.plan.PlanNode.Type;
import org.jboss.dna.graph.query.validate.ImmutableSchemata;
@@ -48,7 +49,7 @@
public class CanonicalPlannerTest {
private CanonicalPlanner planner;
- private ExecutionContext context;
+ private TypeSystem typeSystem;
private QueryBuilder builder;
private PlanHints hints;
private QueryCommand query;
@@ -61,11 +62,11 @@
@Before
public void beforeEach() {
planner = new CanonicalPlanner();
- context = new ExecutionContext();
+ typeSystem = new ExecutionContext().getValueFactories().getTypeSystem();
hints = new PlanHints();
- builder = new QueryBuilder(context);
+ builder = new QueryBuilder(typeSystem);
problems = new SimpleProblems();
- schemataBuilder = ImmutableSchemata.createBuilder(context);
+ schemataBuilder = ImmutableSchemata.createBuilder(typeSystem);
}
protected SelectorName selector( String name ) {
@@ -112,7 +113,7 @@
public void shouldProducePlanForSelectStarFromTable() {
schemata = schemataBuilder.addTable("__ALLNODES__", "column1", "column2", "column3").build();
query = builder.selectStar().fromAllNodes().query();
- queryContext = new QueryContext(context, schemata, hints, problems);
+ queryContext = new QueryContext(schemata, typeSystem, hints, problems);
plan = planner.createPlan(queryContext, query);
assertThat(problems.isEmpty(), is(true));
assertProjectNode(plan, "column1", "column2", "column3");
@@ -128,7 +129,7 @@
public void shouldProduceErrorWhenSelectingNonExistantTable() {
schemata = schemataBuilder.addTable("someTable", "column1", "column2", "column3").build();
query = builder.selectStar().fromAllNodes().query();
- queryContext = new QueryContext(context, schemata, hints, problems);
+ queryContext = new QueryContext(schemata, typeSystem, hints, problems);
plan = planner.createPlan(queryContext, query);
assertThat(problems.hasErrors(), is(true));
}
@@ -137,7 +138,7 @@
public void shouldProduceErrorWhenSelectingNonExistantColumnOnExistingTable() {
schemata = schemataBuilder.addTable("someTable", "column1", "column2", "column3").build();
query = builder.select("column1", "column4").from("someTable").query();
- queryContext = new QueryContext(context, schemata, hints, problems);
+ queryContext = new QueryContext(schemata, typeSystem, hints, problems);
plan = planner.createPlan(queryContext, query);
assertThat(problems.hasErrors(), is(true));
}
@@ -146,7 +147,7 @@
public void shouldProducePlanWhenSelectingAllColumnsOnExistingTable() {
schemata = schemataBuilder.addTable("someTable", "column1", "column2", "column3").build();
query = builder.selectStar().from("someTable").query();
- queryContext = new QueryContext(context, schemata, hints, problems);
+ queryContext = new QueryContext(schemata, typeSystem, hints, problems);
plan = planner.createPlan(queryContext, query);
System.out.println(plan);
assertThat(problems.hasErrors(), is(false));
@@ -164,12 +165,12 @@
schemata = schemataBuilder.addTable("someTable", "column1", "column2", "column3").build();
// Make sure the query without the search criteria does not have an error
query = builder.select("column1", "column2").from("someTable").query();
- queryContext = new QueryContext(context, schemata, hints, problems);
+ queryContext = new QueryContext(schemata, typeSystem, hints, problems);
plan = planner.createPlan(queryContext, query);
assertThat(problems.hasErrors(), is(false));
query = builder.select("column1", "column2").from("someTable").where().search("someTable", "term1").end().query();
- queryContext = new QueryContext(context, schemata, hints, problems);
+ queryContext = new QueryContext(schemata, typeSystem, hints, problems);
plan = planner.createPlan(queryContext, query);
assertThat(problems.hasErrors(), is(true));
}
@@ -180,7 +181,7 @@
.makeSearchable("someTable", "column1")
.build();
query = builder.select("column1", "column4").from("someTable").where().search("someTable", "term1").end().query();
- queryContext = new QueryContext(context, schemata, hints, problems);
+ queryContext = new QueryContext(schemata, typeSystem, hints, problems);
plan = planner.createPlan(queryContext, query);
assertThat(problems.hasErrors(), is(true));
}
@@ -190,7 +191,7 @@
schemata = schemataBuilder.addTable("someTable", "column1", "column2", "column3").build();
// Make sure the query without the search criteria does not have an error
query = builder.select("column1", "column2").from("someTable").query();
- queryContext = new QueryContext(context, schemata, hints, problems);
+ queryContext = new QueryContext(schemata, typeSystem, hints, problems);
plan = planner.createPlan(queryContext, query);
assertThat(problems.hasErrors(), is(false));
@@ -200,7 +201,7 @@
.search("someTable", "column2", "term1")
.end()
.query();
- queryContext = new QueryContext(context, schemata, hints, problems);
+ queryContext = new QueryContext(schemata, typeSystem, hints, problems);
plan = planner.createPlan(queryContext, query);
assertThat(problems.hasErrors(), is(true));
}
@@ -216,7 +217,7 @@
.search("someTable", "column1", "term1")
.end()
.query();
- queryContext = new QueryContext(context, schemata, hints, problems);
+ queryContext = new QueryContext(schemata, typeSystem, hints, problems);
plan = planner.createPlan(queryContext, query);
assertThat(problems.hasErrors(), is(true));
}
Modified: trunk/dna-graph/src/test/java/org/jboss/dna/graph/query/process/AbstractQueryResultsTest.java
===================================================================
--- trunk/dna-graph/src/test/java/org/jboss/dna/graph/query/process/AbstractQueryResultsTest.java 2009-11-24 17:44:29 UTC (rev 1339)
+++ trunk/dna-graph/src/test/java/org/jboss/dna/graph/query/process/AbstractQueryResultsTest.java 2009-11-24 17:46:37 UTC (rev 1340)
@@ -29,7 +29,6 @@
import java.util.List;
import org.jboss.dna.graph.ExecutionContext;
import org.jboss.dna.graph.Location;
-import org.jboss.dna.graph.property.Name;
import org.jboss.dna.graph.property.Path;
import org.jboss.dna.graph.property.PropertyType;
import org.jboss.dna.graph.query.AbstractQueryTest;
@@ -45,6 +44,7 @@
import org.jboss.dna.graph.query.model.Ordering;
import org.jboss.dna.graph.query.model.PropertyValue;
import org.jboss.dna.graph.query.model.SelectorName;
+import org.jboss.dna.graph.query.model.TypeSystem;
import org.jboss.dna.graph.query.validate.ImmutableSchemata;
import org.jboss.dna.graph.query.validate.Schemata;
@@ -54,11 +54,8 @@
public abstract class AbstractQueryResultsTest extends AbstractQueryTest {
protected ExecutionContext executionContext = ExecutionContext.DEFAULT_CONTEXT;
+ protected TypeSystem typeSystem = executionContext.getValueFactories().getTypeSystem();
- protected Name name( String name ) {
- return executionContext.getValueFactories().getNameFactory().create(name);
- }
-
protected Path path( String name ) {
return executionContext.getValueFactories().getPathFactory().create(name);
}
@@ -69,7 +66,7 @@
protected Schemata schemataFor( Columns columns,
PropertyType... types ) {
- ImmutableSchemata.Builder builder = ImmutableSchemata.createBuilder(executionContext);
+ ImmutableSchemata.Builder builder = ImmutableSchemata.createBuilder(typeSystem);
for (String selectorName : columns.getSelectorNames()) {
final SelectorName selector = selector(selectorName);
int i = 0;
@@ -77,7 +74,7 @@
final String name = column.getColumnName();
final PropertyType type = types != null && types.length > i && types[i] != null ? types[i] : PropertyType.STRING;
if (column.getSelectorName().equals(selector)) {
- builder.addColumn(selectorName, name, type);
+ builder.addColumn(selectorName, name, type.getName().toUpperCase());
++i;
}
}
@@ -91,7 +88,7 @@
List<Column> columnObj = new ArrayList<Column>();
SelectorName selector = selector(selectorName);
for (String columnName : columnNames) {
- columnObj.add(new Column(selector, name(columnName), columnName));
+ columnObj.add(new Column(selector, columnName, columnName));
}
return new QueryResultColumns(columnObj, false);
}
@@ -102,7 +99,7 @@
List<Column> columnObj = new ArrayList<Column>();
SelectorName selector = selector(selectorName);
for (String columnName : columnNames) {
- columnObj.add(new Column(selector, name(columnName), columnName));
+ columnObj.add(new Column(selector, columnName, columnName));
}
return new QueryResultColumns(columnObj, true);
}
Modified: trunk/dna-graph/src/test/java/org/jboss/dna/graph/query/process/DistinctComponentTest.java
===================================================================
--- trunk/dna-graph/src/test/java/org/jboss/dna/graph/query/process/DistinctComponentTest.java 2009-11-24 17:44:29 UTC (rev 1339)
+++ trunk/dna-graph/src/test/java/org/jboss/dna/graph/query/process/DistinctComponentTest.java 2009-11-24 17:46:37 UTC (rev 1340)
@@ -28,7 +28,6 @@
import static org.mockito.Mockito.mock;
import java.util.ArrayList;
import java.util.List;
-import org.jboss.dna.graph.ExecutionContext;
import org.jboss.dna.graph.query.QueryContext;
import org.jboss.dna.graph.query.QueryResults.Columns;
import org.jboss.dna.graph.query.validate.Schemata;
@@ -47,7 +46,7 @@
@Before
public void beforeEach() {
- context = new QueryContext(new ExecutionContext(), mock(Schemata.class));
+ context = new QueryContext(mock(Schemata.class), typeSystem);
inputTuples = new ArrayList<Object[]>();
// Define the columns for the results ...
columns = resultColumns("Selector1", "ColA", "ColB", "ColC");
Modified: trunk/dna-graph/src/test/java/org/jboss/dna/graph/query/process/QueryResultColumnsTest.java
===================================================================
--- trunk/dna-graph/src/test/java/org/jboss/dna/graph/query/process/QueryResultColumnsTest.java 2009-11-24 17:44:29 UTC (rev 1339)
+++ trunk/dna-graph/src/test/java/org/jboss/dna/graph/query/process/QueryResultColumnsTest.java 2009-11-24 17:46:37 UTC (rev 1340)
@@ -63,14 +63,14 @@
@Before
public void beforeEach() {
MockitoAnnotations.initMocks(this);
- context = new QueryContext(executionContext, schemata);
+ context = new QueryContext(schemata, typeSystem);
columnList = new ArrayList<Column>();
- columnList.add(new Column(selector("table1"), name("colA"), "colA"));
- columnList.add(new Column(selector("table1"), name("colB"), "colB"));
- columnList.add(new Column(selector("table1"), name("colC"), "colC"));
- columnList.add(new Column(selector("table2"), name("colA"), "colA2"));
- columnList.add(new Column(selector("table2"), name("colB"), "colB2"));
- columnList.add(new Column(selector("table2"), name("colX"), "colX"));
+ columnList.add(new Column(selector("table1"), "colA", "colA"));
+ columnList.add(new Column(selector("table1"), "colB", "colB"));
+ columnList.add(new Column(selector("table1"), "colC", "colC"));
+ columnList.add(new Column(selector("table2"), "colA", "colA2"));
+ columnList.add(new Column(selector("table2"), "colB", "colB2"));
+ columnList.add(new Column(selector("table2"), "colX", "colX"));
columns = new QueryResultColumns(columnList, false);
tuples = new ArrayList<Object[]>();
tuples.add(tuple(columns, new String[] {"/a/b/c", "/a/x/y"}, 1, 2, 3, "2a", "2b", "x"));
Modified: trunk/dna-graph/src/test/java/org/jboss/dna/graph/query/process/QueryResultsTest.java
===================================================================
--- trunk/dna-graph/src/test/java/org/jboss/dna/graph/query/process/QueryResultsTest.java 2009-11-24 17:44:29 UTC (rev 1339)
+++ trunk/dna-graph/src/test/java/org/jboss/dna/graph/query/process/QueryResultsTest.java 2009-11-24 17:46:37 UTC (rev 1340)
@@ -30,7 +30,6 @@
import java.util.NoSuchElementException;
import org.jboss.dna.graph.query.QueryResults.Columns;
import org.jboss.dna.graph.query.model.Column;
-import org.jboss.dna.graph.query.process.QueryResultColumns;
import org.junit.Before;
import org.junit.Test;
@@ -46,12 +45,12 @@
@Before
public void beforeEach() {
columnList = new ArrayList<Column>();
- columnList.add(new Column(selector("table1"), name("colA"), "colA"));
- columnList.add(new Column(selector("table1"), name("colB"), "colB"));
- columnList.add(new Column(selector("table1"), name("colC"), "colC"));
- columnList.add(new Column(selector("table2"), name("colA"), "colA2"));
- columnList.add(new Column(selector("table2"), name("colB"), "colB2"));
- columnList.add(new Column(selector("table2"), name("colX"), "colX"));
+ columnList.add(new Column(selector("table1"), "colA", "colA"));
+ columnList.add(new Column(selector("table1"), "colB", "colB"));
+ columnList.add(new Column(selector("table1"), "colC", "colC"));
+ columnList.add(new Column(selector("table2"), "colA", "colA2"));
+ columnList.add(new Column(selector("table2"), "colB", "colB2"));
+ columnList.add(new Column(selector("table2"), "colX", "colX"));
columnsWithoutScores = new QueryResultColumns(columnList, false);
columnsWithScores = new QueryResultColumns(columnList, true);
}
@@ -148,22 +147,22 @@
@Test( expected = NoSuchElementException.class )
public void shouldFailToFindIndexOfColumnGivenUnusedSelectorName() {
- columnsWithScores.getColumnIndexForProperty("non-existant", name("colA"));
+ columnsWithScores.getColumnIndexForProperty("non-existant", "colA");
}
@Test( expected = NoSuchElementException.class )
public void shouldFailToFindIndexOfColumnGivenNullSelectorName() {
- columnsWithScores.getColumnIndexForProperty(null, name("colA"));
+ columnsWithScores.getColumnIndexForProperty(null, "colA");
}
@Test( expected = NoSuchElementException.class )
public void shouldFailToFindIndexOfColumnGivenEmptySelectorName() {
- columnsWithScores.getColumnIndexForProperty("", name("colA"));
+ columnsWithScores.getColumnIndexForProperty("", "colA");
}
@Test( expected = NoSuchElementException.class )
public void shouldFailToFindIndexOfColumnGivenUnusedPropertyNameName() {
- columnsWithScores.getColumnIndexForProperty("table1", name("non-existant"));
+ columnsWithScores.getColumnIndexForProperty("table1", "non-existant");
}
@Test( expected = NoSuchElementException.class )
@@ -344,7 +343,7 @@
for (Column column : columnsWithScores.getColumns()) {
columnListCopy.add(new Column(column.getSelectorName(), column.getPropertyName(), column.getColumnName()));
}
- columnListCopy.add(new Column(selector("table2"), name("colZ"), "colZ"));
+ columnListCopy.add(new Column(selector("table2"), "colZ", "colZ"));
Columns other = new QueryResultColumns(columnListCopy, columnsWithScores.hasFullTextSearchScores());
assertThat(columnsWithScores.isUnionCompatible(other), is(false));
}
Modified: trunk/dna-graph/src/test/java/org/jboss/dna/graph/query/process/SortLocationsComponentTest.java
===================================================================
--- trunk/dna-graph/src/test/java/org/jboss/dna/graph/query/process/SortLocationsComponentTest.java 2009-11-24 17:44:29 UTC (rev 1339)
+++ trunk/dna-graph/src/test/java/org/jboss/dna/graph/query/process/SortLocationsComponentTest.java 2009-11-24 17:46:37 UTC (rev 1340)
@@ -28,7 +28,6 @@
import static org.mockito.Mockito.mock;
import java.util.ArrayList;
import java.util.List;
-import org.jboss.dna.graph.ExecutionContext;
import org.jboss.dna.graph.query.QueryContext;
import org.jboss.dna.graph.query.QueryResults.Columns;
import org.jboss.dna.graph.query.validate.Schemata;
@@ -47,7 +46,7 @@
@Before
public void beforeEach() {
- context = new QueryContext(new ExecutionContext(), mock(Schemata.class));
+ context = new QueryContext(mock(Schemata.class), typeSystem);
inputTuples = new ArrayList<Object[]>();
// Define the columns for the results ...
columns = resultColumns("Selector1", "ColA", "ColB", "ColC");
Modified: trunk/dna-graph/src/test/java/org/jboss/dna/graph/query/process/SortValuesComponentTest.java
===================================================================
--- trunk/dna-graph/src/test/java/org/jboss/dna/graph/query/process/SortValuesComponentTest.java 2009-11-24 17:44:29 UTC (rev 1339)
+++ trunk/dna-graph/src/test/java/org/jboss/dna/graph/query/process/SortValuesComponentTest.java 2009-11-24 17:46:37 UTC (rev 1340)
@@ -27,7 +27,6 @@
import static org.junit.Assert.assertThat;
import java.util.ArrayList;
import java.util.List;
-import org.jboss.dna.graph.ExecutionContext;
import org.jboss.dna.graph.property.PropertyType;
import org.jboss.dna.graph.query.QueryContext;
import org.jboss.dna.graph.query.QueryResults.Columns;
@@ -55,7 +54,7 @@
columns = resultColumns("Selector1", "ColA", "ColB", "ColC");
schemata = schemataFor(columns, PropertyType.STRING, PropertyType.LONG, PropertyType.STRING);
// Define the context ...
- context = new QueryContext(new ExecutionContext(), schemata);
+ context = new QueryContext(schemata, typeSystem);
inputTuples = new ArrayList<Object[]>();
// And define the delegating component ...
delegate = new ProcessingComponent(context, columns) {
Modified: trunk/dna-graph/src/test/java/org/jboss/dna/graph/query/validate/ImmutableSchemataBuilderTest.java
===================================================================
--- trunk/dna-graph/src/test/java/org/jboss/dna/graph/query/validate/ImmutableSchemataBuilderTest.java 2009-11-24 17:44:29 UTC (rev 1339)
+++ trunk/dna-graph/src/test/java/org/jboss/dna/graph/query/validate/ImmutableSchemataBuilderTest.java 2009-11-24 17:46:37 UTC (rev 1340)
@@ -41,6 +41,8 @@
*/
public class ImmutableSchemataBuilderTest {
+ private static final String STRING_TYPE = PropertyType.STRING.getName().toUpperCase();
+
private ExecutionContext context;
private ImmutableSchemata.Builder builder;
private Schemata schemata;
@@ -48,7 +50,7 @@
@Before
public void beforeEach() {
context = new ExecutionContext();
- builder = ImmutableSchemata.createBuilder(context);
+ builder = ImmutableSchemata.createBuilder(context.getValueFactories().getTypeSystem());
}
@After
@@ -64,9 +66,9 @@
schemata = builder.build();
Table table = schemata.getTable(selector("t1"));
assertThat(table, is(notNullValue()));
- assertThat(table.getColumn("c1").getPropertyType(), is(PropertyType.STRING));
- assertThat(table.getColumn("c2").getPropertyType(), is(PropertyType.STRING));
- assertThat(table.getColumn("c3").getPropertyType(), is(PropertyType.STRING));
+ assertThat(table.getColumn("c1").getPropertyType(), is(STRING_TYPE));
+ assertThat(table.getColumn("c2").getPropertyType(), is(STRING_TYPE));
+ assertThat(table.getColumn("c3").getPropertyType(), is(STRING_TYPE));
}
@Test
@@ -76,14 +78,14 @@
schemata = builder.build();
Table table = schemata.getTable(selector("t1"));
assertThat(table, is(notNullValue()));
- assertThat(table.getColumn("c11").getPropertyType(), is(PropertyType.STRING));
- assertThat(table.getColumn("c12").getPropertyType(), is(PropertyType.STRING));
- assertThat(table.getColumn("c13").getPropertyType(), is(PropertyType.STRING));
+ assertThat(table.getColumn("c11").getPropertyType(), is(STRING_TYPE));
+ assertThat(table.getColumn("c12").getPropertyType(), is(STRING_TYPE));
+ assertThat(table.getColumn("c13").getPropertyType(), is(STRING_TYPE));
table = schemata.getTable(selector("t2"));
assertThat(table, is(notNullValue()));
- assertThat(table.getColumn("c21").getPropertyType(), is(PropertyType.STRING));
- assertThat(table.getColumn("c22").getPropertyType(), is(PropertyType.STRING));
- assertThat(table.getColumn("c23").getPropertyType(), is(PropertyType.STRING));
+ assertThat(table.getColumn("c21").getPropertyType(), is(STRING_TYPE));
+ assertThat(table.getColumn("c22").getPropertyType(), is(STRING_TYPE));
+ assertThat(table.getColumn("c23").getPropertyType(), is(STRING_TYPE));
}
@Test
@@ -93,14 +95,14 @@
schemata = builder.build();
Table table = schemata.getTable(selector("t1"));
assertThat(table, is(notNullValue()));
- assertThat(table.getColumn("c1").getPropertyType(), is(PropertyType.STRING));
- assertThat(table.getColumn("c2").getPropertyType(), is(PropertyType.STRING));
- assertThat(table.getColumn("c3").getPropertyType(), is(PropertyType.STRING));
+ assertThat(table.getColumn("c1").getPropertyType(), is(STRING_TYPE));
+ assertThat(table.getColumn("c2").getPropertyType(), is(STRING_TYPE));
+ assertThat(table.getColumn("c3").getPropertyType(), is(STRING_TYPE));
table = schemata.getTable(selector("t2"));
assertThat(table, is(instanceOf(View.class)));
- assertThat(table.getColumn("c1").getPropertyType(), is(PropertyType.STRING));
- assertThat(table.getColumn("c2").getPropertyType(), is(PropertyType.STRING));
- assertThat(table.getColumn("c3").getPropertyType(), is(PropertyType.STRING));
+ assertThat(table.getColumn("c1").getPropertyType(), is(STRING_TYPE));
+ assertThat(table.getColumn("c2").getPropertyType(), is(STRING_TYPE));
+ assertThat(table.getColumn("c3").getPropertyType(), is(STRING_TYPE));
}
@Test
@@ -110,13 +112,13 @@
schemata = builder.build();
Table table = schemata.getTable(selector("t1"));
assertThat(table, is(notNullValue()));
- assertThat(table.getColumn("c1").getPropertyType(), is(PropertyType.STRING));
- assertThat(table.getColumn("c2").getPropertyType(), is(PropertyType.STRING));
- assertThat(table.getColumn("c3").getPropertyType(), is(PropertyType.STRING));
+ assertThat(table.getColumn("c1").getPropertyType(), is(STRING_TYPE));
+ assertThat(table.getColumn("c2").getPropertyType(), is(STRING_TYPE));
+ assertThat(table.getColumn("c3").getPropertyType(), is(STRING_TYPE));
table = schemata.getTable(selector("t2"));
assertThat(table, is(instanceOf(View.class)));
- assertThat(table.getColumn("v1").getPropertyType(), is(PropertyType.STRING));
- assertThat(table.getColumn("c2").getPropertyType(), is(PropertyType.STRING));
+ assertThat(table.getColumn("v1").getPropertyType(), is(STRING_TYPE));
+ assertThat(table.getColumn("c2").getPropertyType(), is(STRING_TYPE));
}
@Test
@@ -127,20 +129,20 @@
schemata = builder.build();
Table table = schemata.getTable(selector("t1"));
assertThat(table, is(notNullValue()));
- assertThat(table.getColumn("c11").getPropertyType(), is(PropertyType.STRING));
- assertThat(table.getColumn("c12").getPropertyType(), is(PropertyType.STRING));
- assertThat(table.getColumn("c13").getPropertyType(), is(PropertyType.STRING));
+ assertThat(table.getColumn("c11").getPropertyType(), is(STRING_TYPE));
+ assertThat(table.getColumn("c12").getPropertyType(), is(STRING_TYPE));
+ assertThat(table.getColumn("c13").getPropertyType(), is(STRING_TYPE));
table = schemata.getTable(selector("t2"));
assertThat(table, is(notNullValue()));
- assertThat(table.getColumn("c21").getPropertyType(), is(PropertyType.STRING));
- assertThat(table.getColumn("c22").getPropertyType(), is(PropertyType.STRING));
- assertThat(table.getColumn("c23").getPropertyType(), is(PropertyType.STRING));
+ assertThat(table.getColumn("c21").getPropertyType(), is(STRING_TYPE));
+ assertThat(table.getColumn("c22").getPropertyType(), is(STRING_TYPE));
+ assertThat(table.getColumn("c23").getPropertyType(), is(STRING_TYPE));
schemata = builder.build();
table = schemata.getTable(selector("v1"));
assertThat(table, is(instanceOf(View.class)));
- assertThat(table.getColumn("x1").getPropertyType(), is(PropertyType.STRING));
- assertThat(table.getColumn("c12").getPropertyType(), is(PropertyType.STRING));
- assertThat(table.getColumn("c23").getPropertyType(), is(PropertyType.STRING));
+ assertThat(table.getColumn("x1").getPropertyType(), is(STRING_TYPE));
+ assertThat(table.getColumn("c12").getPropertyType(), is(STRING_TYPE));
+ assertThat(table.getColumn("c23").getPropertyType(), is(STRING_TYPE));
}
@Test
@@ -152,24 +154,24 @@
schemata = builder.build();
Table table = schemata.getTable(selector("t1"));
assertThat(table, is(notNullValue()));
- assertThat(table.getColumn("c11").getPropertyType(), is(PropertyType.STRING));
- assertThat(table.getColumn("c12").getPropertyType(), is(PropertyType.STRING));
- assertThat(table.getColumn("c13").getPropertyType(), is(PropertyType.STRING));
+ assertThat(table.getColumn("c11").getPropertyType(), is(STRING_TYPE));
+ assertThat(table.getColumn("c12").getPropertyType(), is(STRING_TYPE));
+ assertThat(table.getColumn("c13").getPropertyType(), is(STRING_TYPE));
table = schemata.getTable(selector("t2"));
assertThat(table, is(notNullValue()));
- assertThat(table.getColumn("c21").getPropertyType(), is(PropertyType.STRING));
- assertThat(table.getColumn("c22").getPropertyType(), is(PropertyType.STRING));
- assertThat(table.getColumn("c23").getPropertyType(), is(PropertyType.STRING));
+ assertThat(table.getColumn("c21").getPropertyType(), is(STRING_TYPE));
+ assertThat(table.getColumn("c22").getPropertyType(), is(STRING_TYPE));
+ assertThat(table.getColumn("c23").getPropertyType(), is(STRING_TYPE));
schemata = builder.build();
table = schemata.getTable(selector("v1"));
assertThat(table, is(instanceOf(View.class)));
- assertThat(table.getColumn("x1").getPropertyType(), is(PropertyType.STRING));
- assertThat(table.getColumn("c12").getPropertyType(), is(PropertyType.STRING));
- assertThat(table.getColumn("c23").getPropertyType(), is(PropertyType.STRING));
+ assertThat(table.getColumn("x1").getPropertyType(), is(STRING_TYPE));
+ assertThat(table.getColumn("c12").getPropertyType(), is(STRING_TYPE));
+ assertThat(table.getColumn("c23").getPropertyType(), is(STRING_TYPE));
table = schemata.getTable(selector("v2"));
assertThat(table, is(instanceOf(View.class)));
- assertThat(table.getColumn("x1").getPropertyType(), is(PropertyType.STRING));
- assertThat(table.getColumn("c12").getPropertyType(), is(PropertyType.STRING));
+ assertThat(table.getColumn("x1").getPropertyType(), is(STRING_TYPE));
+ assertThat(table.getColumn("c12").getPropertyType(), is(STRING_TYPE));
}
protected SelectorName selector( String name ) {
Modified: trunk/dna-graph/src/test/java/org/jboss/dna/graph/search/SearchEngineTest.java
===================================================================
--- trunk/dna-graph/src/test/java/org/jboss/dna/graph/search/SearchEngineTest.java 2009-11-24 17:44:29 UTC (rev 1339)
+++ trunk/dna-graph/src/test/java/org/jboss/dna/graph/search/SearchEngineTest.java 2009-11-24 17:46:37 UTC (rev 1340)
@@ -248,7 +248,7 @@
Query query = mock(Query.class);
Schemata schemata = mock(Schemata.class);
engine.query(context, workspaceName1, query, schemata);
- verify(sessionWs1).query(eq(new QueryContext(context, schemata)), eq(query));
+ verify(sessionWs1).query(eq(new QueryContext(schemata, context.getValueFactories().getTypeSystem())), eq(query));
verify(sessionWs1).commit();
}
}
Modified: trunk/dna-jcr/src/main/java/org/jboss/dna/jcr/AbstractJcrNode.java
===================================================================
--- trunk/dna-jcr/src/main/java/org/jboss/dna/jcr/AbstractJcrNode.java 2009-11-24 17:44:29 UTC (rev 1339)
+++ trunk/dna-jcr/src/main/java/org/jboss/dna/jcr/AbstractJcrNode.java 2009-11-24 17:46:37 UTC (rev 1340)
@@ -1007,11 +1007,10 @@
throws ItemExistsException, PathNotFoundException, VersionException, ConstraintViolationException, LockException,
RepositoryException {
-
if (isLocked() && !holdsLock()) {
throw new LockException(JcrI18n.lockTokenNotHeld.text(this.location));
}
-
+
// Determine the path ...
NodeEditor editor = null;
Path path = null;
@@ -1336,7 +1335,7 @@
* @return <code>false</code>
* @see javax.jcr.Node#holdsLock()
*/
- public final boolean holdsLock() throws RepositoryException {
+ public final boolean holdsLock() /*throws RepositoryException*/{
WorkspaceLockManager.DnaLock lock = session().workspace().lockManager().lockFor(this.location);
return lock != null && cache.session().lockTokens().contains(lock.getLockToken());
@@ -1351,7 +1350,7 @@
public final boolean isLocked() throws LockException, RepositoryException {
return lock() != null;
}
-
+
/**
* {@inheritDoc}
*
@@ -1440,7 +1439,7 @@
if (lock == null) throw new LockException(JcrI18n.notLocked.text(this.location));
return lock.lockFor(cache);
}
-
+
/**
* {@inheritDoc}
*
Modified: trunk/dna-jcr/src/main/java/org/jboss/dna/jcr/xpath/XPathParser.java
===================================================================
--- trunk/dna-jcr/src/main/java/org/jboss/dna/jcr/xpath/XPathParser.java 2009-11-24 17:44:29 UTC (rev 1339)
+++ trunk/dna-jcr/src/main/java/org/jboss/dna/jcr/xpath/XPathParser.java 2009-11-24 17:46:37 UTC (rev 1340)
@@ -34,11 +34,10 @@
import org.jboss.dna.common.text.TokenStream.Tokenizer;
import org.jboss.dna.common.text.TokenStream.Tokens;
import org.jboss.dna.common.xml.XmlCharacters;
-import org.jboss.dna.graph.ExecutionContext;
import org.jboss.dna.graph.GraphI18n;
-import org.jboss.dna.graph.property.ValueFactory;
import org.jboss.dna.graph.property.ValueFormatException;
import org.jboss.dna.graph.query.model.Operator;
+import org.jboss.dna.graph.query.model.TypeSystem;
import org.jboss.dna.jcr.xpath.XPath.Add;
import org.jboss.dna.jcr.xpath.XPath.And;
import org.jboss.dna.jcr.xpath.XPath.AnyKindTest;
@@ -79,10 +78,10 @@
* defined by JCR 1.0, and is a subset of what is allowed by the W3C XPath 2.0 specification.
*/
public class XPathParser {
- private final ExecutionContext context;
+ private final TypeSystem typeSystem;
- public XPathParser( ExecutionContext context ) {
- this.context = context;
+ public XPathParser( TypeSystem context ) {
+ this.typeSystem = context;
}
public Component parseXPath( String xpath ) {
@@ -417,7 +416,6 @@
else if (tokens.canConsume('+')) sign = "";
// Try to parse this value as a number ...
- ValueFactory<String> stringFactory = context.getValueFactories().getStringFactory();
String number = tokens.consume();
if (number.indexOf(".") != -1) {
String value = sign + number;
@@ -427,7 +425,7 @@
}
try {
// Convert to a double and then back to a string to get canonical form ...
- String canonical = stringFactory.create(context.getValueFactories().getDoubleFactory().create(value));
+ String canonical = typeSystem.getDoubleFactory().asString(value);
return new Literal(canonical);
} catch (ValueFormatException e) {
String msg = GraphI18n.expectingLiteralAndUnableToParseAsDouble.text(value, pos.getLine(), pos.getColumn());
@@ -438,7 +436,7 @@
String value = sign + number;
try {
// Convert to a long and then back to a string to get canonical form ...
- String canonical = stringFactory.create(context.getValueFactories().getLongFactory().create(value));
+ String canonical = typeSystem.getLongFactory().asString(value);
return new Literal(canonical);
} catch (ValueFormatException e) {
String msg = GraphI18n.expectingLiteralAndUnableToParseAsLong.text(value, pos.getLine(), pos.getColumn());
Modified: trunk/dna-jcr/src/main/java/org/jboss/dna/jcr/xpath/XPathQueryParser.java
===================================================================
--- trunk/dna-jcr/src/main/java/org/jboss/dna/jcr/xpath/XPathQueryParser.java 2009-11-24 17:44:29 UTC (rev 1339)
+++ trunk/dna-jcr/src/main/java/org/jboss/dna/jcr/xpath/XPathQueryParser.java 2009-11-24 17:46:37 UTC (rev 1340)
@@ -24,8 +24,8 @@
package org.jboss.dna.jcr.xpath;
import org.jboss.dna.common.text.ParsingException;
-import org.jboss.dna.graph.ExecutionContext;
import org.jboss.dna.graph.query.model.QueryCommand;
+import org.jboss.dna.graph.query.model.TypeSystem;
import org.jboss.dna.graph.query.parse.InvalidQueryException;
import org.jboss.dna.graph.query.parse.QueryParser;
import org.jboss.dna.jcr.xpath.XPath.Component;
@@ -76,15 +76,15 @@
/**
* {@inheritDoc}
*
- * @see org.jboss.dna.graph.query.parse.QueryParser#parseQuery(java.lang.String, org.jboss.dna.graph.ExecutionContext)
+ * @see org.jboss.dna.graph.query.parse.QueryParser#parseQuery(java.lang.String, org.jboss.dna.graph.query.model.TypeSystem)
*/
public QueryCommand parseQuery( String query,
- ExecutionContext context ) throws InvalidQueryException, ParsingException {
- Component xpath = new XPathParser(context).parseXPath(query);
+ TypeSystem typeSystem ) throws InvalidQueryException, ParsingException {
+ Component xpath = new XPathParser(typeSystem).parseXPath(query);
System.out.println(query);
System.out.println(" --> " + xpath);
// Convert the result into a QueryCommand ...
- QueryCommand command = new XPathToQueryTranslator(context, query).createQuery(xpath);
+ QueryCommand command = new XPathToQueryTranslator(typeSystem, query).createQuery(xpath);
return command;
}
}
Modified: trunk/dna-jcr/src/main/java/org/jboss/dna/jcr/xpath/XPathToQueryTranslator.java
===================================================================
--- trunk/dna-jcr/src/main/java/org/jboss/dna/jcr/xpath/XPathToQueryTranslator.java 2009-11-24 17:44:29 UTC (rev 1339)
+++ trunk/dna-jcr/src/main/java/org/jboss/dna/jcr/xpath/XPathToQueryTranslator.java 2009-11-24 17:46:37 UTC (rev 1340)
@@ -30,12 +30,12 @@
import java.util.List;
import java.util.Map;
import java.util.Set;
-import org.jboss.dna.graph.ExecutionContext;
import org.jboss.dna.graph.property.PropertyType;
import org.jboss.dna.graph.query.QueryBuilder;
import org.jboss.dna.graph.query.QueryBuilder.ConstraintBuilder;
import org.jboss.dna.graph.query.model.Operator;
import org.jboss.dna.graph.query.model.QueryCommand;
+import org.jboss.dna.graph.query.model.TypeSystem;
import org.jboss.dna.graph.query.parse.InvalidQueryException;
import org.jboss.dna.jcr.xpath.XPath.And;
import org.jboss.dna.jcr.xpath.XPath.AttributeNameTest;
@@ -65,33 +65,33 @@
*/
public class XPathToQueryTranslator {
- protected static final Map<NameTest, PropertyType> CAST_FUNCTION_NAME_TO_TYPE;
+ protected static final Map<NameTest, String> CAST_FUNCTION_NAME_TO_TYPE;
static {
- Map<NameTest, PropertyType> map = new HashMap<NameTest, PropertyType>();
- map.put(new NameTest("fn", "string"), PropertyType.STRING);
- map.put(new NameTest("xs", "string"), PropertyType.STRING);
- map.put(new NameTest("xs", "base64Binary"), PropertyType.BINARY);
- map.put(new NameTest("xs", "double"), PropertyType.DOUBLE);
- map.put(new NameTest("xs", "long"), PropertyType.LONG);
- map.put(new NameTest("xs", "boolean"), PropertyType.BOOLEAN);
- map.put(new NameTest("xs", "dateTime"), PropertyType.DATE);
- map.put(new NameTest("xs", "string"), PropertyType.PATH);
- map.put(new NameTest("xs", "string"), PropertyType.NAME);
- map.put(new NameTest("xs", "IDREF"), PropertyType.REFERENCE);
+ Map<NameTest, String> map = new HashMap<NameTest, String>();
+ map.put(new NameTest("fn", "string"), PropertyType.STRING.getName().toUpperCase());
+ map.put(new NameTest("xs", "string"), PropertyType.STRING.getName().toUpperCase());
+ map.put(new NameTest("xs", "base64Binary"), PropertyType.BINARY.getName().toUpperCase());
+ map.put(new NameTest("xs", "double"), PropertyType.DOUBLE.getName().toUpperCase());
+ map.put(new NameTest("xs", "long"), PropertyType.LONG.getName().toUpperCase());
+ map.put(new NameTest("xs", "boolean"), PropertyType.BOOLEAN.getName().toUpperCase());
+ map.put(new NameTest("xs", "dateTime"), PropertyType.DATE.getName().toUpperCase());
+ map.put(new NameTest("xs", "string"), PropertyType.PATH.getName().toUpperCase());
+ map.put(new NameTest("xs", "string"), PropertyType.NAME.getName().toUpperCase());
+ map.put(new NameTest("xs", "IDREF"), PropertyType.REFERENCE.getName().toUpperCase());
CAST_FUNCTION_NAME_TO_TYPE = Collections.unmodifiableMap(map);
}
private final String query;
- private final ExecutionContext context;
+ private final TypeSystem typeSystem;
private final QueryBuilder builder;
private final Set<String> aliases = new HashSet<String>();
- public XPathToQueryTranslator( ExecutionContext context,
+ public XPathToQueryTranslator( TypeSystem context,
String query ) {
this.query = query;
- this.context = context;
- this.builder = new QueryBuilder(this.context);
+ this.typeSystem = context;
+ this.builder = new QueryBuilder(this.typeSystem);
}
public QueryCommand createQuery( Component xpath ) {
@@ -429,7 +429,7 @@
NameTest functionName = call.getName();
List<Component> parameters = call.getParameters();
// Is this a cast ...
- PropertyType castType = CAST_FUNCTION_NAME_TO_TYPE.get(functionName);
+ String castType = CAST_FUNCTION_NAME_TO_TYPE.get(functionName);
if (castType != null) {
if (parameters.size() == 1 && parameters.get(0).collapse() instanceof Literal) {
// The first parameter can be the type name (or table name) ...
Modified: trunk/dna-jcr/src/test/java/org/jboss/dna/jcr/JcrSessionTest.java
===================================================================
--- trunk/dna-jcr/src/test/java/org/jboss/dna/jcr/JcrSessionTest.java 2009-11-24 17:44:29 UTC (rev 1339)
+++ trunk/dna-jcr/src/test/java/org/jboss/dna/jcr/JcrSessionTest.java 2009-11-24 17:46:37 UTC (rev 1340)
@@ -58,7 +58,6 @@
import javax.security.auth.login.LoginContext;
import org.jboss.dna.graph.JaasSecurityContext;
import org.jboss.dna.graph.property.Path;
-import org.jboss.dna.graph.property.PathFactory;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
@@ -159,9 +158,6 @@
sessionAttributes = new HashMap<String, Object>();
// Now create the workspace ...
- PathFactory pathFactory = context.getValueFactories().getPathFactory();
- Path locksPath = pathFactory.create(pathFactory.createRootPath(), JcrLexicon.SYSTEM, DnaLexicon.LOCKS);
- WorkspaceLockManager wlm = new WorkspaceLockManager(context, repository, workspaceName, locksPath);
workspace = new JcrWorkspace(repository, workspaceName, context, sessionAttributes);
// Create the session and log in ...
Modified: trunk/dna-jcr/src/test/java/org/jboss/dna/jcr/WorkspaceLockManagerTest.java
===================================================================
--- trunk/dna-jcr/src/test/java/org/jboss/dna/jcr/WorkspaceLockManagerTest.java 2009-11-24 17:44:29 UTC (rev 1339)
+++ trunk/dna-jcr/src/test/java/org/jboss/dna/jcr/WorkspaceLockManagerTest.java 2009-11-24 17:46:37 UTC (rev 1340)
@@ -8,7 +8,6 @@
import java.util.LinkedList;
import java.util.UUID;
import javax.jcr.RepositoryException;
-import javax.security.auth.login.LoginException;
import org.jboss.dna.graph.ExecutionContext;
import org.jboss.dna.graph.Graph;
import org.jboss.dna.graph.Location;
@@ -33,7 +32,7 @@
public class WorkspaceLockManagerTest {
- private Graph graph;
+ protected Graph graph;
private ExecutionContext context;
private UUID validUuid;
private Location validLocation;
@@ -43,7 +42,7 @@
private LinkedList<Request> executedRequests;
private RepositoryNodeTypeManager repoTypeManager;
- private WorkspaceLockManager workspaceLockManager;
+ protected WorkspaceLockManager workspaceLockManager;
@Mock
private RepositoryConnectionFactory connectionFactory;
@@ -51,7 +50,7 @@
protected JcrRepository repository;
@Before
- public void beforeEach() throws LoginException {
+ public void beforeEach() {
MockitoAnnotations.initMocks(this);
executedRequests = new LinkedList<Request>();
sourceName = "Source";
Modified: trunk/dna-jcr/src/test/java/org/jboss/dna/jcr/xpath/XPathParserTest.java
===================================================================
--- trunk/dna-jcr/src/test/java/org/jboss/dna/jcr/xpath/XPathParserTest.java 2009-11-24 17:44:29 UTC (rev 1339)
+++ trunk/dna-jcr/src/test/java/org/jboss/dna/jcr/xpath/XPathParserTest.java 2009-11-24 17:46:37 UTC (rev 1340)
@@ -36,6 +36,7 @@
import org.jboss.dna.common.text.TokenStream.Tokenizer;
import org.jboss.dna.graph.ExecutionContext;
import org.jboss.dna.graph.query.model.Operator;
+import org.jboss.dna.graph.query.model.TypeSystem;
import org.jboss.dna.jcr.xpath.XPath.And;
import org.jboss.dna.jcr.xpath.XPath.AnyKindTest;
import org.jboss.dna.jcr.xpath.XPath.AttributeNameTest;
@@ -70,13 +71,13 @@
*/
public class XPathParserTest {
- private ExecutionContext context;
+ private TypeSystem typeSystem;
private XPathParser parser;
@Before
public void beforeEach() {
- context = new ExecutionContext();
- parser = new XPathParser(context);
+ typeSystem = new ExecutionContext().getValueFactories().getTypeSystem();
+ parser = new XPathParser(typeSystem);
}
@After
@@ -961,7 +962,7 @@
}
protected void assertParsable( String xpath ) {
- new XPathQueryParser().parseQuery(xpath, context);
+ new XPathQueryParser().parseQuery(xpath, typeSystem);
}
protected void assertParsable( String xpath,
@@ -976,7 +977,7 @@
protected void assertNotParsable( String xpath ) {
try {
- new XPathQueryParser().parseQuery(xpath, context);
+ new XPathQueryParser().parseQuery(xpath, typeSystem);
fail("Expected an invalid XPath: " + xpath);
} catch (ParsingException e) {
// expected
Modified: trunk/dna-jcr/src/test/java/org/jboss/dna/jcr/xpath/XPathToQueryTranslatorTest.java
===================================================================
--- trunk/dna-jcr/src/test/java/org/jboss/dna/jcr/xpath/XPathToQueryTranslatorTest.java 2009-11-24 17:44:29 UTC (rev 1339)
+++ trunk/dna-jcr/src/test/java/org/jboss/dna/jcr/xpath/XPathToQueryTranslatorTest.java 2009-11-24 17:46:37 UTC (rev 1340)
@@ -28,6 +28,7 @@
import org.hamcrest.Matcher;
import org.jboss.dna.graph.ExecutionContext;
import org.jboss.dna.graph.query.model.QueryCommand;
+import org.jboss.dna.graph.query.model.TypeSystem;
import org.jboss.dna.graph.query.parse.SqlQueryParser;
import org.jboss.dna.jcr.xpath.XPath.Component;
import org.junit.After;
@@ -40,13 +41,15 @@
public class XPathToQueryTranslatorTest {
private ExecutionContext context;
+ private TypeSystem typeSystem;
private XPathParser parser;
@Before
public void beforeEach() {
context = new ExecutionContext();
context.getNamespaceRegistry().register("x", "http://example.com");
- parser = new XPathParser(context);
+ typeSystem = context.getValueFactories().getTypeSystem();
+ parser = new XPathParser(typeSystem);
}
@After
@@ -276,18 +279,18 @@
private QueryCommand translateToSql( String xpath ) {
Component component = parser.parseXPath(xpath);
- XPathToQueryTranslator translator = new XPathToQueryTranslator(context, xpath);
+ XPathToQueryTranslator translator = new XPathToQueryTranslator(typeSystem, xpath);
return translator.createQuery(component);
}
private QueryCommand xpath( String xpath ) {
Component component = parser.parseXPath(xpath);
- XPathToQueryTranslator translator = new XPathToQueryTranslator(context, xpath);
+ XPathToQueryTranslator translator = new XPathToQueryTranslator(typeSystem, xpath);
return translator.createQuery(component);
}
protected QueryCommand sql( String sql ) {
- return new SqlQueryParser().parseQuery(sql, context);
+ return new SqlQueryParser().parseQuery(sql, typeSystem);
}
protected Matcher<QueryCommand> isSql( String sql ) {
Modified: trunk/dna-jcr-tck/pom.xml
===================================================================
--- trunk/dna-jcr-tck/pom.xml 2009-11-24 17:44:29 UTC (rev 1339)
+++ trunk/dna-jcr-tck/pom.xml 2009-11-24 17:46:37 UTC (rev 1340)
@@ -4,7 +4,7 @@
<parent>
<groupId>org.jboss.dna</groupId>
<artifactId>dna</artifactId>
- <version>0.6-SNAPSHOT</version>
+ <version>0.7-SNAPSHOT</version>
</parent>
<!-- The groupId and version values are inherited from parent -->
<artifactId>dna-jcr-tck</artifactId>
Modified: trunk/dna-search/src/main/java/org/jboss/dna/search/LuceneQueryComponent.java
===================================================================
--- trunk/dna-search/src/main/java/org/jboss/dna/search/LuceneQueryComponent.java 2009-11-24 17:44:29 UTC (rev 1339)
+++ trunk/dna-search/src/main/java/org/jboss/dna/search/LuceneQueryComponent.java 2009-11-24 17:46:37 UTC (rev 1340)
@@ -34,11 +34,9 @@
import org.apache.lucene.search.TermQuery;
import org.apache.lucene.search.BooleanClause.Occur;
import org.jboss.dna.common.i18n.I18n;
-import org.jboss.dna.graph.ExecutionContext;
import org.jboss.dna.graph.property.Binary;
-import org.jboss.dna.graph.property.Name;
+import org.jboss.dna.graph.property.Path;
import org.jboss.dna.graph.property.PropertyType;
-import org.jboss.dna.graph.property.ValueFactory;
import org.jboss.dna.graph.query.QueryContext;
import org.jboss.dna.graph.query.QueryResults.Columns;
import org.jboss.dna.graph.query.model.And;
@@ -68,9 +66,11 @@
import org.jboss.dna.graph.query.model.SelectorName;
import org.jboss.dna.graph.query.model.SetCriteria;
import org.jboss.dna.graph.query.model.StaticOperand;
+import org.jboss.dna.graph.query.model.TypeSystem;
import org.jboss.dna.graph.query.model.UpperCase;
import org.jboss.dna.graph.query.model.Visitors;
import org.jboss.dna.graph.query.model.FullTextSearch.NegationTerm;
+import org.jboss.dna.graph.query.model.TypeSystem.TypeFactory;
import org.jboss.dna.graph.query.plan.PlanNode;
import org.jboss.dna.graph.query.process.AbstractAccessComponent;
import org.jboss.dna.graph.query.process.ProcessingComponent;
@@ -106,8 +106,9 @@
this.workspaceName = workspaceName;
}
- protected String fieldNameFor( Name name ) {
- return session.stringFactory.create(name);
+ protected String fieldNameFor( String name ) {
+ // Convert to a name and then to a string, so that the namespaces are resolved
+ return session.stringFactory.create(session.nameFactory.create(name));
}
/**
@@ -175,14 +176,14 @@
// There was a error working with the constraints (such as a ValueFormatException) ...
QueryContext context = getContext();
I18n msg = SearchI18n.errorWhilePerformingQuery;
- String origQueryString = Visitors.readable(originalQuery, context.getExecutionContext());
+ String origQueryString = Visitors.readable(originalQuery);
context.getProblems().addError(e, msg, origQueryString, workspaceName, sourceName, e.getMessage());
return emptyTuples();
} catch (RuntimeException e) {
// There was a error working with the constraints (such as a ValueFormatException) ...
QueryContext context = getContext();
I18n msg = SearchI18n.errorWhilePerformingQuery;
- String origQueryString = Visitors.readable(originalQuery, context.getExecutionContext());
+ String origQueryString = Visitors.readable(originalQuery);
context.getProblems().addError(e, msg, origQueryString, workspaceName, sourceName, e.getMessage());
return emptyTuples();
}
@@ -196,7 +197,6 @@
List<Object[]> tuples = null;
final Columns columns = getColumns();
final QueryContext context = getContext();
- final ExecutionContext execContext = context.getExecutionContext();
try {
// Execute the query against the content indexes ...
IndexSearcher searcher = session.getContentSearcher();
@@ -206,7 +206,7 @@
} catch (IOException e) {
// There was a problem executing the Lucene query ...
I18n msg = SearchI18n.errorWhilePerformingLuceneQuery;
- String origQueryString = Visitors.readable(originalQuery, execContext);
+ String origQueryString = Visitors.readable(originalQuery);
context.getProblems().addError(e, msg, pushDownQuery, origQueryString, workspaceName, sourceName, e.getMessage());
return emptyTuples();
}
@@ -287,7 +287,7 @@
if (constraint instanceof FullTextSearch) {
FullTextSearch search = (FullTextSearch)constraint;
String fieldName = ContentIndex.FULL_TEXT;
- Name propertyName = search.getPropertyName();
+ String propertyName = search.getPropertyName();
if (propertyName != null) {
fieldName = session.fullTextFieldName(fieldNameFor(propertyName));
}
@@ -296,15 +296,18 @@
try {
if (constraint instanceof SameNode) {
SameNode sameNode = (SameNode)constraint;
- return session.findNodeAt(sameNode.getPath());
+ Path path = session.pathFactory.create(sameNode.getPath());
+ return session.findNodeAt(path);
}
if (constraint instanceof ChildNode) {
ChildNode childNode = (ChildNode)constraint;
- return session.findChildNodes(childNode.getParentPath());
+ Path path = session.pathFactory.create(childNode.getParentPath());
+ return session.findChildNodes(path);
}
if (constraint instanceof DescendantNode) {
DescendantNode descendantNode = (DescendantNode)constraint;
- return session.findAllNodesBelow(descendantNode.getAncestorPath());
+ Path path = session.pathFactory.create(descendantNode.getAncestorPath());
+ return session.findAllNodesBelow(path);
}
} catch (IOException e) {
I18n msg = SearchI18n.errorWhilePerformingQuery;
@@ -435,13 +438,14 @@
return ((String)value).toLowerCase();
}
assert !(value instanceof Binary);
- ValueFactory<String> stringFactory = getContext().getExecutionContext().getValueFactories().getStringFactory();
- ValueFactory<?> valueFactory = getContext().getExecutionContext().getValueFactories().getValueFactory(value);
+ TypeSystem typeSystem = getContext().getTypeSystem();
+ TypeFactory<String> stringFactory = typeSystem.getStringFactory();
+ TypeFactory<?> valueFactory = typeSystem.getTypeFactory(value);
return valueFactory.create(stringFactory.create(value).toLowerCase());
}
protected Query createQuery( SelectorName selectorName,
- Name propertyName ) {
+ String propertyName ) {
Term term = new Term(fieldNameFor(propertyName));
return new TermQuery(term);
}
Modified: trunk/dna-search/src/test/java/org/jboss/dna/search/SearchEngineTest.java
===================================================================
--- trunk/dna-search/src/test/java/org/jboss/dna/search/SearchEngineTest.java 2009-11-24 17:44:29 UTC (rev 1339)
+++ trunk/dna-search/src/test/java/org/jboss/dna/search/SearchEngineTest.java 2009-11-24 17:46:37 UTC (rev 1340)
@@ -40,10 +40,10 @@
import org.jboss.dna.graph.property.Path;
import org.jboss.dna.graph.query.QueryResults;
import org.jboss.dna.graph.query.model.QueryCommand;
+import org.jboss.dna.graph.query.model.TypeSystem;
import org.jboss.dna.graph.query.parse.SqlQueryParser;
import org.jboss.dna.graph.query.validate.ImmutableSchemata;
import org.jboss.dna.graph.query.validate.Schemata;
-import org.jboss.dna.graph.query.validate.ImmutableSchemata.Builder;
import org.jboss.dna.graph.search.SearchEngine;
import org.jboss.dna.graph.search.SearchProvider;
import org.junit.Before;
@@ -56,6 +56,7 @@
private SearchEngine engine;
private SearchProvider provider;
private ExecutionContext context;
+ private TypeSystem typeSystem;
private String sourceName;
private String workspaceName1;
private String workspaceName2;
@@ -68,6 +69,7 @@
@Before
public void beforeEach() throws Exception {
context = new ExecutionContext();
+ typeSystem = context.getValueFactories().getTypeSystem();
sourceName = "sourceA";
workspaceName1 = "workspace1";
workspaceName2 = "workspace2";
@@ -100,10 +102,7 @@
loadContent();
// Create the schemata for the workspaces ...
- Builder builder = ImmutableSchemata.createBuilder(context);
- builder.addTable("__ALLNODES__", "maker", "model", "year");
- schemata = builder.build();
- schemata = ImmutableSchemata.createBuilder(context)
+ schemata = ImmutableSchemata.createBuilder(typeSystem)
.addTable("__ALLNODES__", "maker", "model", "year", "msrp")
.makeSearchable("__ALLNODES__", "maker")
.build();
@@ -227,7 +226,7 @@
@Test
public void shouldFindNodesBySimpleXpathQuery() {
engine.index(workspaceName1, path("/"), 100);
- QueryCommand query = sql.parseQuery("SELECT model, maker FROM __ALLNODES__", context);
+ QueryCommand query = sql.parseQuery("SELECT model, maker FROM __ALLNODES__", typeSystem);
QueryResults results = engine.query(context, workspaceName1, query, schemata);
assertThat(results, is(notNullValue()));
assertThat(results.getRowCount(), is(18));
@@ -241,7 +240,7 @@
@Test
public void shouldFindNodesBySimpleQuery() {
engine.index(workspaceName1, path("/"), 100);
- QueryCommand query = sql.parseQuery("SELECT model, maker FROM __ALLNODES__", context);
+ QueryCommand query = sql.parseQuery("SELECT model, maker FROM __ALLNODES__", typeSystem);
QueryResults results = engine.query(context, workspaceName1, query, schemata);
assertThat(results, is(notNullValue()));
assertThat(results.getRowCount(), is(18));
@@ -251,7 +250,7 @@
@Test
public void shouldFindNodesBySimpleQueryWithEqualityComparisonCriteria() {
engine.index(workspaceName1, path("/"), 100);
- QueryCommand query = sql.parseQuery("SELECT model, maker FROM __ALLNODES__ WHERE maker = 'Toyota'", context);
+ QueryCommand query = sql.parseQuery("SELECT model, maker FROM __ALLNODES__ WHERE maker = 'Toyota'", typeSystem);
QueryResults results = engine.query(context, workspaceName1, query, schemata);
assertThat(results, is(notNullValue()));
assertThat(results.getRowCount(), is(2));
@@ -262,7 +261,7 @@
@Test
public void shouldFindNodesBySimpleQueryWithGreaterThanComparisonCriteria() {
engine.index(workspaceName1, path("/"), 100);
- QueryCommand query = sql.parseQuery("SELECT model, maker FROM __ALLNODES__ WHERE mpgHighway > 20", context);
+ QueryCommand query = sql.parseQuery("SELECT model, maker FROM __ALLNODES__ WHERE mpgHighway > 20", typeSystem);
QueryResults results = engine.query(context, workspaceName1, query, schemata);
assertThat(results, is(notNullValue()));
assertThat(results.getRowCount(), is(2));
@@ -272,7 +271,7 @@
@Test
public void shouldFindNodesBySimpleQueryWithLowercaseEqualityComparisonCriteria() {
engine.index(workspaceName1, path("/"), 100);
- QueryCommand query = sql.parseQuery("SELECT model, maker FROM __ALLNODES__ WHERE LOWER(maker) = 'toyota'", context);
+ QueryCommand query = sql.parseQuery("SELECT model, maker FROM __ALLNODES__ WHERE LOWER(maker) = 'toyota'", typeSystem);
QueryResults results = engine.query(context, workspaceName1, query, schemata);
assertThat(results, is(notNullValue()));
assertThat(results.getRowCount(), is(2));
@@ -282,7 +281,7 @@
@Test
public void shouldFindNodesBySimpleQueryWithUppercaseEqualityComparisonCriteria() {
engine.index(workspaceName1, path("/"), 100);
- QueryCommand query = sql.parseQuery("SELECT model, maker FROM __ALLNODES__ WHERE UPPER(maker) = 'TOYOTA'", context);
+ QueryCommand query = sql.parseQuery("SELECT model, maker FROM __ALLNODES__ WHERE UPPER(maker) = 'TOYOTA'", typeSystem);
QueryResults results = engine.query(context, workspaceName1, query, schemata);
assertThat(results, is(notNullValue()));
assertThat(results.getRowCount(), is(2));
@@ -292,7 +291,7 @@
@Test
public void shouldFindNodesBySimpleQueryWithLikeComparisonCriteria() {
engine.index(workspaceName1, path("/"), 100);
- QueryCommand query = sql.parseQuery("SELECT model, maker FROM __ALLNODES__ WHERE maker LIKE 'Toyo%'", context);
+ QueryCommand query = sql.parseQuery("SELECT model, maker FROM __ALLNODES__ WHERE maker LIKE 'Toyo%'", typeSystem);
QueryResults results = engine.query(context, workspaceName1, query, schemata);
assertThat(results, is(notNullValue()));
assertThat(results.getRowCount(), is(2));
@@ -302,7 +301,7 @@
@Test
public void shouldFindNodesBySimpleQueryWithLikeComparisonCriteriaWithLeadingWildcard() {
engine.index(workspaceName1, path("/"), 100);
- QueryCommand query = sql.parseQuery("SELECT model, maker FROM __ALLNODES__ WHERE maker LIKE '%yota'", context);
+ QueryCommand query = sql.parseQuery("SELECT model, maker FROM __ALLNODES__ WHERE maker LIKE '%yota'", typeSystem);
QueryResults results = engine.query(context, workspaceName1, query, schemata);
assertThat(results, is(notNullValue()));
assertThat(results.getRowCount(), is(2));
@@ -312,7 +311,7 @@
@Test
public void shouldFindNodesBySimpleQueryWithLowercaseLikeComparisonCriteria() {
engine.index(workspaceName1, path("/"), 100);
- QueryCommand query = sql.parseQuery("SELECT model, maker FROM __ALLNODES__ WHERE LOWER(maker) LIKE 'toyo%'", context);
+ QueryCommand query = sql.parseQuery("SELECT model, maker FROM __ALLNODES__ WHERE LOWER(maker) LIKE 'toyo%'", typeSystem);
QueryResults results = engine.query(context, workspaceName1, query, schemata);
assertThat(results, is(notNullValue()));
assertThat(results.getRowCount(), is(2));
@@ -322,7 +321,7 @@
@Test
public void shouldFindNodesBySimpleQueryWithFullTextSearchCriteria() {
engine.index(workspaceName1, path("/"), 100);
- QueryCommand query = sql.parseQuery("SELECT model, maker FROM __ALLNODES__ WHERE CONTAINS(maker,'martin')", context);
+ QueryCommand query = sql.parseQuery("SELECT model, maker FROM __ALLNODES__ WHERE CONTAINS(maker,'martin')", typeSystem);
QueryResults results = engine.query(context, workspaceName1, query, schemata);
assertNoErrors(results);
assertThat(results, is(notNullValue()));
@@ -333,7 +332,7 @@
@Test
public void shouldFindNodesBySimpleQueryWithDepthCriteria() {
engine.index(workspaceName1, path("/"), 100);
- QueryCommand query = sql.parseQuery("SELECT model, maker FROM __ALLNODES__ WHERE DEPTH() > 2", context);
+ QueryCommand query = sql.parseQuery("SELECT model, maker FROM __ALLNODES__ WHERE DEPTH() > 2", typeSystem);
QueryResults results = engine.query(context, workspaceName1, query, schemata);
assertNoErrors(results);
assertThat(results, is(notNullValue()));
@@ -345,7 +344,7 @@
public void shouldFindNodesBySimpleQueryWithLocalNameCriteria() {
engine.index(workspaceName1, path("/"), 100);
QueryCommand query = sql.parseQuery("SELECT model, maker FROM __ALLNODES__ WHERE LOCALNAME() LIKE 'Toyota%' OR LOCALNAME() LIKE 'Land %'",
- context);
+ typeSystem);
QueryResults results = engine.query(context, workspaceName1, query, schemata);
assertNoErrors(results);
assertThat(results, is(notNullValue()));
@@ -357,7 +356,7 @@
public void shouldFindNodesBySimpleQueryWithNameCriteria() {
engine.index(workspaceName1, path("/"), 100);
QueryCommand query = sql.parseQuery("SELECT model, maker FROM __ALLNODES__ WHERE NAME() LIKE 'Toyota%[1]' OR NAME() LIKE 'Land %'",
- context);
+ typeSystem);
QueryResults results = engine.query(context, workspaceName1, query, schemata);
assertNoErrors(results);
assertThat(results, is(notNullValue()));
@@ -368,7 +367,7 @@
@Test
public void shouldFindNodesBySimpleQueryWithNameCriteriaThatMatchesNoNodes() {
engine.index(workspaceName1, path("/"), 100);
- QueryCommand query = sql.parseQuery("SELECT model, maker FROM __ALLNODES__ WHERE NAME() LIKE 'Toyota%[2]'", context);
+ QueryCommand query = sql.parseQuery("SELECT model, maker FROM __ALLNODES__ WHERE NAME() LIKE 'Toyota%[2]'", typeSystem);
QueryResults results = engine.query(context, workspaceName1, query, schemata);
assertNoErrors(results);
assertThat(results, is(notNullValue()));
@@ -380,7 +379,7 @@
public void shouldFindNodesBySimpleQueryWithPathCriteria() {
engine.index(workspaceName1, path("/"), 100);
QueryCommand query = sql.parseQuery("SELECT model, maker FROM __ALLNODES__ WHERE PATH() LIKE '/Cars[%]/Hy%/Toyota%' OR PATH() LIKE '/Cars[1]/Utility[1]/%'",
- context);
+ typeSystem);
QueryResults results = engine.query(context, workspaceName1, query, schemata);
assertNoErrors(results);
assertThat(results, is(notNullValue()));
@@ -392,7 +391,7 @@
public void shouldFindNodesBySimpleQueryWithDescendantCriteria() {
engine.index(workspaceName1, path("/"), 100);
QueryCommand query = sql.parseQuery("SELECT model, maker FROM __ALLNODES__ WHERE ISDESCENDANTNODE('/Cars/Hybrid')",
- context);
+ typeSystem);
QueryResults results = engine.query(context, workspaceName1, query, schemata);
assertNoErrors(results);
assertThat(results, is(notNullValue()));
14 years, 5 months
DNA SVN: r1339 - in trunk: dna-graph/src/main/java/org/jboss/dna/graph/query/process and 3 other directories.
by dna-commits@lists.jboss.org
Author: rhauch
Date: 2009-11-24 12:44:29 -0500 (Tue, 24 Nov 2009)
New Revision: 1339
Added:
trunk/dna-search/src/main/java/org/jboss/dna/search/query/IdsQuery.java
Removed:
trunk/dna-search/src/main/java/org/jboss/dna/search/query/UuidsQuery.java
Modified:
trunk/dna-graph/src/main/java/org/jboss/dna/graph/query/QueryResults.java
trunk/dna-graph/src/main/java/org/jboss/dna/graph/query/process/QueryProcessor.java
trunk/dna-graph/src/main/java/org/jboss/dna/graph/query/process/QueryResults.java
trunk/dna-search/src/main/java/org/jboss/dna/search/DualIndexSearchProvider.java
trunk/dna-search/src/main/java/org/jboss/dna/search/IndexRules.java
trunk/dna-search/src/main/java/org/jboss/dna/search/LuceneQueryComponent.java
trunk/dna-search/src/main/java/org/jboss/dna/search/LuceneSession.java
trunk/dna-search/src/main/java/org/jboss/dna/search/query/CompareQuery.java
trunk/dna-search/src/main/java/org/jboss/dna/search/query/CompareStringQuery.java
trunk/dna-search/src/test/java/org/jboss/dna/search/SearchEngineTest.java
Log:
DNA-467 Integrated the Lucene implementation of the SearchEngine component, added a number of unit tests.
Modified: trunk/dna-graph/src/main/java/org/jboss/dna/graph/query/QueryResults.java
===================================================================
--- trunk/dna-graph/src/main/java/org/jboss/dna/graph/query/QueryResults.java 2009-11-24 17:43:50 UTC (rev 1338)
+++ trunk/dna-graph/src/main/java/org/jboss/dna/graph/query/QueryResults.java 2009-11-24 17:44:29 UTC (rev 1339)
@@ -80,6 +80,13 @@
public List<Object[]> getTuples();
/**
+ * Get the number of rows in the results.
+ *
+ * @return the number of rows; never negative
+ */
+ public int getRowCount();
+
+ /**
* Get the problems encountered during execution.
*
* @return the problems; never null but possibly empty
Modified: trunk/dna-graph/src/main/java/org/jboss/dna/graph/query/process/QueryProcessor.java
===================================================================
--- trunk/dna-graph/src/main/java/org/jboss/dna/graph/query/process/QueryProcessor.java 2009-11-24 17:43:50 UTC (rev 1338)
+++ trunk/dna-graph/src/main/java/org/jboss/dna/graph/query/process/QueryProcessor.java 2009-11-24 17:44:29 UTC (rev 1339)
@@ -162,7 +162,7 @@
switch (node.getType()) {
case ACCESS:
// If the ACCESS node will not have results ...
- if (node.getProperty(Property.ACCESS_NO_RESULTS, Boolean.class)) {
+ if (node.hasProperty(Property.ACCESS_NO_RESULTS)) {
component = new NoResultsComponent(context, columns);
} else {
// Create the component to handle the ACCESS node ...
Modified: trunk/dna-graph/src/main/java/org/jboss/dna/graph/query/process/QueryResults.java
===================================================================
--- trunk/dna-graph/src/main/java/org/jboss/dna/graph/query/process/QueryResults.java 2009-11-24 17:43:50 UTC (rev 1338)
+++ trunk/dna-graph/src/main/java/org/jboss/dna/graph/query/process/QueryResults.java 2009-11-24 17:44:29 UTC (rev 1339)
@@ -138,6 +138,15 @@
/**
* {@inheritDoc}
*
+ * @see org.jboss.dna.graph.query.QueryResults#getRowCount()
+ */
+ public int getRowCount() {
+ return tuples.size();
+ }
+
+ /**
+ * {@inheritDoc}
+ *
* @see org.jboss.dna.graph.query.QueryResults#getProblems()
*/
public Problems getProblems() {
@@ -251,6 +260,7 @@
for (Object[] tuple : getTuples()) {
for (int i = 0, j = 1; i != tupleLength; ++i, ++j) {
String valueStr = stringOf(tuple[i], stringFactory);
+ if (valueStr == null) continue;
columnWidths[j] = Math.max(Math.min(maxWidth, valueStr.length()), columnWidths[j]);
}
}
Modified: trunk/dna-search/src/main/java/org/jboss/dna/search/DualIndexSearchProvider.java
===================================================================
--- trunk/dna-search/src/main/java/org/jboss/dna/search/DualIndexSearchProvider.java 2009-11-24 17:43:50 UTC (rev 1338)
+++ trunk/dna-search/src/main/java/org/jboss/dna/search/DualIndexSearchProvider.java 2009-11-24 17:44:29 UTC (rev 1339)
@@ -28,6 +28,7 @@
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.HashSet;
+import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
@@ -60,15 +61,14 @@
import org.apache.lucene.search.Scorer;
import org.apache.lucene.search.TermQuery;
import org.apache.lucene.search.TopDocs;
-import org.apache.lucene.search.WildcardQuery;
import org.apache.lucene.search.BooleanClause.Occur;
-import org.apache.lucene.search.regex.JavaUtilRegexCapabilities;
-import org.apache.lucene.search.regex.RegexQuery;
import org.apache.lucene.store.Directory;
import org.apache.lucene.util.Version;
import org.jboss.dna.common.text.NoOpEncoder;
+import org.jboss.dna.common.text.SecureHashTextEncoder;
import org.jboss.dna.common.text.TextEncoder;
import org.jboss.dna.common.util.Logger;
+import org.jboss.dna.common.util.SecureHash.Algorithm;
import org.jboss.dna.graph.DnaLexicon;
import org.jboss.dna.graph.ExecutionContext;
import org.jboss.dna.graph.JcrLexicon;
@@ -77,8 +77,8 @@
import org.jboss.dna.graph.property.Binary;
import org.jboss.dna.graph.property.DateTime;
import org.jboss.dna.graph.property.Name;
+import org.jboss.dna.graph.property.NamespaceRegistry;
import org.jboss.dna.graph.property.Path;
-import org.jboss.dna.graph.property.PathFactory;
import org.jboss.dna.graph.property.Property;
import org.jboss.dna.graph.property.PropertyType;
import org.jboss.dna.graph.property.ValueFactories;
@@ -107,13 +107,14 @@
import org.jboss.dna.graph.search.SearchException;
import org.jboss.dna.graph.search.SearchProvider;
import org.jboss.dna.search.IndexRules.Rule;
+import org.jboss.dna.search.LuceneSession.TupleCollector;
import org.jboss.dna.search.query.CompareLengthQuery;
import org.jboss.dna.search.query.CompareNameQuery;
import org.jboss.dna.search.query.ComparePathQuery;
import org.jboss.dna.search.query.CompareStringQuery;
+import org.jboss.dna.search.query.IdsQuery;
import org.jboss.dna.search.query.MatchNoneQuery;
import org.jboss.dna.search.query.NotQuery;
-import org.jboss.dna.search.query.UuidsQuery;
/**
* A simple {@link SearchProvider} implementation that relies upon two separate indexes: one for the node content and a second one
@@ -134,8 +135,8 @@
static {
IndexRules.Builder builder = IndexRules.createBuilder();
// Configure the default behavior ...
- builder.defaultTo(IndexRules.INDEX | IndexRules.ANALYZE | IndexRules.FULL_TEXT);
- // Configure the UUID properties to be just indexed (not stored, not analyzed, not included in full-text) ...
+ builder.defaultTo(IndexRules.INDEX | IndexRules.FULL_TEXT | IndexRules.STORE);
+ // Configure the UUID properties to be just indexed and stored (not analyzed, not included in full-text) ...
builder.store(JcrLexicon.UUID, DnaLexicon.UUID);
// Configure the properties that we'll treat as dates ...
builder.treatAsDates(JcrLexicon.CREATED, JcrLexicon.LAST_MODIFIED);
@@ -150,24 +151,40 @@
protected static final double MAX_DOUBLE = Double.MAX_VALUE;
protected static final int MIN_DEPTH = 0;
protected static final int MAX_DEPTH = 100;
+ protected static final int MIN_SNS_INDEX = 1;
+ protected static final int MAX_SNS_INDEX = 1000; // assume there won't be more than 1000 same-name-siblings
protected static final String PATHS_INDEX_NAME = "paths";
protected static final String CONTENT_INDEX_NAME = "content";
- protected static final String UUID_FIELD = "uuid";
- protected static final String FULL_TEXT_SUFFIX = "/fs"; // the slash character is not allowed in a property name unescaped
+ /**
+ * Given the name of a property field of the form "<namespace>:<local>" (where <namespace> can be zero-length), this
+ * provider also stores the value(s) for free-text searching in a field named ":ft:<namespace>:<local>". Thus, even if
+ * the namespace is zero-length, the free-text search field will be named ":ft::<local>" and will not clash with any other
+ * property name.
+ */
+ protected static final String FULL_TEXT_PREFIX = ":ft:";
+ /**
+ * This index stores only these fields, so we can use the most obvious names and not worry about clashes.
+ */
static class PathIndex {
- public static final String PATH = "path";
- public static final String LOCAL_NAME = "name";
+ public static final String PATH = "pth";
+ public static final String NODE_NAME = "nam";
+ public static final String LOCAL_NAME = "loc";
public static final String SNS_INDEX = "sns";
- public static final String UUID = UUID_FIELD;
- public static final String DEPTH = "depth";
+ public static final String LOCATION_ID_PROPERTIES = "idp";
+ public static final String ID = ContentIndex.ID;
+ public static final String DEPTH = "dep";
}
+ /**
+ * This index stores these two fields <i>plus</i> all properties. Therefore, we have to worry about name clashes, which is why
+ * these field names are prefixed with '::', which is something that does appear in property names as they are serialized.
+ */
static class ContentIndex {
- public static final String UUID = UUID_FIELD;
- public static final String FULL_TEXT = "fts";
+ public static final String ID = "::id";
+ public static final String FULL_TEXT = "::fts";
}
/**
@@ -190,12 +207,13 @@
private static final long serialVersionUID = 1L;
public FieldSelectorResult accept( String fieldName ) {
- return PathIndex.UUID.equals(fieldName) ? FieldSelectorResult.LOAD_AND_BREAK : FieldSelectorResult.NO_LOAD;
+ return PathIndex.ID.equals(fieldName) ? FieldSelectorResult.LOAD_AND_BREAK : FieldSelectorResult.NO_LOAD;
}
};
private final IndexRules rules;
private final LuceneConfiguration directoryConfiguration;
+ private final TextEncoder namespaceEncoder;
public DualIndexSearchProvider( LuceneConfiguration directoryConfiguration,
IndexRules rules ) {
@@ -203,6 +221,7 @@
assert rules != null;
this.rules = rules;
this.directoryConfiguration = directoryConfiguration;
+ this.namespaceEncoder = new SecureHashTextEncoder(Algorithm.SHA_1, 10);
}
public DualIndexSearchProvider( LuceneConfiguration directoryConfiguration ) {
@@ -253,7 +272,9 @@
assert contentIndexDirectory != null;
Analyzer analyzer = createAnalyzer();
assert analyzer != null;
- return new DualIndexSession(context, sourceName, workspaceName, rules, pathIndexDirectory, contentIndexDirectory,
+ NamespaceRegistry encodingRegistry = new EncodingNamespaceRegistry(context.getNamespaceRegistry(), namespaceEncoder);
+ ExecutionContext encodingContext = context.with(encodingRegistry);
+ return new DualIndexSession(encodingContext, sourceName, workspaceName, rules, pathIndexDirectory, contentIndexDirectory,
analyzer, overwrite, readOnly);
}
@@ -304,9 +325,82 @@
*/
@Override
protected String fullTextFieldName( String propertyName ) {
- return propertyName + FULL_TEXT_SUFFIX;
+ return FULL_TEXT_PREFIX + propertyName;
}
+ protected void addIdProperties( Location location,
+ Document doc ) {
+ if (!location.hasIdProperties()) return;
+ for (Property idProp : location.getIdProperties()) {
+ String fieldValue = serializeProperty(idProp);
+ doc.add(new Field(PathIndex.LOCATION_ID_PROPERTIES, fieldValue, Field.Store.YES, Field.Index.NOT_ANALYZED));
+ }
+ }
+
+ protected Location readLocation( Document doc ) {
+ // Read the path ...
+ String pathString = doc.get(PathIndex.PATH);
+ Path path = pathFactory.create(pathString);
+ // Look for the Location's ID properties ...
+ String[] idProps = doc.getValues(PathIndex.LOCATION_ID_PROPERTIES);
+ if (idProps.length == 0) {
+ return Location.create(path);
+ }
+ if (idProps.length == 1) {
+ Property idProp = deserializeProperty(idProps[0]);
+ if (idProp == null) return Location.create(path);
+ if (idProp.isSingle() && (idProp.getName().equals(JcrLexicon.UUID) || idProp.getName().equals(DnaLexicon.UUID))) {
+ return Location.create(path, (UUID)idProp.getFirstValue()); // know that deserialize returns UUID value
+ }
+ return Location.create(path, idProp);
+ }
+ List<Property> properties = new LinkedList<Property>();
+ for (String idProp : doc.getValues(PathIndex.LOCATION_ID_PROPERTIES)) {
+ Property prop = deserializeProperty(idProp);
+ if (prop != null) properties.add(prop);
+ }
+ return properties.isEmpty() ? Location.create(path) : Location.create(path, properties);
+
+ }
+
+ protected final String serializeProperty( Property property ) {
+ StringBuilder sb = new StringBuilder();
+ sb.append(stringFactory.create(property.getName()));
+ sb.append('=');
+ Iterator<?> iter = property.getValues();
+ if (iter.hasNext()) {
+ sb.append(stringFactory.create(iter.next()));
+ }
+ while (iter.hasNext()) {
+ sb.append('\n');
+ sb.append(stringFactory.create(iter.next()));
+ }
+ return sb.toString();
+ }
+
+ protected final Property deserializeProperty( String propertyString ) {
+ int index = propertyString.indexOf('=');
+ assert index > -1;
+ if (index == propertyString.length() - 1) return null;
+ Name propName = nameFactory.create(propertyString.substring(0, index));
+ String valueString = propertyString.substring(index + 1);
+ // Break into multiple values if multiple lines ...
+ String[] values = valueString.split("\\n");
+ if (values.length == 0) return null;
+ if (values.length == 1) {
+ Object value = values[0];
+ if (DnaLexicon.UUID.equals(propName) || JcrLexicon.UUID.equals(propName)) {
+ value = uuidFactory.create(value);
+ }
+ return context.getPropertyFactory().create(propName, value);
+ }
+ List<String> propValues = new LinkedList<String>();
+ for (String value : values) {
+ propValues.add(value);
+ }
+ return context.getPropertyFactory().create(propName, propValues);
+ }
+
protected IndexReader getPathsReader() throws IOException {
if (pathsReader == null) {
pathsReader = IndexReader.open(pathsIndexDirectory, readOnly);
@@ -379,9 +473,10 @@
UUID uuid = location.getUuid();
if (uuid == null) uuid = UUID.randomUUID();
Path path = location.getPath();
- String uuidStr = stringFactory.create(uuid);
+ String idStr = stringFactory.create(uuid);
String pathStr = pathAsString(path, stringFactory);
String nameStr = path.isRoot() ? "" : stringFactory.create(path.getLastSegment().getName());
+ String localNameStr = path.isRoot() ? "" : path.getLastSegment().getName().getLocalName();
int sns = path.isRoot() ? 1 : path.getLastSegment().getIndex();
Logger logger = Logger.getLogger(getClass());
@@ -395,15 +490,17 @@
// be changed without changing any other content fields ...
Document doc = new Document();
doc.add(new Field(PathIndex.PATH, pathStr, Field.Store.YES, Field.Index.NOT_ANALYZED));
- doc.add(new Field(PathIndex.LOCAL_NAME, nameStr, Field.Store.YES, Field.Index.ANALYZED));
- doc.add(new NumericField(PathIndex.LOCAL_NAME, Field.Store.YES, true).setIntValue(sns));
- doc.add(new Field(PathIndex.UUID, uuidStr, Field.Store.YES, Field.Index.NOT_ANALYZED));
+ doc.add(new Field(PathIndex.NODE_NAME, nameStr, Field.Store.YES, Field.Index.NOT_ANALYZED));
+ doc.add(new Field(PathIndex.LOCAL_NAME, localNameStr, Field.Store.YES, Field.Index.NOT_ANALYZED));
+ doc.add(new NumericField(PathIndex.SNS_INDEX, Field.Store.YES, true).setIntValue(sns));
+ doc.add(new Field(PathIndex.ID, idStr, Field.Store.YES, Field.Index.NOT_ANALYZED));
doc.add(new NumericField(PathIndex.DEPTH, Field.Store.YES, true).setIntValue(path.size()));
+ addIdProperties(location, doc);
getPathsWriter().addDocument(doc);
// Create the document for the content (properties) ...
doc = new Document();
- doc.add(new Field(ContentIndex.UUID, uuidStr, Field.Store.YES, Field.Index.NOT_ANALYZED));
+ doc.add(new Field(ContentIndex.ID, idStr, Field.Store.YES, Field.Index.NOT_ANALYZED));
String stringValue = null;
StringBuilder fullTextSearchValue = null;
for (Property property : node.getProperties()) {
@@ -506,12 +603,12 @@
assert !readOnly;
try {
// Create a query to find all the nodes at or below the specified path ...
- Set<UUID> uuids = getUuidsForDescendantsOf(path, true);
- Query uuidQuery = findAllNodesWithUuids(uuids);
+ Set<String> ids = getIdsForDescendantsOf(path, true);
+ Query uuidQuery = findAllNodesWithIds(ids);
// Now delete the documents from each index using this query, which we can reuse ...
getPathsWriter().deleteDocuments(uuidQuery);
getContentWriter().deleteDocuments(uuidQuery);
- return uuids.size();
+ return ids.size();
} catch (FileNotFoundException e) {
// There are no index files yet, so nothing to delete ...
return 0;
@@ -551,24 +648,19 @@
int numberOfResults = scoreDocs.length;
if (numberOfResults > offset) {
// There are enough results to satisfy the offset ...
- PathFactory pathFactory = context.getValueFactories().getPathFactory();
for (int i = offset, num = scoreDocs.length; i != num; ++i) {
ScoreDoc result = scoreDocs[i];
int docId = result.doc;
// Find the UUID of the node (this UUID might be artificial, so we have to find the path) ...
Document doc = contentReader.document(docId, UUID_FIELD_SELECTOR);
- String uuid = doc.get(ContentIndex.UUID);
- // Find the path for this node (is there a better way to do this than one search per UUID?) ...
- TopDocs pathDocs = pathSearcher.search(new TermQuery(new Term(PathIndex.UUID, uuid)), 1);
- if (pathDocs.scoreDocs.length < 1) {
+ String id = doc.get(ContentIndex.ID);
+ Location location = getLocationForDocument(id, pathReader, pathSearcher);
+ if (location == null) {
// No path record found ...
continue;
}
- Document pathDoc = pathReader.document(pathDocs.scoreDocs[0].doc);
- String pathString = pathDoc.get(PathIndex.PATH);
- Path path = pathFactory.create(pathString);
// Now add the location ...
- results.add(Location.create(path, UUID.fromString(uuid)));
+ results.add(location);
}
}
} catch (ParseException e) {
@@ -579,6 +671,26 @@
}
}
+ protected Location getLocationForDocument( String id,
+ IndexReader pathReader,
+ IndexSearcher pathSearcher ) throws IOException {
+ // Find the path for this node (is there a better way to do this than one search per ID?) ...
+ TopDocs pathDocs = pathSearcher.search(new TermQuery(new Term(PathIndex.ID, id)), 1);
+ if (pathDocs.scoreDocs.length < 1) {
+ // No path record found ...
+ return null;
+ }
+ Document pathDoc = pathReader.document(pathDocs.scoreDocs[0].doc);
+ return readLocation(pathDoc);
+ }
+
+ protected UUID getUuid( Document document,
+ Name name ) {
+ String nameString = stringFactory.create(name);
+ String value = document.get(nameString);
+ return value != null ? uuidFactory.create(value) : null;
+ }
+
/**
* {@inheritDoc}
*
@@ -802,13 +914,23 @@
}
/**
- * Get the set of UUIDs for the children of the node at the given path.
+ * {@inheritDoc}
*
+ * @see org.jboss.dna.search.LuceneSession#createTupleCollector(Columns)
+ */
+ @Override
+ public TupleCollector createTupleCollector( Columns columns ) {
+ return new DualIndexTupleCollector(this, columns);
+ }
+
+ /**
+ * Get the set of IDs for the children of the node at the given path.
+ *
* @param parentPath the path to the parent node; may not be null
- * @return the UUIDs of the child nodes; never null but possibly empty
+ * @return the doc IDs of the child nodes; never null but possibly empty
* @throws IOException if there is an error accessing the indexes
*/
- protected Set<UUID> getUuidsForChildrenOf( Path parentPath ) throws IOException {
+ protected Set<String> getIdsForChildrenOf( Path parentPath ) throws IOException {
// Find the path of the parent ...
String stringifiedPath = pathAsString(parentPath, stringFactory);
// Append a '/' to the parent path, so we'll only get decendants ...
@@ -825,23 +947,23 @@
combinedQuery.add(depthQuery, Occur.MUST);
query = combinedQuery;
- // Now execute and collect the UUIDs ...
- UuidCollector uuidCollector = new UuidCollector();
+ // Now execute and collect the IDs ...
+ IdCollector idCollector = new IdCollector();
IndexSearcher searcher = getPathsSearcher();
- searcher.search(query, uuidCollector);
- return uuidCollector.getUuids();
+ searcher.search(query, idCollector);
+ return idCollector.getIds();
}
/**
- * Get the set of UUIDs for the nodes that are descendants of the node at the given path.
+ * Get the set of IDs for the nodes that are descendants of the node at the given path.
*
* @param parentPath the path to the parent node; may not be null and <i>may not be the root node</i>
* @param includeParent true if the parent node should be included in the results, or false if only the descendants should
* be included
- * @return the UUIDs of the nodes; never null but possibly empty
+ * @return the IDs of the nodes; never null but possibly empty
* @throws IOException if there is an error accessing the indexes
*/
- protected Set<UUID> getUuidsForDescendantsOf( Path parentPath,
+ protected Set<String> getIdsForDescendantsOf( Path parentPath,
boolean includeParent ) throws IOException {
assert !parentPath.isRoot();
@@ -855,21 +977,21 @@
// Create a prefix query ...
Query query = new PrefixQuery(new Term(PathIndex.PATH, stringifiedPath));
- // Now execute and collect the UUIDs ...
- UuidCollector uuidCollector = new UuidCollector();
+ // Now execute and collect the IDs ...
+ IdCollector idCollector = new IdCollector();
IndexSearcher searcher = getPathsSearcher();
- searcher.search(query, uuidCollector);
- return uuidCollector.getUuids();
+ searcher.search(query, idCollector);
+ return idCollector.getIds();
}
/**
- * Get the set containing the single UUID for the node at the given path.
+ * Get the set containing the single ID for the node at the given path.
*
* @param path the path to the node; may not be null
- * @return the UUID of the supplied node; or null if the node cannot be found
+ * @return the ID of the supplied node; or null if the node cannot be found
* @throws IOException if there is an error accessing the indexes
*/
- protected UUID getUuidFor( Path path ) throws IOException {
+ protected String getIdFor( Path path ) throws IOException {
// Create a query to find all the nodes below the parent path ...
IndexSearcher searcher = getPathsSearcher();
String stringifiedPath = pathAsString(path, stringFactory);
@@ -879,38 +1001,38 @@
TopDocs topDocs = searcher.search(query, 1);
if (topDocs.totalHits == 0) return null;
Document pathDoc = getPathsReader().document(topDocs.scoreDocs[0].doc);
- String uuidString = pathDoc.get(PathIndex.UUID);
- return UUID.fromString(uuidString);
+ String idString = pathDoc.get(PathIndex.ID);
+ assert idString != null;
+ return idString;
}
/**
- * Utility method to create a query to find all of the documents representing nodes with the supplied UUIDs.
+ * {@inheritDoc}
*
- * @param uuids the UUIDs of the nodes that are to be found; may not be null
- * @return the query; never null
+ * @see org.jboss.dna.search.LuceneSession#findAllNodesWithIds(java.util.Set)
*/
@Override
- public Query findAllNodesWithUuids( Set<UUID> uuids ) {
- if (uuids.isEmpty()) {
+ public Query findAllNodesWithIds( Set<String> ids ) {
+ if (ids.isEmpty()) {
// There are no children, so return a null query ...
return new MatchNoneQuery();
}
- if (uuids.size() == 1) {
- UUID uuid = uuids.iterator().next();
- if (uuid == null) return new MatchNoneQuery();
- return new TermQuery(new Term(ContentIndex.UUID, uuid.toString()));
+ if (ids.size() == 1) {
+ String id = ids.iterator().next();
+ if (id == null) return new MatchNoneQuery();
+ return new TermQuery(new Term(ContentIndex.ID, id));
}
- if (uuids.size() < 50) {
+ if (ids.size() < 50) {
// Create an OR boolean query for all the UUIDs, since this is probably more efficient ...
BooleanQuery query = new BooleanQuery();
- for (UUID uuid : uuids) {
- Query uuidQuery = new TermQuery(new Term(ContentIndex.UUID, uuid.toString()));
+ for (String id : ids) {
+ Query uuidQuery = new TermQuery(new Term(ContentIndex.ID, id));
query.add(uuidQuery, Occur.SHOULD);
}
return query;
}
// Return a query that will always find all of the UUIDs ...
- return new UuidsQuery(ContentIndex.UUID, uuids, getContext().getValueFactories().getUuidFactory());
+ return new IdsQuery(ContentIndex.ID, ids);
}
@Override
@@ -918,8 +1040,8 @@
if (ancestorPath.isRoot()) {
return new MatchAllDocsQuery();
}
- Set<UUID> uuids = getUuidsForDescendantsOf(ancestorPath, false);
- return findAllNodesWithUuids(uuids);
+ Set<String> ids = getIdsForDescendantsOf(ancestorPath, false);
+ return findAllNodesWithIds(ids);
}
/**
@@ -935,58 +1057,37 @@
if (parentPath.isRoot()) {
return new MatchAllDocsQuery();
}
- Set<UUID> childUuids = getUuidsForChildrenOf(parentPath);
- return findAllNodesWithUuids(childUuids);
+ Set<String> childIds = getIdsForChildrenOf(parentPath);
+ return findAllNodesWithIds(childIds);
}
/**
* Create a query that can be used to find the one document (or node) that exists at the exact path supplied. This method
- * first queries the {@link PathIndex path index} to find the UUID of the node at the supplied path, and then returns a
- * query that matches the UUID.
+ * first queries the {@link PathIndex path index} to find the ID of the node at the supplied path, and then returns a
+ * query that matches the ID.
*
* @param path the path of the node
* @return the query; never null
- * @throws IOException if there is an error finding the UUID for the supplied path
+ * @throws IOException if there is an error finding the ID for the supplied path
*/
@Override
public Query findNodeAt( Path path ) throws IOException {
- UUID uuid = getUuidFor(path);
- if (uuid == null) return null;
- return new TermQuery(new Term(ContentIndex.UUID, uuid.toString()));
+ String id = getIdFor(path);
+ if (id == null) return null;
+ return new TermQuery(new Term(ContentIndex.ID, id));
}
/**
- * Create a query that can be used to find documents (or nodes) that have a field value that satisfies the supplied LIKE
- * expression.
+ * {@inheritDoc}
*
- * @param fieldName the name of the document field to search
- * @param likeExpression the JCR like expression
- * @return the query; never null
+ * @see org.jboss.dna.search.LuceneSession#findNodesLike(java.lang.String, java.lang.String, boolean)
*/
@Override
public Query findNodesLike( String fieldName,
- String likeExpression ) {
- assert likeExpression != null;
- assert likeExpression.length() > 0;
-
- // '%' matches 0 or more characters
- // '_' matches any single character
- // '\x' matches 'x'
- // all other characters match themselves
-
- // Wildcard queries are a better match, but they can be slow and should not be used
- // if the first character of the expression is a '%' or '_' ...
- char firstChar = likeExpression.charAt(0);
- if (firstChar != '%' && firstChar != '_') {
- // Create a wildcard query ...
- String expression = toWildcardExpression(likeExpression);
- return new WildcardQuery(new Term(fieldName, expression));
- }
- // Create a regex query,
- String regex = toRegularExpression(likeExpression);
- RegexQuery query = new RegexQuery(new Term(fieldName, regex));
- query.setRegexImplementation(new JavaUtilRegexCapabilities());
- return query;
+ String likeExpression,
+ boolean caseSensitive ) {
+ ValueFactories factories = context.getValueFactories();
+ return CompareStringQuery.createQueryForNodesWithFieldLike(likeExpression, fieldName, factories, caseSensitive);
}
@Override
@@ -1042,9 +1143,15 @@
if (!caseSensitive) stringValue = stringValue.toLowerCase();
switch (operator) {
case EQUAL_TO:
- return new TermQuery(new Term(field, stringValue));
+ return CompareStringQuery.createQueryForNodesWithFieldEqualTo(stringValue,
+ field,
+ factories,
+ caseSensitive);
case NOT_EQUAL_TO:
- Query query = new TermQuery(new Term(field, stringValue));
+ Query query = CompareStringQuery.createQueryForNodesWithFieldEqualTo(stringValue,
+ field,
+ factories,
+ caseSensitive);
return new NotQuery(query);
case GREATER_THAN:
return CompareStringQuery.createQueryForNodesWithFieldGreaterThan(stringValue,
@@ -1067,7 +1174,7 @@
factories,
caseSensitive);
case LIKE:
- return findNodesLike(field, stringValue);
+ return findNodesLike(field, stringValue, caseSensitive);
}
break;
case DATE:
@@ -1239,7 +1346,8 @@
return new NotQuery(findNodeAt(pathValue));
case LIKE:
String likeExpression = stringFactory.create(value);
- return findNodesLike(PathIndex.PATH, likeExpression);
+ query = findNodesLike(PathIndex.PATH, likeExpression, caseSensitive);
+ break;
case GREATER_THAN:
query = ComparePathQuery.createQueryForNodesWithPathGreaterThan(pathValue,
PathIndex.PATH,
@@ -1265,11 +1373,11 @@
caseSensitive);
break;
}
- // Now execute and collect the UUIDs ...
- UuidCollector uuidCollector = new UuidCollector();
+ // Now execute and collect the IDs ...
+ IdCollector idCollector = new IdCollector();
IndexSearcher searcher = getPathsSearcher();
- searcher.search(query, uuidCollector);
- return findAllNodesWithUuids(uuidCollector.getUuids());
+ searcher.search(query, idCollector);
+ return findAllNodesWithIds(idCollector.getIds());
}
@Override
@@ -1277,6 +1385,7 @@
Operator operator,
Object value,
boolean caseSensitive ) throws IOException {
+ ValueFactories factories = getContext().getValueFactories();
String stringValue = stringFactory.create(value);
if (!caseSensitive) stringValue = stringValue.toLowerCase();
Path.Segment segment = operator != Operator.LIKE ? pathFactory.createSegment(stringValue) : null;
@@ -1285,42 +1394,42 @@
switch (operator) {
case EQUAL_TO:
BooleanQuery booleanQuery = new BooleanQuery();
- booleanQuery.add(new TermQuery(new Term(PathIndex.LOCAL_NAME, stringValue)), Occur.MUST);
+ booleanQuery.add(new TermQuery(new Term(PathIndex.NODE_NAME, stringValue)), Occur.MUST);
booleanQuery.add(NumericRangeQuery.newIntRange(PathIndex.SNS_INDEX, snsIndex, snsIndex, true, false),
Occur.MUST);
return booleanQuery;
case NOT_EQUAL_TO:
booleanQuery = new BooleanQuery();
- booleanQuery.add(new TermQuery(new Term(PathIndex.LOCAL_NAME, stringValue)), Occur.MUST);
+ booleanQuery.add(new TermQuery(new Term(PathIndex.NODE_NAME, stringValue)), Occur.MUST);
booleanQuery.add(NumericRangeQuery.newIntRange(PathIndex.SNS_INDEX, snsIndex, snsIndex, true, false),
Occur.MUST);
return new NotQuery(booleanQuery);
case GREATER_THAN:
query = CompareNameQuery.createQueryForNodesWithNameGreaterThan(segment,
- PathIndex.LOCAL_NAME,
+ PathIndex.NODE_NAME,
PathIndex.SNS_INDEX,
- context.getValueFactories(),
+ factories,
caseSensitive);
break;
case GREATER_THAN_OR_EQUAL_TO:
query = CompareNameQuery.createQueryForNodesWithNameGreaterThanOrEqualTo(segment,
- PathIndex.LOCAL_NAME,
+ PathIndex.NODE_NAME,
PathIndex.SNS_INDEX,
- context.getValueFactories(),
+ factories,
caseSensitive);
break;
case LESS_THAN:
query = CompareNameQuery.createQueryForNodesWithNameLessThan(segment,
- PathIndex.LOCAL_NAME,
+ PathIndex.NODE_NAME,
PathIndex.SNS_INDEX,
- context.getValueFactories(),
+ factories,
caseSensitive);
break;
case LESS_THAN_OR_EQUAL_TO:
query = CompareNameQuery.createQueryForNodesWithNameLessThanOrEqualTo(segment,
- PathIndex.LOCAL_NAME,
+ PathIndex.NODE_NAME,
PathIndex.SNS_INDEX,
- context.getValueFactories(),
+ factories,
caseSensitive);
break;
case LIKE:
@@ -1330,7 +1439,10 @@
if (openBracketIndex != -1) {
String localNameExpression = likeExpression.substring(0, openBracketIndex);
String snsIndexExpression = likeExpression.substring(openBracketIndex);
- Query localNameQuery = createLocalNameQuery(localNameExpression);
+ Query localNameQuery = CompareStringQuery.createQueryForNodesWithFieldLike(localNameExpression,
+ PathIndex.NODE_NAME,
+ factories,
+ caseSensitive);
Query snsQuery = createSnsIndexQuery(snsIndexExpression);
if (localNameQuery == null) {
if (snsQuery == null) {
@@ -1353,17 +1465,20 @@
}
} else {
// There is no SNS expression ...
- query = createLocalNameQuery(likeExpression);
+ query = CompareStringQuery.createQueryForNodesWithFieldLike(likeExpression,
+ PathIndex.NODE_NAME,
+ factories,
+ caseSensitive);
}
assert query != null;
break;
}
- // Now execute and collect the UUIDs ...
- UuidCollector uuidCollector = new UuidCollector();
+ // Now execute and collect the IDs ...
+ IdCollector idCollector = new IdCollector();
IndexSearcher searcher = getPathsSearcher();
- searcher.search(query, uuidCollector);
- return findAllNodesWithUuids(uuidCollector.getUuids());
+ searcher.search(query, idCollector);
+ return findAllNodesWithIds(idCollector.getIds());
}
@Override
@@ -1376,12 +1491,20 @@
switch (operator) {
case LIKE:
String likeExpression = stringFactory.create(value);
- return findNodesLike(PathIndex.LOCAL_NAME, likeExpression); // already is a query with UUIDs
+ query = findNodesLike(PathIndex.LOCAL_NAME, likeExpression, caseSensitive);
+ break;
case EQUAL_TO:
- query = new TermQuery(new Term(PathIndex.LOCAL_NAME, nameValue));
+ query = CompareStringQuery.createQueryForNodesWithFieldEqualTo(nameValue,
+ PathIndex.LOCAL_NAME,
+ context.getValueFactories(),
+ caseSensitive);
break;
case NOT_EQUAL_TO:
- query = new NotQuery(new TermQuery(new Term(PathIndex.LOCAL_NAME, nameValue)));
+ query = CompareStringQuery.createQueryForNodesWithFieldEqualTo(nameValue,
+ PathIndex.LOCAL_NAME,
+ context.getValueFactories(),
+ caseSensitive);
+ query = new NotQuery(query);
break;
case GREATER_THAN:
query = CompareStringQuery.createQueryForNodesWithFieldGreaterThan(nameValue,
@@ -1409,11 +1532,11 @@
break;
}
- // Now execute and collect the UUIDs ...
- UuidCollector uuidCollector = new UuidCollector();
+ // Now execute and collect the IDs ...
+ IdCollector idCollector = new IdCollector();
IndexSearcher searcher = getPathsSearcher();
- searcher.search(query, uuidCollector);
- return findAllNodesWithUuids(uuidCollector.getUuids());
+ searcher.search(query, idCollector);
+ return findAllNodesWithIds(idCollector.getIds());
}
@Override
@@ -1447,25 +1570,34 @@
return null;
}
- // Now execute and collect the UUIDs ...
- UuidCollector uuidCollector = new UuidCollector();
+ // Now execute and collect the IDs ...
+ IdCollector idCollector = new IdCollector();
IndexSearcher searcher = getPathsSearcher();
- searcher.search(query, uuidCollector);
- return findAllNodesWithUuids(uuidCollector.getUuids());
+ searcher.search(query, idCollector);
+ return findAllNodesWithIds(idCollector.getIds());
}
- protected Query createLocalNameQuery( String likeExpression ) {
+ protected Query createLocalNameQuery( String likeExpression,
+ boolean caseSensitive ) {
if (likeExpression == null) return null;
- likeExpression = likeExpression.trim();
- if (likeExpression.length() == 0) return null;
- if (likeExpression.indexOf('?') != -1 || likeExpression.indexOf('*') != -1) {
- // The local name is a like ...
- return findNodesLike(PathIndex.LOCAL_NAME, likeExpression);
- }
- // The local name is an exact match ...
- return new TermQuery(new Term(PathIndex.LOCAL_NAME, likeExpression));
+ ValueFactories factories = getContext().getValueFactories();
+ return CompareStringQuery.createQueryForNodesWithFieldLike(likeExpression,
+ PathIndex.LOCAL_NAME,
+ factories,
+ caseSensitive);
}
+ /**
+ * Utility method to generate a query against the SNS indexes. This method attempts to generate a query that works most
+ * efficiently, depending upon the supplied expression. For example, if the supplied expression is just "[3]", then a
+ * range query is used to find all values matching '3'. However, if "[3_]" is used (where '_' matches any
+ * single-character, or digit in this case), then a range query is used to find all values between '30' and '39'.
+ * Similarly, if "[3%]" is used, then a regular expression query is used.
+ *
+ * @param likeExpression the expression that uses the JCR 2.0 LIKE representation, and which includes the leading '[' and
+ * trailing ']' characters
+ * @return the query, or null if the expression cannot be represented as a query
+ */
protected Query createSnsIndexQuery( String likeExpression ) {
if (likeExpression == null) return null;
likeExpression = likeExpression.trim();
@@ -1480,16 +1612,51 @@
if (closeBracketIndex != -1) {
likeExpression = likeExpression.substring(0, closeBracketIndex);
}
- // If SNS expression contains '?' or '*' ...
- if (likeExpression.indexOf('?') != -1 || likeExpression.indexOf('*') != -1) {
- // There is a LIKE expression for the SNS ...
- return findNodesLike(PathIndex.SNS_INDEX, likeExpression);
+ if (likeExpression.equals("_")) {
+ // The SNS expression can only be one digit ...
+ return NumericRangeQuery.newIntRange(PathIndex.SNS_INDEX, MIN_SNS_INDEX, 9, true, true);
}
+ if (likeExpression.equals("%")) {
+ // The SNS expression can be any digits ...
+ return NumericRangeQuery.newIntRange(PathIndex.SNS_INDEX, MIN_SNS_INDEX, MAX_SNS_INDEX, true, true);
+ }
+ if (likeExpression.indexOf('_') != -1) {
+ if (likeExpression.indexOf('%') != -1) {
+ // Contains both ...
+ return findNodesLike(PathIndex.SNS_INDEX, likeExpression, true);
+ }
+ // It presumably contains some numbers and at least one '_' character ...
+ int firstWildcardChar = likeExpression.indexOf('_');
+ if (firstWildcardChar + 1 < likeExpression.length()) {
+ // There's at least some characters after the first '_' ...
+ int secondWildcardChar = likeExpression.indexOf('_', firstWildcardChar + 1);
+ if (secondWildcardChar != -1) {
+ // There are multiple '_' characters ...
+ return findNodesLike(PathIndex.SNS_INDEX, likeExpression, true);
+ }
+ }
+ // There's only one '_', so parse the lowermost value and uppermost value ...
+ String lowerExpression = likeExpression.replace('_', '0');
+ String upperExpression = likeExpression.replace('_', '9');
+ try {
+ // This SNS is just a number ...
+ int lowerSns = Integer.parseInt(lowerExpression);
+ int upperSns = Integer.parseInt(upperExpression);
+ return NumericRangeQuery.newIntRange(PathIndex.SNS_INDEX, lowerSns, upperSns, true, true);
+ } catch (NumberFormatException e) {
+ // It's not a number but it's in the SNS field, so there will be no results ...
+ return new MatchNoneQuery();
+ }
+ }
+ if (likeExpression.indexOf('%') != -1) {
+ // It presumably contains some numbers and at least one '%' character ...
+ return findNodesLike(PathIndex.SNS_INDEX, likeExpression, true);
+ }
// This is not a LIKE expression but an exact value specification and should be a number ...
try {
// This SNS is just a number ...
int sns = Integer.parseInt(likeExpression);
- return NumericRangeQuery.newIntRange(PathIndex.SNS_INDEX, sns, sns, true, false);
+ return NumericRangeQuery.newIntRange(PathIndex.SNS_INDEX, sns, sns, true, true);
} catch (NumberFormatException e) {
// It's not a number but it's in the SNS field, so there will be no results ...
return new MatchNoneQuery();
@@ -1505,13 +1672,13 @@
*
* @see DualIndexSearchProvider.DualIndexSession#findChildNodes(Path)
*/
- protected static class UuidCollector extends Collector {
- private final Set<UUID> uuids = new HashSet<UUID>();
- private String[] uuidsByDocId;
+ protected static class IdCollector extends Collector {
+ private final Set<String> ids = new HashSet<String>();
+ private String[] idsByDocId;
// private int baseDocId;
- protected UuidCollector() {
+ protected IdCollector() {
}
/**
@@ -1519,8 +1686,8 @@
*
* @return the set of UUIDs; never null
*/
- public Set<UUID> getUuids() {
- return uuids;
+ public Set<String> getIds() {
+ return ids;
}
/**
@@ -1551,9 +1718,9 @@
@Override
public void collect( int docId ) {
assert docId >= 0;
- String uuidString = uuidsByDocId[docId];
- assert uuidString != null;
- uuids.add(UUID.fromString(uuidString));
+ String idString = idsByDocId[docId];
+ assert idString != null;
+ ids.add(idString);
}
/**
@@ -1564,8 +1731,148 @@
@Override
public void setNextReader( IndexReader reader,
int docBase ) throws IOException {
- this.uuidsByDocId = FieldCache.DEFAULT.getStrings(reader, UUID_FIELD);
+ this.idsByDocId = FieldCache.DEFAULT.getStrings(reader, ContentIndex.ID); // same value as PathIndex.ID
// this.baseDocId = docBase;
}
}
+
+ /**
+ * This collector is responsible for loading the value for each of the columns into each tuple array.
+ */
+ protected class DualIndexTupleCollector extends TupleCollector {
+ private final DualIndexSession session;
+ private final LinkedList<Object[]> tuples = new LinkedList<Object[]>();
+ private final Columns columns;
+ private final int numValues;
+ private final boolean recordScore;
+ private final int scoreIndex;
+ private final FieldSelector fieldSelector;
+ private final int locationIndex;
+ private Scorer scorer;
+ private IndexReader currentReader;
+ private int docOffset;
+ private boolean resolvedLocations = false;
+
+ protected DualIndexTupleCollector( DualIndexSession session,
+ Columns columns ) {
+ this.session = session;
+ this.columns = columns;
+ assert this.session != null;
+ assert this.columns != null;
+ this.numValues = this.columns.getTupleSize();
+ assert this.numValues >= 0;
+ assert this.columns.getSelectorNames().size() == 1;
+ final String selectorName = this.columns.getSelectorNames().get(0);
+ this.locationIndex = this.columns.getLocationIndex(selectorName);
+ this.recordScore = this.columns.hasFullTextSearchScores();
+ this.scoreIndex = this.recordScore ? this.columns.getFullTextSearchScoreIndexFor(selectorName) : -1;
+ final Set<String> columnNames = new HashSet<String>(this.columns.getColumnNames());
+ columnNames.add(ContentIndex.ID); // add the UUID, which we'll put into the Location ...
+ this.fieldSelector = new FieldSelector() {
+ private static final long serialVersionUID = 1L;
+
+ public FieldSelectorResult accept( String fieldName ) {
+ return columnNames.contains(fieldName) ? FieldSelectorResult.LOAD : FieldSelectorResult.NO_LOAD;
+ }
+ };
+ }
+
+ /**
+ * @return tuples
+ */
+ @Override
+ public LinkedList<Object[]> getTuples() {
+ resolveLocations();
+ return tuples;
+ }
+
+ protected void resolveLocations() {
+ if (resolvedLocations) return;
+ try {
+ // The Location field in the tuples all contain the ID of the document, so we need to replace these
+ // with the appropriate Location objects, using the content from the PathIndex ...
+ IndexReader pathReader = session.getPathsReader();
+ IndexSearcher pathSearcher = session.getPathsSearcher();
+ for (Object[] tuple : tuples) {
+ String id = (String)tuple[locationIndex];
+ assert id != null;
+ Location location = session.getLocationForDocument(id, pathReader, pathSearcher);
+ assert location != null;
+ tuple[locationIndex] = location;
+ }
+ resolvedLocations = true;
+ } catch (IOException e) {
+ throw new LuceneException(e);
+ }
+ }
+
+ /**
+ * {@inheritDoc}
+ *
+ * @see org.apache.lucene.search.Collector#acceptsDocsOutOfOrder()
+ */
+ @Override
+ public boolean acceptsDocsOutOfOrder() {
+ return true;
+ }
+
+ /**
+ * Get the location index.
+ *
+ * @return locationIndex
+ */
+ public int getLocationIndex() {
+ return locationIndex;
+ }
+
+ /**
+ * {@inheritDoc}
+ *
+ * @see org.apache.lucene.search.Collector#setNextReader(org.apache.lucene.index.IndexReader, int)
+ */
+ @Override
+ public void setNextReader( IndexReader reader,
+ int docBase ) {
+ this.currentReader = reader;
+ this.docOffset = docBase;
+ }
+
+ /**
+ * {@inheritDoc}
+ *
+ * @see org.apache.lucene.search.Collector#setScorer(org.apache.lucene.search.Scorer)
+ */
+ @Override
+ public void setScorer( Scorer scorer ) {
+ this.scorer = scorer;
+ }
+
+ /**
+ * {@inheritDoc}
+ *
+ * @see org.apache.lucene.search.Collector#collect(int)
+ */
+ @Override
+ public void collect( int doc ) throws IOException {
+ int docId = doc + docOffset;
+ Object[] tuple = new Object[numValues];
+ Document document = currentReader.document(docId, fieldSelector);
+ for (String columnName : columns.getColumnNames()) {
+ int index = columns.getColumnIndexForName(columnName);
+ // We just need to retrieve the first value if there is more than one ...
+ tuple[index] = document.get(columnName);
+ }
+
+ // Set the score column if required ...
+ if (recordScore) {
+ assert scorer != null;
+ tuple[scoreIndex] = scorer.score();
+ }
+
+ // Load the document ID (which is a stringified UUID) into the Location slot,
+ // which will be replaced later with a real Location ...
+ tuple[locationIndex] = document.get(ContentIndex.ID);
+ tuples.add(tuple);
+ }
+ }
}
Modified: trunk/dna-search/src/main/java/org/jboss/dna/search/IndexRules.java
===================================================================
--- trunk/dna-search/src/main/java/org/jboss/dna/search/IndexRules.java 2009-11-24 17:43:50 UTC (rev 1338)
+++ trunk/dna-search/src/main/java/org/jboss/dna/search/IndexRules.java 2009-11-24 17:44:29 UTC (rev 1339)
@@ -339,7 +339,7 @@
*/
public static Builder createBuilder( IndexRules initialRules ) {
CheckArg.isNotNull(initialRules, "initialRules");
- return new Builder(initialRules.rulesByName).defaultTo(initialRules.defaultRule);
+ return new Builder(new HashMap<Name, Rule>(initialRules.rulesByName)).defaultTo(initialRules.defaultRule);
}
/**
Modified: trunk/dna-search/src/main/java/org/jboss/dna/search/LuceneQueryComponent.java
===================================================================
--- trunk/dna-search/src/main/java/org/jboss/dna/search/LuceneQueryComponent.java 2009-11-24 17:43:50 UTC (rev 1338)
+++ trunk/dna-search/src/main/java/org/jboss/dna/search/LuceneQueryComponent.java 2009-11-24 17:44:29 UTC (rev 1339)
@@ -24,28 +24,17 @@
package org.jboss.dna.search;
import java.io.IOException;
-import java.util.HashSet;
-import java.util.LinkedList;
import java.util.List;
-import java.util.Set;
-import java.util.UUID;
-import org.apache.lucene.document.Document;
-import org.apache.lucene.document.FieldSelector;
-import org.apache.lucene.document.FieldSelectorResult;
-import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.Term;
import org.apache.lucene.search.BooleanQuery;
-import org.apache.lucene.search.Collector;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.MatchAllDocsQuery;
import org.apache.lucene.search.PhraseQuery;
import org.apache.lucene.search.Query;
-import org.apache.lucene.search.Scorer;
import org.apache.lucene.search.TermQuery;
import org.apache.lucene.search.BooleanClause.Occur;
import org.jboss.dna.common.i18n.I18n;
import org.jboss.dna.graph.ExecutionContext;
-import org.jboss.dna.graph.Location;
import org.jboss.dna.graph.property.Binary;
import org.jboss.dna.graph.property.Name;
import org.jboss.dna.graph.property.PropertyType;
@@ -88,6 +77,7 @@
import org.jboss.dna.graph.query.process.SelectComponent;
import org.jboss.dna.graph.query.process.SelectComponent.Analyzer;
import org.jboss.dna.search.DualIndexSearchProvider.ContentIndex;
+import org.jboss.dna.search.LuceneSession.TupleCollector;
/**
*
@@ -210,7 +200,7 @@
try {
// Execute the query against the content indexes ...
IndexSearcher searcher = session.getContentSearcher();
- TupleCollector collector = new TupleCollector(columns, execContext.getValueFactories().getUuidFactory());
+ TupleCollector collector = session.createTupleCollector(columns);
searcher.search(pushDownQuery, collector);
tuples = collector.getTuples();
} catch (IOException e) {
@@ -498,112 +488,4 @@
assert false;
return null;
}
-
- /**
- * This collector is responsible for loading the value for each of the columns into each tuple array.
- */
- protected static class TupleCollector extends Collector {
- private final LinkedList<Object[]> tuples = new LinkedList<Object[]>();
- private final Columns columns;
- private final int numValues;
- private final boolean recordScore;
- private final int scoreIndex;
- private final FieldSelector fieldSelector;
- private final int locationIndex;
- private final ValueFactory<UUID> uuidFactory;
- private Scorer scorer;
- private IndexReader currentReader;
- private int docOffset;
-
- protected TupleCollector( Columns columns,
- ValueFactory<UUID> uuidFactory ) {
- this.columns = columns;
- this.uuidFactory = uuidFactory;
- assert this.columns != null;
- assert this.uuidFactory != null;
- this.numValues = this.columns.getTupleSize();
- assert this.numValues >= 0;
- assert this.columns.getSelectorNames().size() == 1;
- final String selectorName = this.columns.getSelectorNames().get(0);
- this.locationIndex = this.columns.getLocationIndex(selectorName);
- this.recordScore = this.columns.hasFullTextSearchScores();
- this.scoreIndex = this.recordScore ? this.columns.getFullTextSearchScoreIndexFor(selectorName) : -1;
- final Set<String> columnNames = new HashSet<String>(this.columns.getColumnNames());
- columnNames.add(ContentIndex.UUID); // add the UUID, which we'll put into the Location ...
- this.fieldSelector = new FieldSelector() {
- private static final long serialVersionUID = 1L;
-
- public FieldSelectorResult accept( String fieldName ) {
- return columnNames.contains(fieldName) ? FieldSelectorResult.LOAD : FieldSelectorResult.NO_LOAD;
- }
- };
- }
-
- /**
- * @return tuples
- */
- public LinkedList<Object[]> getTuples() {
- return tuples;
- }
-
- /**
- * {@inheritDoc}
- *
- * @see org.apache.lucene.search.Collector#acceptsDocsOutOfOrder()
- */
- @Override
- public boolean acceptsDocsOutOfOrder() {
- return true;
- }
-
- /**
- * {@inheritDoc}
- *
- * @see org.apache.lucene.search.Collector#setNextReader(org.apache.lucene.index.IndexReader, int)
- */
- @Override
- public void setNextReader( IndexReader reader,
- int docBase ) {
- this.currentReader = reader;
- this.docOffset = docBase;
- }
-
- /**
- * {@inheritDoc}
- *
- * @see org.apache.lucene.search.Collector#setScorer(org.apache.lucene.search.Scorer)
- */
- @Override
- public void setScorer( Scorer scorer ) {
- this.scorer = scorer;
- }
-
- /**
- * {@inheritDoc}
- *
- * @see org.apache.lucene.search.Collector#collect(int)
- */
- @Override
- public void collect( int doc ) throws IOException {
- int docId = doc + docOffset;
- Object[] tuple = new Object[numValues];
- Document document = currentReader.document(docId, fieldSelector);
- for (String columnName : columns.getColumnNames()) {
- int index = columns.getColumnIndexForName(columnName);
- // We just need to retrieve the first value if there is more than one ...
- tuple[index] = document.get(columnName);
- }
-
- // Set the score column if required ...
- if (recordScore) {
- assert scorer != null;
- tuple[scoreIndex] = scorer.score();
- }
-
- // Load the UUID into a Location object ...
- UUID uuid = uuidFactory.create(document.get(ContentIndex.UUID));
- tuple[locationIndex] = Location.create(uuid);
- tuples.add(tuple);
- }
- }
}
Modified: trunk/dna-search/src/main/java/org/jboss/dna/search/LuceneSession.java
===================================================================
--- trunk/dna-search/src/main/java/org/jboss/dna/search/LuceneSession.java 2009-11-24 17:43:50 UTC (rev 1338)
+++ trunk/dna-search/src/main/java/org/jboss/dna/search/LuceneSession.java 2009-11-24 17:44:29 UTC (rev 1339)
@@ -26,16 +26,19 @@
import java.io.IOException;
import java.util.LinkedList;
import java.util.Set;
-import java.util.UUID;
import net.jcip.annotations.NotThreadSafe;
import org.apache.lucene.analysis.Analyzer;
+import org.apache.lucene.search.Collector;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.jboss.dna.common.i18n.I18n;
import org.jboss.dna.graph.ExecutionContext;
import org.jboss.dna.graph.property.DateTimeFactory;
+import org.jboss.dna.graph.property.NameFactory;
import org.jboss.dna.graph.property.Path;
import org.jboss.dna.graph.property.PathFactory;
+import org.jboss.dna.graph.property.UuidFactory;
+import org.jboss.dna.graph.property.ValueFactories;
import org.jboss.dna.graph.property.ValueFactory;
import org.jboss.dna.graph.query.QueryContext;
import org.jboss.dna.graph.query.QueryEngine;
@@ -76,6 +79,8 @@
protected final ValueFactory<String> stringFactory;
protected final DateTimeFactory dateFactory;
protected final PathFactory pathFactory;
+ protected final UuidFactory uuidFactory;
+ protected final NameFactory nameFactory;
private int changeCount;
private QueryEngine queryEngine;
@@ -93,9 +98,12 @@
this.overwrite = overwrite;
this.readOnly = readOnly;
this.analyzer = analyzer;
- this.stringFactory = context.getValueFactories().getStringFactory();
- this.dateFactory = context.getValueFactories().getDateFactory();
- this.pathFactory = context.getValueFactories().getPathFactory();
+ ValueFactories factories = context.getValueFactories();
+ this.stringFactory = factories.getStringFactory();
+ this.dateFactory = factories.getDateFactory();
+ this.pathFactory = factories.getPathFactory();
+ this.uuidFactory = factories.getUuidFactory();
+ this.nameFactory = factories.getNameFactory();
assert this.context != null;
assert this.sourceName != null;
assert this.workspaceName != null;
@@ -227,13 +235,21 @@
throws IOException;
/**
- * Utility method to create a query to find all of the documents representing nodes with the supplied UUIDs.
+ * Create a {@link TupleCollector} instance that collects the results from the index(es).
*
- * @param uuids the UUIDs of the nodes that are to be found; may not be null
+ * @param columns the column definitions; never null
+ * @return the collector; never null
+ */
+ public abstract TupleCollector createTupleCollector( Columns columns );
+
+ /**
+ * Utility method to create a query to find all of the documents representing nodes with the supplied IDs.
+ *
+ * @param ids the IDs of the nodes that are to be found; may not be null
* @return the query; never null
* @throws IOException if there is a problem creating this query
*/
- public abstract Query findAllNodesWithUuids( Set<UUID> uuids ) throws IOException;
+ public abstract Query findAllNodesWithIds( Set<String> ids ) throws IOException;
public abstract Query findAllNodesBelow( Path ancestorPath ) throws IOException;
@@ -264,11 +280,13 @@
*
* @param fieldName the name of the document field to search
* @param likeExpression the JCR like expression
+ * @param caseSensitive true if the evaluation should be performed in a case sensitive manner, or false otherwise
* @return the query; never null
* @throws IOException if there is an error creating the query
*/
public abstract Query findNodesLike( String fieldName,
- String likeExpression ) throws IOException;
+ String likeExpression,
+ boolean caseSensitive ) throws IOException;
public abstract Query findNodesWith( Length propertyLength,
Operator operator,
@@ -320,49 +338,28 @@
// public abstract Query createSnsIndexQuery( String likeExpression ) throws IOException;
- /**
- * Convert the JCR like expression to a Lucene wildcard expression. The JCR like expression uses '%' to match 0 or more
- * characters, '_' to match any single character, '\x' to match the 'x' character, and all other characters to match
- * themselves.
- *
- * @param likeExpression the like expression; may not be null
- * @return the expression that can be used with a WildcardQuery; never null
- */
- public String toWildcardExpression( String likeExpression ) {
- assert likeExpression != null;
- assert likeExpression.length() > 0;
- return likeExpression.replace('%', '*').replace('_', '?').replaceAll("\\\\(.)", "$1");
- }
-
- /**
- * Convert the JCR like expression to a regular expression. The JCR like expression uses '%' to match 0 or more characters,
- * '_' to match any single character, '\x' to match the 'x' character, and all other characters to match themselves. Note that
- * if any regex metacharacters appear in the like expression, they will be escaped within the resulting regular expression.
- *
- * @param likeExpression the like expression; may not be null
- * @return the expression that can be used with a WildcardQuery; never null
- */
- public String toRegularExpression( String likeExpression ) {
- assert likeExpression != null;
- assert likeExpression.length() > 0;
- // Replace all '\x' with 'x' ...
- String result = likeExpression.replaceAll("\\\\(.)", "$1");
- // Escape characters used as metacharacters in regular expressions, including
- // '[', '^', '\', '$', '.', '|', '?', '*', '+', '(', and ')'
- result = result.replaceAll("([[^\\\\$.|?*+()])", "\\$1");
- // Replace '%'->'[.]+' and '_'->'[.]
- result = likeExpression.replace("%", "[.]+").replace("_", "[.]");
- return result;
- }
-
public String pathAsString( Path path,
ValueFactory<String> stringFactory ) {
assert path != null;
if (path.isRoot()) return "/";
- String pathStr = stringFactory.create(path);
- if (!pathStr.endsWith("]")) {
- pathStr = pathStr + '[' + Path.DEFAULT_INDEX + ']';
+ StringBuilder sb = new StringBuilder();
+ for (Path.Segment segment : path) {
+ sb.append('/');
+ sb.append(stringFactory.create(segment.getName()));
+ sb.append('[');
+ sb.append(segment.getIndex());
+ sb.append(']');
}
- return pathStr;
+ return sb.toString();
}
+
+ public static abstract class TupleCollector extends Collector {
+
+ /**
+ * Get the tuples.
+ *
+ * @return the tuples; never null
+ */
+ public abstract LinkedList<Object[]> getTuples();
+ }
}
Modified: trunk/dna-search/src/main/java/org/jboss/dna/search/query/CompareQuery.java
===================================================================
--- trunk/dna-search/src/main/java/org/jboss/dna/search/query/CompareQuery.java 2009-11-24 17:43:50 UTC (rev 1338)
+++ trunk/dna-search/src/main/java/org/jboss/dna/search/query/CompareQuery.java 2009-11-24 17:44:29 UTC (rev 1339)
@@ -96,7 +96,7 @@
* @param fieldSelector the field selector that should load the fields needed to recover the value; may be null if the field
* selector should be generated automatically
*/
- protected CompareQuery( String fieldName,
+ protected CompareQuery( final String fieldName,
ValueType constraintValue,
ValueFactory<ValueType> valueTypeFactory,
ValueFactory<String> stringFactory,
@@ -114,7 +114,7 @@
private static final long serialVersionUID = 1L;
public FieldSelectorResult accept( String fieldName ) {
- return fieldName.equals(fieldName) ? FieldSelectorResult.LOAD_AND_BREAK : FieldSelectorResult.NO_LOAD;
+ return CompareQuery.this.fieldName.equals(fieldName) ? FieldSelectorResult.LOAD_AND_BREAK : FieldSelectorResult.NO_LOAD;
}
};
}
@@ -133,7 +133,7 @@
*/
@Override
public Weight createWeight( Searcher searcher ) {
- return new NotWeight(searcher);
+ return new CompareWeight(searcher);
}
/**
@@ -149,11 +149,11 @@
/**
* Calculates query weights and builds query scores for our NOT queries.
*/
- protected class NotWeight extends Weight {
+ protected class CompareWeight extends Weight {
private static final long serialVersionUID = 1L;
private final Searcher searcher;
- protected NotWeight( Searcher searcher ) {
+ protected CompareWeight( Searcher searcher ) {
this.searcher = searcher;
assert this.searcher != null;
}
@@ -217,7 +217,7 @@
boolean scoreDocsInOrder,
boolean topScorer ) {
// Return a custom scorer ...
- return new NotScorer(reader);
+ return new CompareScorer(reader);
}
/**
@@ -235,17 +235,17 @@
/**
* A scorer for the Path query.
*/
- protected class NotScorer extends Scorer {
+ protected class CompareScorer extends Scorer {
private int docId = -1;
private final int maxDocId;
private final IndexReader reader;
- protected NotScorer( IndexReader reader ) {
+ protected CompareScorer( IndexReader reader ) {
// We don't care which Similarity we have, because we don't use it. So get the default.
super(Similarity.getDefault());
this.reader = reader;
assert this.reader != null;
- this.maxDocId = this.reader.maxDoc();
+ this.maxDocId = this.reader.maxDoc() - 1;
}
/**
Modified: trunk/dna-search/src/main/java/org/jboss/dna/search/query/CompareStringQuery.java
===================================================================
--- trunk/dna-search/src/main/java/org/jboss/dna/search/query/CompareStringQuery.java 2009-11-24 17:43:50 UTC (rev 1338)
+++ trunk/dna-search/src/main/java/org/jboss/dna/search/query/CompareStringQuery.java 2009-11-24 17:44:29 UTC (rev 1339)
@@ -24,10 +24,16 @@
package org.jboss.dna.search.query;
import java.io.IOException;
+import java.util.regex.Pattern;
import org.apache.lucene.index.IndexReader;
+import org.apache.lucene.index.Term;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.Searcher;
+import org.apache.lucene.search.TermQuery;
import org.apache.lucene.search.Weight;
+import org.apache.lucene.search.WildcardQuery;
+import org.apache.lucene.search.regex.JavaUtilRegexCapabilities;
+import org.apache.lucene.search.regex.RegexQuery;
import org.jboss.dna.graph.property.ValueComparators;
import org.jboss.dna.graph.property.ValueFactories;
import org.jboss.dna.graph.property.ValueFactory;
@@ -42,6 +48,19 @@
public class CompareStringQuery extends CompareQuery<String> {
private static final long serialVersionUID = 1L;
+ protected static final Evaluator<String> EQUAL_TO = new Evaluator<String>() {
+ private static final long serialVersionUID = 1L;
+
+ public boolean satisfiesConstraint( String nodeValue,
+ String constraintValue ) {
+ return constraintValue.equals(nodeValue);
+ }
+
+ @Override
+ public String toString() {
+ return " = ";
+ }
+ };
protected static final Evaluator<String> IS_LESS_THAN = new Evaluator<String>() {
private static final long serialVersionUID = 1L;
@@ -96,6 +115,29 @@
};
/**
+ * Construct a {@link Query} implementation that scores documents with a string field value that is equal to the supplied
+ * constraint value.
+ *
+ * @param constraintValue the constraint value; may not be null
+ * @param fieldName the name of the document field containing the value; may not be null
+ * @param factories the value factories that can be used during the scoring; may not be null
+ * @param caseSensitive true if the comparison should be done in a case-sensitive manner, or false if it is to be
+ * case-insensitive
+ * @return the query; never null
+ */
+ public static Query createQueryForNodesWithFieldEqualTo( String constraintValue,
+ String fieldName,
+ ValueFactories factories,
+ boolean caseSensitive ) {
+ if (caseSensitive) {
+ // We can just do a normal TermQuery ...
+ return new TermQuery(new Term(fieldName, constraintValue));
+ }
+ return new CompareStringQuery(fieldName, constraintValue, factories.getStringFactory(), factories.getStringFactory(),
+ EQUAL_TO, caseSensitive);
+ }
+
+ /**
* Construct a {@link Query} implementation that scores documents with a string field value that is greater than the supplied
* constraint value.
*
@@ -171,6 +213,83 @@
IS_LESS_THAN_OR_EQUAL_TO, caseSensitive);
}
+ /**
+ * Construct a {@link Query} implementation that scores documents with a string field value that is LIKE the supplied
+ * constraint value.
+ *
+ * @param likeExpression the LIKE expression; may not be null
+ * @param fieldName the name of the document field containing the value; may not be null
+ * @param factories the value factories that can be used during the scoring; may not be null
+ * @param caseSensitive true if the comparison should be done in a case-sensitive manner, or false if it is to be
+ * case-insensitive
+ * @return the query; never null
+ */
+ public static Query createQueryForNodesWithFieldLike( String likeExpression,
+ String fieldName,
+ ValueFactories factories,
+ boolean caseSensitive ) {
+ assert likeExpression != null;
+ assert likeExpression.length() > 0;
+ if (likeExpression.indexOf('%') == -1 && likeExpression.indexOf('_') == -1) {
+ // This is not a like expression, so just do an equals ...
+ return createQueryForNodesWithFieldEqualTo(likeExpression, fieldName, factories, caseSensitive);
+ }
+ if (caseSensitive) {
+ // We can just do a normal Wildcard or RegEx query ...
+
+ // '%' matches 0 or more characters
+ // '_' matches any single character
+ // '\x' matches 'x'
+ // all other characters match themselves
+
+ // Wildcard queries are a better match, but they can be slow and should not be used
+ // if the first character of the expression is a '%' or '_' ...
+ char firstChar = likeExpression.charAt(0);
+ if (firstChar != '%' && firstChar != '_') {
+ // Create a wildcard query ...
+ String expression = toWildcardExpression(likeExpression);
+ return new WildcardQuery(new Term(fieldName, expression));
+ }
+ }
+ // Create a regex query (which will be done using the correct case) ...
+ String regex = toRegularExpression(likeExpression);
+ RegexQuery query = new RegexQuery(new Term(fieldName, regex));
+ int flags = caseSensitive ? 0 : Pattern.CASE_INSENSITIVE;
+ query.setRegexImplementation(new JavaUtilRegexCapabilities(flags));
+ return query;
+ }
+
+ /**
+ * Convert the JCR like expression to a Lucene wildcard expression. The JCR like expression uses '%' to match 0 or more
+ * characters, '_' to match any single character, '\x' to match the 'x' character, and all other characters to match
+ * themselves.
+ *
+ * @param likeExpression the like expression; may not be null
+ * @return the expression that can be used with a WildcardQuery; never null
+ */
+ protected static String toWildcardExpression( String likeExpression ) {
+ return likeExpression.replace('%', '*').replace('_', '?').replaceAll("\\\\(.)", "$1");
+ }
+
+ /**
+ * Convert the JCR like expression to a regular expression. The JCR like expression uses '%' to match 0 or more characters,
+ * '_' to match any single character, '\x' to match the 'x' character, and all other characters to match themselves. Note that
+ * if any regex metacharacters appear in the like expression, they will be escaped within the resulting regular expression.
+ *
+ * @param likeExpression the like expression; may not be null
+ * @return the expression that can be used with a WildcardQuery; never null
+ */
+ protected static String toRegularExpression( String likeExpression ) {
+ // Replace all '\x' with 'x' ...
+ String result = likeExpression.replaceAll("\\\\(.)", "$1");
+ // Escape characters used as metacharacters in regular expressions, including
+ // '[', '^', '\', '$', '.', '|', '?', '*', '+', '(', and ')'
+ result = result.replaceAll("([\\[^\\\\$.|?*+()])", "\\$1");
+ // Replace '%'->'[.]+' and '_'->'[.]
+ result = likeExpression.replace("%", ".+").replace("_", ".");
+ return result;
+ }
+
private final boolean caseSensitive;
/**
@@ -204,6 +323,7 @@
protected String readFromDocument( IndexReader reader,
int docId ) throws IOException {
String result = super.readFromDocument(reader, docId);
+ if (result == null) return null;
return caseSensitive ? result : result.toLowerCase();
}
Copied: trunk/dna-search/src/main/java/org/jboss/dna/search/query/IdsQuery.java (from rev 1338, trunk/dna-search/src/main/java/org/jboss/dna/search/query/UuidsQuery.java)
===================================================================
--- trunk/dna-search/src/main/java/org/jboss/dna/search/query/IdsQuery.java (rev 0)
+++ trunk/dna-search/src/main/java/org/jboss/dna/search/query/IdsQuery.java 2009-11-24 17:44:29 UTC (rev 1339)
@@ -0,0 +1,261 @@
+/*
+ * JBoss DNA (http://www.jboss.org/dna)
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ * See the AUTHORS.txt file in the distribution for a full listing of
+ * individual contributors.
+ *
+ * JBoss DNA is free software. Unless otherwise indicated, all code in JBoss DNA
+ * is licensed to you under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation; either version 2.1 of
+ * the License, or (at your option) any later version.
+ *
+ * JBoss DNA is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this software; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+ */
+package org.jboss.dna.search.query;
+
+import java.io.IOException;
+import java.util.Set;
+import org.apache.lucene.document.Document;
+import org.apache.lucene.document.FieldSelector;
+import org.apache.lucene.document.FieldSelectorResult;
+import org.apache.lucene.index.IndexReader;
+import org.apache.lucene.search.Explanation;
+import org.apache.lucene.search.Query;
+import org.apache.lucene.search.Scorer;
+import org.apache.lucene.search.Searcher;
+import org.apache.lucene.search.Similarity;
+import org.apache.lucene.search.Weight;
+
+/**
+ * A Lucene {@link Query} implementation that is used to score positively those documents that have a ID in the supplied set. This
+ * works for large sets of IDs; in smaller numbers, it may be more efficient to create a boolean query that checks for each of the
+ * IDs.
+ */
+public class IdsQuery extends Query {
+
+ private static final long serialVersionUID = 1L;
+
+ /**
+ * The operand that is being negated by this query.
+ */
+ protected final Set<String> uuids;
+ protected final FieldSelector fieldSelector;
+ protected final String fieldName;
+
+ /**
+ * Construct a {@link Query} implementation that scores nodes according to the supplied comparator.
+ *
+ * @param fieldName the name of the document field containing the value; may not be null
+ * @param ids the set of ID values; may not be null
+ */
+ public IdsQuery( String fieldName,
+ Set<String> ids ) {
+ this.fieldName = fieldName;
+ this.uuids = ids;
+ assert this.fieldName != null;
+ assert this.uuids != null;
+ this.fieldSelector = new FieldSelector() {
+ private static final long serialVersionUID = 1L;
+
+ public FieldSelectorResult accept( String fieldName ) {
+ return fieldName.equals(fieldName) ? FieldSelectorResult.LOAD_AND_BREAK : FieldSelectorResult.NO_LOAD;
+ }
+ };
+ }
+
+ protected boolean includeDocument( IndexReader reader,
+ int docId ) throws IOException {
+ Document doc = reader.document(docId, fieldSelector);
+ String valueString = doc.get(fieldName);
+ return uuids.contains(valueString);
+ }
+
+ /**
+ * {@inheritDoc}
+ *
+ * @see org.apache.lucene.search.Query#createWeight(org.apache.lucene.search.Searcher)
+ */
+ @Override
+ public Weight createWeight( Searcher searcher ) {
+ return new IdSetWeight(searcher);
+ }
+
+ /**
+ * {@inheritDoc}
+ *
+ * @see org.apache.lucene.search.Query#toString(java.lang.String)
+ */
+ @Override
+ public String toString( String field ) {
+ return fieldName + " IN UUIDs";
+ }
+
+ /**
+ * Calculates query weights and builds query scores for our NOT queries.
+ */
+ protected class IdSetWeight extends Weight {
+ private static final long serialVersionUID = 1L;
+ private final Searcher searcher;
+
+ protected IdSetWeight( Searcher searcher ) {
+ this.searcher = searcher;
+ assert this.searcher != null;
+ }
+
+ /**
+ * {@inheritDoc}
+ *
+ * @see org.apache.lucene.search.Weight#getQuery()
+ */
+ @Override
+ public Query getQuery() {
+ return IdsQuery.this;
+ }
+
+ /**
+ * {@inheritDoc}
+ * <p>
+ * This implementation always returns a weight factor of 1.0.
+ * </p>
+ *
+ * @see org.apache.lucene.search.Weight#getValue()
+ */
+ @Override
+ public float getValue() {
+ return 1.0f; // weight factor of 1.0
+ }
+
+ /**
+ * {@inheritDoc}
+ * <p>
+ * This implementation always returns a normalization factor of 1.0.
+ * </p>
+ *
+ * @see org.apache.lucene.search.Weight#sumOfSquaredWeights()
+ */
+ @Override
+ public float sumOfSquaredWeights() {
+ return 1.0f; // normalization factor of 1.0
+ }
+
+ /**
+ * {@inheritDoc}
+ * <p>
+ * This implementation always does nothing, as there is nothing to normalize.
+ * </p>
+ *
+ * @see org.apache.lucene.search.Weight#normalize(float)
+ */
+ @Override
+ public void normalize( float norm ) {
+ // No need to do anything here
+ }
+
+ /**
+ * {@inheritDoc}
+ *
+ * @see org.apache.lucene.search.Weight#scorer(org.apache.lucene.index.IndexReader, boolean, boolean)
+ */
+ @Override
+ public Scorer scorer( IndexReader reader,
+ boolean scoreDocsInOrder,
+ boolean topScorer ) {
+ // Return a custom scorer ...
+ return new IdScorer(reader);
+ }
+
+ /**
+ * {@inheritDoc}
+ *
+ * @see org.apache.lucene.search.Weight#explain(org.apache.lucene.index.IndexReader, int)
+ */
+ @Override
+ public Explanation explain( IndexReader reader,
+ int doc ) {
+ return new Explanation(getValue(), getQuery().toString());
+ }
+ }
+
+ /**
+ * A scorer for the Path query.
+ */
+ protected class IdScorer extends Scorer {
+ private int docId = -1;
+ private final int maxDocId;
+ private final IndexReader reader;
+
+ protected IdScorer( IndexReader reader ) {
+ // We don't care which Similarity we have, because we don't use it. So get the default.
+ super(Similarity.getDefault());
+ this.reader = reader;
+ assert this.reader != null;
+ this.maxDocId = this.reader.maxDoc();
+ }
+
+ /**
+ * {@inheritDoc}
+ *
+ * @see org.apache.lucene.search.DocIdSetIterator#docID()
+ */
+ @Override
+ public int docID() {
+ return docId;
+ }
+
+ /**
+ * {@inheritDoc}
+ *
+ * @see org.apache.lucene.search.DocIdSetIterator#nextDoc()
+ */
+ @Override
+ public int nextDoc() throws IOException {
+ do {
+ ++docId;
+ if (reader.isDeleted(docId)) {
+ // We should skip this document ...
+ continue;
+ }
+ if (includeDocument(reader, docId)) return docId;
+ } while (docId < maxDocId);
+ return Scorer.NO_MORE_DOCS;
+ }
+
+ /**
+ * {@inheritDoc}
+ *
+ * @see org.apache.lucene.search.DocIdSetIterator#advance(int)
+ */
+ @Override
+ public int advance( int target ) throws IOException {
+ if (target == Scorer.NO_MORE_DOCS) return target;
+ while (true) {
+ int doc = nextDoc();
+ if (doc >= target) return doc;
+ }
+ }
+
+ /**
+ * {@inheritDoc}
+ * <p>
+ * This method always returns a score of 1.0 for the current document, since only those documents that satisfy the NOT are
+ * scored by this scorer.
+ * </p>
+ *
+ * @see org.apache.lucene.search.Scorer#score()
+ */
+ @Override
+ public float score() {
+ return 1.0f;
+ }
+ }
+}
Property changes on: trunk/dna-search/src/main/java/org/jboss/dna/search/query/IdsQuery.java
___________________________________________________________________
Name: svn:keywords
+ Id Revision
Name: svn:eol-style
+ LF
Deleted: trunk/dna-search/src/main/java/org/jboss/dna/search/query/UuidsQuery.java
===================================================================
--- trunk/dna-search/src/main/java/org/jboss/dna/search/query/UuidsQuery.java 2009-11-24 17:43:50 UTC (rev 1338)
+++ trunk/dna-search/src/main/java/org/jboss/dna/search/query/UuidsQuery.java 2009-11-24 17:44:29 UTC (rev 1339)
@@ -1,268 +0,0 @@
-/*
- * JBoss DNA (http://www.jboss.org/dna)
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership. Some portions may be licensed
- * to Red Hat, Inc. under one or more contributor license agreements.
- * See the AUTHORS.txt file in the distribution for a full listing of
- * individual contributors.
- *
- * JBoss DNA is free software. Unless otherwise indicated, all code in JBoss DNA
- * is licensed to you under the terms of the GNU Lesser General Public License as
- * published by the Free Software Foundation; either version 2.1 of
- * the License, or (at your option) any later version.
- *
- * JBoss DNA is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with this software; if not, write to the Free
- * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
- * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
- */
-package org.jboss.dna.search.query;
-
-import java.io.IOException;
-import java.util.Set;
-import java.util.UUID;
-import org.apache.lucene.document.Document;
-import org.apache.lucene.document.FieldSelector;
-import org.apache.lucene.document.FieldSelectorResult;
-import org.apache.lucene.index.IndexReader;
-import org.apache.lucene.search.Explanation;
-import org.apache.lucene.search.Query;
-import org.apache.lucene.search.Scorer;
-import org.apache.lucene.search.Searcher;
-import org.apache.lucene.search.Similarity;
-import org.apache.lucene.search.Weight;
-import org.jboss.dna.graph.property.ValueFactory;
-
-/**
- * A Lucene {@link Query} implementation that is used to score positively those documents that have a UUID in the supplied set.
- * This works for large sets of UUIDs; in smaller numbers, it may be more efficient to create a boolean query that checks for each
- * fo the UUIDs.
- */
-public class UuidsQuery extends Query {
-
- private static final long serialVersionUID = 1L;
-
- /**
- * The operand that is being negated by this query.
- */
- protected final Set<UUID> uuids;
- protected final FieldSelector fieldSelector;
- protected final String fieldName;
- protected final ValueFactory<UUID> uuidFactory;
-
- /**
- * Construct a {@link Query} implementation that scores nodes according to the supplied comparator.
- *
- * @param fieldName the name of the document field containing the value; may not be null
- * @param uuids the set of UUID values; may not be null
- * @param uuidFactory the factory to create UUID values; may not be null
- */
- public UuidsQuery( String fieldName,
- Set<UUID> uuids,
- ValueFactory<UUID> uuidFactory ) {
- this.fieldName = fieldName;
- this.uuids = uuids;
- this.uuidFactory = uuidFactory;
- assert this.fieldName != null;
- assert this.uuids != null;
- assert this.uuidFactory != null;
- this.fieldSelector = new FieldSelector() {
- private static final long serialVersionUID = 1L;
-
- public FieldSelectorResult accept( String fieldName ) {
- return fieldName.equals(fieldName) ? FieldSelectorResult.LOAD_AND_BREAK : FieldSelectorResult.NO_LOAD;
- }
- };
- }
-
- protected boolean includeDocument( IndexReader reader,
- int docId ) throws IOException {
- Document doc = reader.document(docId, fieldSelector);
- String valueString = doc.get(fieldName);
- return uuids.contains(uuidFactory.create(valueString));
- }
-
- /**
- * {@inheritDoc}
- *
- * @see org.apache.lucene.search.Query#createWeight(org.apache.lucene.search.Searcher)
- */
- @Override
- public Weight createWeight( Searcher searcher ) {
- return new UuidSetWeight(searcher);
- }
-
- /**
- * {@inheritDoc}
- *
- * @see org.apache.lucene.search.Query#toString(java.lang.String)
- */
- @Override
- public String toString( String field ) {
- return fieldName + " IN UUIDs";
- }
-
- /**
- * Calculates query weights and builds query scores for our NOT queries.
- */
- protected class UuidSetWeight extends Weight {
- private static final long serialVersionUID = 1L;
- private final Searcher searcher;
-
- protected UuidSetWeight( Searcher searcher ) {
- this.searcher = searcher;
- assert this.searcher != null;
- }
-
- /**
- * {@inheritDoc}
- *
- * @see org.apache.lucene.search.Weight#getQuery()
- */
- @Override
- public Query getQuery() {
- return UuidsQuery.this;
- }
-
- /**
- * {@inheritDoc}
- * <p>
- * This implementation always returns a weight factor of 1.0.
- * </p>
- *
- * @see org.apache.lucene.search.Weight#getValue()
- */
- @Override
- public float getValue() {
- return 1.0f; // weight factor of 1.0
- }
-
- /**
- * {@inheritDoc}
- * <p>
- * This implementation always returns a normalization factor of 1.0.
- * </p>
- *
- * @see org.apache.lucene.search.Weight#sumOfSquaredWeights()
- */
- @Override
- public float sumOfSquaredWeights() {
- return 1.0f; // normalization factor of 1.0
- }
-
- /**
- * {@inheritDoc}
- * <p>
- * This implementation always does nothing, as there is nothing to normalize.
- * </p>
- *
- * @see org.apache.lucene.search.Weight#normalize(float)
- */
- @Override
- public void normalize( float norm ) {
- // No need to do anything here
- }
-
- /**
- * {@inheritDoc}
- *
- * @see org.apache.lucene.search.Weight#scorer(org.apache.lucene.index.IndexReader, boolean, boolean)
- */
- @Override
- public Scorer scorer( IndexReader reader,
- boolean scoreDocsInOrder,
- boolean topScorer ) {
- // Return a custom scorer ...
- return new UuidScorer(reader);
- }
-
- /**
- * {@inheritDoc}
- *
- * @see org.apache.lucene.search.Weight#explain(org.apache.lucene.index.IndexReader, int)
- */
- @Override
- public Explanation explain( IndexReader reader,
- int doc ) {
- return new Explanation(getValue(), getQuery().toString());
- }
- }
-
- /**
- * A scorer for the Path query.
- */
- protected class UuidScorer extends Scorer {
- private int docId = -1;
- private final int maxDocId;
- private final IndexReader reader;
-
- protected UuidScorer( IndexReader reader ) {
- // We don't care which Similarity we have, because we don't use it. So get the default.
- super(Similarity.getDefault());
- this.reader = reader;
- assert this.reader != null;
- this.maxDocId = this.reader.maxDoc();
- }
-
- /**
- * {@inheritDoc}
- *
- * @see org.apache.lucene.search.DocIdSetIterator#docID()
- */
- @Override
- public int docID() {
- return docId;
- }
-
- /**
- * {@inheritDoc}
- *
- * @see org.apache.lucene.search.DocIdSetIterator#nextDoc()
- */
- @Override
- public int nextDoc() throws IOException {
- do {
- ++docId;
- if (reader.isDeleted(docId)) {
- // We should skip this document ...
- continue;
- }
- if (includeDocument(reader, docId)) return docId;
- } while (docId < maxDocId);
- return Scorer.NO_MORE_DOCS;
- }
-
- /**
- * {@inheritDoc}
- *
- * @see org.apache.lucene.search.DocIdSetIterator#advance(int)
- */
- @Override
- public int advance( int target ) throws IOException {
- if (target == Scorer.NO_MORE_DOCS) return target;
- while (true) {
- int doc = nextDoc();
- if (doc >= target) return doc;
- }
- }
-
- /**
- * {@inheritDoc}
- * <p>
- * This method always returns a score of 1.0 for the current document, since only those documents that satisfy the NOT are
- * scored by this scorer.
- * </p>
- *
- * @see org.apache.lucene.search.Scorer#score()
- */
- @Override
- public float score() {
- return 1.0f;
- }
- }
-}
Modified: trunk/dna-search/src/test/java/org/jboss/dna/search/SearchEngineTest.java
===================================================================
--- trunk/dna-search/src/test/java/org/jboss/dna/search/SearchEngineTest.java 2009-11-24 17:43:50 UTC (rev 1338)
+++ trunk/dna-search/src/test/java/org/jboss/dna/search/SearchEngineTest.java 2009-11-24 17:44:29 UTC (rev 1339)
@@ -26,6 +26,7 @@
import static org.hamcrest.core.Is.is;
import static org.hamcrest.core.IsNull.notNullValue;
import static org.junit.Assert.assertThat;
+import static org.junit.Assert.fail;
import java.io.IOException;
import java.util.List;
import org.jboss.dna.graph.ExecutionContext;
@@ -35,10 +36,18 @@
import org.jboss.dna.graph.connector.RepositoryConnectionFactory;
import org.jboss.dna.graph.connector.RepositorySourceException;
import org.jboss.dna.graph.connector.inmemory.InMemoryRepositorySource;
+import org.jboss.dna.graph.property.Name;
import org.jboss.dna.graph.property.Path;
+import org.jboss.dna.graph.query.QueryResults;
+import org.jboss.dna.graph.query.model.QueryCommand;
+import org.jboss.dna.graph.query.parse.SqlQueryParser;
+import org.jboss.dna.graph.query.validate.ImmutableSchemata;
+import org.jboss.dna.graph.query.validate.Schemata;
+import org.jboss.dna.graph.query.validate.ImmutableSchemata.Builder;
import org.jboss.dna.graph.search.SearchEngine;
import org.jboss.dna.graph.search.SearchProvider;
import org.junit.Before;
+import org.junit.Ignore;
import org.junit.Test;
import org.xml.sax.SAXException;
@@ -53,6 +62,8 @@
private InMemoryRepositorySource source;
private RepositoryConnectionFactory connectionFactory;
private Graph content;
+ private Schemata schemata;
+ private SqlQueryParser sql;
@Before
public void beforeEach() throws Exception {
@@ -79,14 +90,32 @@
};
// Set up the provider and the search engine ...
- IndexRules rules = DualIndexSearchProvider.DEFAULT_RULES;
+ IndexRules.Builder rulesBuilder = IndexRules.createBuilder(DualIndexSearchProvider.DEFAULT_RULES);
+ // rulesBuilder.analyzeAndStoreAndFullText(name("maker"));
+ IndexRules rules = rulesBuilder.build();
LuceneConfiguration luceneConfig = LuceneConfigurations.inMemory();
// LuceneConfiguration luceneConfig = LuceneConfigurations.using(new File("target/testIndexes"));
provider = new DualIndexSearchProvider(luceneConfig, rules);
engine = new SearchEngine(context, sourceName, connectionFactory, provider);
loadContent();
+
+ // Create the schemata for the workspaces ...
+ Builder builder = ImmutableSchemata.createBuilder(context);
+ builder.addTable("__ALLNODES__", "maker", "model", "year");
+ schemata = builder.build();
+ schemata = ImmutableSchemata.createBuilder(context)
+ .addTable("__ALLNODES__", "maker", "model", "year", "msrp")
+ .makeSearchable("__ALLNODES__", "maker")
+ .build();
+
+ // And create the SQL parser ...
+ sql = new SqlQueryParser();
}
+ protected Name name( String name ) {
+ return context.getValueFactories().getNameFactory().create(name);
+ }
+
protected Path path( String path ) {
return context.getValueFactories().getPathFactory().create(path);
}
@@ -167,6 +196,10 @@
engine.index(workspaceName1, path("/Cars"), 10);
}
+ // ----------------------------------------------------------------------------------------------------------------
+ // Full-text search
+ // ----------------------------------------------------------------------------------------------------------------
+
@Test
public void shouldFindNodesByFullTextSearch() {
engine.index(workspaceName1, path("/"), 100);
@@ -190,4 +223,188 @@
assertThat(results.size(), is(1));
assertThat(results.get(0).getPath(), is(path("/Cars/Hybrid/Toyota Highlander")));
}
+
+ @Test
+ public void shouldFindNodesBySimpleXpathQuery() {
+ engine.index(workspaceName1, path("/"), 100);
+ QueryCommand query = sql.parseQuery("SELECT model, maker FROM __ALLNODES__", context);
+ QueryResults results = engine.query(context, workspaceName1, query, schemata);
+ assertThat(results, is(notNullValue()));
+ assertThat(results.getRowCount(), is(18));
+ System.out.println(results);
+ }
+
+ // ----------------------------------------------------------------------------------------------------------------
+ // Query
+ // ----------------------------------------------------------------------------------------------------------------
+
+ @Test
+ public void shouldFindNodesBySimpleQuery() {
+ engine.index(workspaceName1, path("/"), 100);
+ QueryCommand query = sql.parseQuery("SELECT model, maker FROM __ALLNODES__", context);
+ QueryResults results = engine.query(context, workspaceName1, query, schemata);
+ assertThat(results, is(notNullValue()));
+ assertThat(results.getRowCount(), is(18));
+ System.out.println(results);
+ }
+
+ @Test
+ public void shouldFindNodesBySimpleQueryWithEqualityComparisonCriteria() {
+ engine.index(workspaceName1, path("/"), 100);
+ QueryCommand query = sql.parseQuery("SELECT model, maker FROM __ALLNODES__ WHERE maker = 'Toyota'", context);
+ QueryResults results = engine.query(context, workspaceName1, query, schemata);
+ assertThat(results, is(notNullValue()));
+ assertThat(results.getRowCount(), is(2));
+ System.out.println(results);
+ }
+
+ @Ignore
+ @Test
+ public void shouldFindNodesBySimpleQueryWithGreaterThanComparisonCriteria() {
+ engine.index(workspaceName1, path("/"), 100);
+ QueryCommand query = sql.parseQuery("SELECT model, maker FROM __ALLNODES__ WHERE mpgHighway > 20", context);
+ QueryResults results = engine.query(context, workspaceName1, query, schemata);
+ assertThat(results, is(notNullValue()));
+ assertThat(results.getRowCount(), is(2));
+ System.out.println(results);
+ }
+
+ @Test
+ public void shouldFindNodesBySimpleQueryWithLowercaseEqualityComparisonCriteria() {
+ engine.index(workspaceName1, path("/"), 100);
+ QueryCommand query = sql.parseQuery("SELECT model, maker FROM __ALLNODES__ WHERE LOWER(maker) = 'toyota'", context);
+ QueryResults results = engine.query(context, workspaceName1, query, schemata);
+ assertThat(results, is(notNullValue()));
+ assertThat(results.getRowCount(), is(2));
+ System.out.println(results);
+ }
+
+ @Test
+ public void shouldFindNodesBySimpleQueryWithUppercaseEqualityComparisonCriteria() {
+ engine.index(workspaceName1, path("/"), 100);
+ QueryCommand query = sql.parseQuery("SELECT model, maker FROM __ALLNODES__ WHERE UPPER(maker) = 'TOYOTA'", context);
+ QueryResults results = engine.query(context, workspaceName1, query, schemata);
+ assertThat(results, is(notNullValue()));
+ assertThat(results.getRowCount(), is(2));
+ System.out.println(results);
+ }
+
+ @Test
+ public void shouldFindNodesBySimpleQueryWithLikeComparisonCriteria() {
+ engine.index(workspaceName1, path("/"), 100);
+ QueryCommand query = sql.parseQuery("SELECT model, maker FROM __ALLNODES__ WHERE maker LIKE 'Toyo%'", context);
+ QueryResults results = engine.query(context, workspaceName1, query, schemata);
+ assertThat(results, is(notNullValue()));
+ assertThat(results.getRowCount(), is(2));
+ System.out.println(results);
+ }
+
+ @Test
+ public void shouldFindNodesBySimpleQueryWithLikeComparisonCriteriaWithLeadingWildcard() {
+ engine.index(workspaceName1, path("/"), 100);
+ QueryCommand query = sql.parseQuery("SELECT model, maker FROM __ALLNODES__ WHERE maker LIKE '%yota'", context);
+ QueryResults results = engine.query(context, workspaceName1, query, schemata);
+ assertThat(results, is(notNullValue()));
+ assertThat(results.getRowCount(), is(2));
+ System.out.println(results);
+ }
+
+ @Test
+ public void shouldFindNodesBySimpleQueryWithLowercaseLikeComparisonCriteria() {
+ engine.index(workspaceName1, path("/"), 100);
+ QueryCommand query = sql.parseQuery("SELECT model, maker FROM __ALLNODES__ WHERE LOWER(maker) LIKE 'toyo%'", context);
+ QueryResults results = engine.query(context, workspaceName1, query, schemata);
+ assertThat(results, is(notNullValue()));
+ assertThat(results.getRowCount(), is(2));
+ System.out.println(results);
+ }
+
+ @Test
+ public void shouldFindNodesBySimpleQueryWithFullTextSearchCriteria() {
+ engine.index(workspaceName1, path("/"), 100);
+ QueryCommand query = sql.parseQuery("SELECT model, maker FROM __ALLNODES__ WHERE CONTAINS(maker,'martin')", context);
+ QueryResults results = engine.query(context, workspaceName1, query, schemata);
+ assertNoErrors(results);
+ assertThat(results, is(notNullValue()));
+ assertThat(results.getRowCount(), is(1));
+ System.out.println(results);
+ }
+
+ @Test
+ public void shouldFindNodesBySimpleQueryWithDepthCriteria() {
+ engine.index(workspaceName1, path("/"), 100);
+ QueryCommand query = sql.parseQuery("SELECT model, maker FROM __ALLNODES__ WHERE DEPTH() > 2", context);
+ QueryResults results = engine.query(context, workspaceName1, query, schemata);
+ assertNoErrors(results);
+ assertThat(results, is(notNullValue()));
+ assertThat(results.getRowCount(), is(12));
+ System.out.println(results);
+ }
+
+ @Test
+ public void shouldFindNodesBySimpleQueryWithLocalNameCriteria() {
+ engine.index(workspaceName1, path("/"), 100);
+ QueryCommand query = sql.parseQuery("SELECT model, maker FROM __ALLNODES__ WHERE LOCALNAME() LIKE 'Toyota%' OR LOCALNAME() LIKE 'Land %'",
+ context);
+ QueryResults results = engine.query(context, workspaceName1, query, schemata);
+ assertNoErrors(results);
+ assertThat(results, is(notNullValue()));
+ assertThat(results.getRowCount(), is(4));
+ System.out.println(results);
+ }
+
+ @Test
+ public void shouldFindNodesBySimpleQueryWithNameCriteria() {
+ engine.index(workspaceName1, path("/"), 100);
+ QueryCommand query = sql.parseQuery("SELECT model, maker FROM __ALLNODES__ WHERE NAME() LIKE 'Toyota%[1]' OR NAME() LIKE 'Land %'",
+ context);
+ QueryResults results = engine.query(context, workspaceName1, query, schemata);
+ assertNoErrors(results);
+ assertThat(results, is(notNullValue()));
+ assertThat(results.getRowCount(), is(4));
+ System.out.println(results);
+ }
+
+ @Test
+ public void shouldFindNodesBySimpleQueryWithNameCriteriaThatMatchesNoNodes() {
+ engine.index(workspaceName1, path("/"), 100);
+ QueryCommand query = sql.parseQuery("SELECT model, maker FROM __ALLNODES__ WHERE NAME() LIKE 'Toyota%[2]'", context);
+ QueryResults results = engine.query(context, workspaceName1, query, schemata);
+ assertNoErrors(results);
+ assertThat(results, is(notNullValue()));
+ assertThat(results.getRowCount(), is(0));
+ System.out.println(results);
+ }
+
+ @Test
+ public void shouldFindNodesBySimpleQueryWithPathCriteria() {
+ engine.index(workspaceName1, path("/"), 100);
+ QueryCommand query = sql.parseQuery("SELECT model, maker FROM __ALLNODES__ WHERE PATH() LIKE '/Cars[%]/Hy%/Toyota%' OR PATH() LIKE '/Cars[1]/Utility[1]/%'",
+ context);
+ QueryResults results = engine.query(context, workspaceName1, query, schemata);
+ assertNoErrors(results);
+ assertThat(results, is(notNullValue()));
+ assertThat(results.getRowCount(), is(6));
+ System.out.println(results);
+ }
+
+ @Test
+ public void shouldFindNodesBySimpleQueryWithDescendantCriteria() {
+ engine.index(workspaceName1, path("/"), 100);
+ QueryCommand query = sql.parseQuery("SELECT model, maker FROM __ALLNODES__ WHERE ISDESCENDANTNODE('/Cars/Hybrid')",
+ context);
+ QueryResults results = engine.query(context, workspaceName1, query, schemata);
+ assertNoErrors(results);
+ assertThat(results, is(notNullValue()));
+ assertThat(results.getRowCount(), is(3));
+ System.out.println(results);
+ }
+
+ protected void assertNoErrors( QueryResults results ) {
+ if (results.getProblems().hasErrors()) {
+ fail("Found errors: " + results.getProblems());
+ }
+ assertThat(results.getProblems().hasErrors(), is(false));
+ }
+
}
14 years, 5 months
DNA SVN: r1338 - trunk/dna-search/src/main/java/org/jboss/dna/search.
by dna-commits@lists.jboss.org
Author: rhauch
Date: 2009-11-24 12:43:50 -0500 (Tue, 24 Nov 2009)
New Revision: 1338
Modified:
trunk/dna-search/src/main/java/org/jboss/dna/search/DualIndexSearchProvider.java
Log:
DNA-467 Removed use of a method that was deprecated in 2.9 (or maybe 2.9.1)
Modified: trunk/dna-search/src/main/java/org/jboss/dna/search/DualIndexSearchProvider.java
===================================================================
--- trunk/dna-search/src/main/java/org/jboss/dna/search/DualIndexSearchProvider.java 2009-11-24 17:43:33 UTC (rev 1337)
+++ trunk/dna-search/src/main/java/org/jboss/dna/search/DualIndexSearchProvider.java 2009-11-24 17:43:50 UTC (rev 1338)
@@ -539,7 +539,7 @@
try {
// Parse the full-text search and search against the 'fts' field ...
- QueryParser parser = new QueryParser(ContentIndex.FULL_TEXT, createAnalyzer());
+ QueryParser parser = new QueryParser(Version.LUCENE_29, ContentIndex.FULL_TEXT, createAnalyzer());
Query query = parser.parse(fullTextString);
TopDocs docs = getContentSearcher().search(query, maxResults + offset);
14 years, 5 months
DNA SVN: r1337 - in trunk/dna-search: src/main/java/org/jboss/dna/search and 1 other directories.
by dna-commits@lists.jboss.org
Author: rhauch
Date: 2009-11-24 12:43:33 -0500 (Tue, 24 Nov 2009)
New Revision: 1337
Added:
trunk/dna-search/src/test/java/org/jboss/dna/search/SearchEngineTest.java
Modified:
trunk/dna-search/pom.xml
trunk/dna-search/src/main/java/org/jboss/dna/search/DualIndexSearchProvider.java
Log:
DNA-467 Changed the implementation of the method to delete nodes under a specified branch, and added several test cases to verify that the content can be indexed, re-indexed (multiple times), and searched.
Modified: trunk/dna-search/pom.xml
===================================================================
--- trunk/dna-search/pom.xml 2009-11-24 02:19:50 UTC (rev 1336)
+++ trunk/dna-search/pom.xml 2009-11-24 17:43:33 UTC (rev 1337)
@@ -45,22 +45,22 @@
<dependency>
<groupId>org.apache.lucene</groupId>
<artifactId>lucene-core</artifactId>
- <version>2.9.0</version>
+ <version>2.9.1</version>
</dependency>
<dependency>
<groupId>org.apache.lucene</groupId>
<artifactId>lucene-analyzers</artifactId>
- <version>2.9.0</version>
+ <version>2.9.1</version>
</dependency>
<dependency>
<groupId>org.apache.lucene</groupId>
<artifactId>lucene-snowball</artifactId>
- <version>2.9.0</version>
+ <version>2.9.1</version>
</dependency>
<dependency>
<groupId>org.apache.lucene</groupId>
<artifactId>lucene-regex</artifactId>
- <version>2.9.0</version>
+ <version>2.9.1</version>
</dependency>
<!--
Testing (note the scope)
Modified: trunk/dna-search/src/main/java/org/jboss/dna/search/DualIndexSearchProvider.java
===================================================================
--- trunk/dna-search/src/main/java/org/jboss/dna/search/DualIndexSearchProvider.java 2009-11-24 02:19:50 UTC (rev 1336)
+++ trunk/dna-search/src/main/java/org/jboss/dna/search/DualIndexSearchProvider.java 2009-11-24 17:43:33 UTC (rev 1337)
@@ -134,7 +134,7 @@
static {
IndexRules.Builder builder = IndexRules.createBuilder();
// Configure the default behavior ...
- builder.defaultTo(IndexRules.INDEX | IndexRules.ANALYZE);
+ builder.defaultTo(IndexRules.INDEX | IndexRules.ANALYZE | IndexRules.FULL_TEXT);
// Configure the UUID properties to be just indexed (not stored, not analyzed, not included in full-text) ...
builder.store(JcrLexicon.UUID, DnaLexicon.UUID);
// Configure the properties that we'll treat as dates ...
@@ -324,7 +324,13 @@
protected IndexWriter getPathsWriter() throws IOException {
assert !readOnly;
if (pathsWriter == null) {
- pathsWriter = new IndexWriter(pathsIndexDirectory, analyzer, overwrite, MaxFieldLength.UNLIMITED);
+ if (overwrite) {
+ // Always overwrite it ...
+ pathsWriter = new IndexWriter(pathsIndexDirectory, analyzer, overwrite, MaxFieldLength.UNLIMITED);
+ } else {
+ // Don't overwrite, but create if missing ...
+ pathsWriter = new IndexWriter(pathsIndexDirectory, analyzer, MaxFieldLength.UNLIMITED);
+ }
}
return pathsWriter;
}
@@ -332,7 +338,13 @@
protected IndexWriter getContentWriter() throws IOException {
assert !readOnly;
if (contentWriter == null) {
- contentWriter = new IndexWriter(contentIndexDirectory, analyzer, overwrite, MaxFieldLength.UNLIMITED);
+ if (overwrite) {
+ // Always overwrite it ...
+ contentWriter = new IndexWriter(contentIndexDirectory, analyzer, overwrite, MaxFieldLength.UNLIMITED);
+ } else {
+ // Don't overwrite, but create if missing ...
+ contentWriter = new IndexWriter(contentIndexDirectory, analyzer, MaxFieldLength.UNLIMITED);
+ }
}
return contentWriter;
}
@@ -492,33 +504,14 @@
*/
public int deleteBelow( Path path ) {
assert !readOnly;
- // Perform a query using the reader to find those nodes at/below the path ...
try {
- IndexReader pathReader = getPathsReader();
- IndexSearcher pathSearcher = new IndexSearcher(pathReader);
- String pathStr = stringFactory.create(path) + "/";
- PrefixQuery query = new PrefixQuery(new Term(PathIndex.PATH, pathStr));
- int numberDeleted = 0;
- while (true) {
- // Execute the query and get the results ...
- TopDocs results = pathSearcher.search(query, SIZE_OF_DELETE_BATCHES);
- int numResultsInBatch = results.scoreDocs.length;
- // Walk the results, delete the doc, and add to the query that we'll use against the content index ...
- IndexReader contentReader = getContentReader();
- for (ScoreDoc result : results.scoreDocs) {
- int docId = result.doc;
- // Find the UUID of the node ...
- Document doc = pathReader.document(docId, UUID_FIELD_SELECTOR);
- String uuid = doc.get(PathIndex.UUID);
- // Delete the document from the paths index ...
- pathReader.deleteDocument(docId);
- // Delete the corresponding document from the content index ...
- contentReader.deleteDocuments(new Term(ContentIndex.UUID, uuid));
- }
- numberDeleted += numResultsInBatch;
- if (numResultsInBatch < SIZE_OF_DELETE_BATCHES) break;
- }
- return numberDeleted;
+ // Create a query to find all the nodes at or below the specified path ...
+ Set<UUID> uuids = getUuidsForDescendantsOf(path, true);
+ Query uuidQuery = findAllNodesWithUuids(uuids);
+ // Now delete the documents from each index using this query, which we can reuse ...
+ getPathsWriter().deleteDocuments(uuidQuery);
+ getContentWriter().deleteDocuments(uuidQuery);
+ return uuids.size();
} catch (FileNotFoundException e) {
// There are no index files yet, so nothing to delete ...
return 0;
@@ -628,42 +621,42 @@
}
}
if (pathsWriter != null) {
+ // try {
+ // pathsWriter.commit();
+ // } catch (IOException e) {
+ // if (ioError == null) ioError = e;
+ // } catch (RuntimeException e) {
+ // if (runtimeError == null) runtimeError = e;
+ // } finally {
try {
- pathsWriter.commit();
+ pathsWriter.close();
} catch (IOException e) {
- ioError = e;
+ if (ioError == null) ioError = e;
} catch (RuntimeException e) {
- runtimeError = e;
+ if (runtimeError == null) runtimeError = e;
} finally {
- try {
- pathsWriter.close();
- } catch (IOException e) {
- ioError = e;
- } catch (RuntimeException e) {
- runtimeError = e;
- } finally {
- pathsWriter = null;
- }
+ pathsWriter = null;
}
+ // }
}
if (contentWriter != null) {
+ // try {
+ // contentWriter.commit();
+ // } catch (IOException e) {
+ // if (ioError == null) ioError = e;
+ // } catch (RuntimeException e) {
+ // if (runtimeError == null) runtimeError = e;
+ // } finally {
try {
- contentWriter.commit();
+ contentWriter.close();
} catch (IOException e) {
if (ioError == null) ioError = e;
} catch (RuntimeException e) {
if (runtimeError == null) runtimeError = e;
} finally {
- try {
- contentWriter.close();
- } catch (IOException e) {
- ioError = e;
- } catch (RuntimeException e) {
- runtimeError = e;
- } finally {
- contentWriter = null;
- }
+ contentWriter = null;
}
+ // }
}
if (ioError != null) {
String msg = SearchI18n.errorWhileCommittingIndexChanges.text(workspaceName, sourceName, ioError.getMessage());
@@ -916,7 +909,7 @@
}
return query;
}
- // Returna query that will always find all of the UUIDs ...
+ // Return a query that will always find all of the UUIDs ...
return new UuidsQuery(ContentIndex.UUID, uuids, getContext().getValueFactories().getUuidFactory());
}
@@ -1515,8 +1508,9 @@
protected static class UuidCollector extends Collector {
private final Set<UUID> uuids = new HashSet<UUID>();
private String[] uuidsByDocId;
- private int baseDocId;
+ // private int baseDocId;
+
protected UuidCollector() {
}
@@ -1555,10 +1549,9 @@
* @see org.apache.lucene.search.Collector#collect(int)
*/
@Override
- public void collect( int doc ) {
- int index = doc - baseDocId;
- assert index >= 0;
- String uuidString = uuidsByDocId[index];
+ public void collect( int docId ) {
+ assert docId >= 0;
+ String uuidString = uuidsByDocId[docId];
assert uuidString != null;
uuids.add(UUID.fromString(uuidString));
}
@@ -1572,7 +1565,7 @@
public void setNextReader( IndexReader reader,
int docBase ) throws IOException {
this.uuidsByDocId = FieldCache.DEFAULT.getStrings(reader, UUID_FIELD);
- this.baseDocId = docBase;
+ // this.baseDocId = docBase;
}
}
}
Added: trunk/dna-search/src/test/java/org/jboss/dna/search/SearchEngineTest.java
===================================================================
--- trunk/dna-search/src/test/java/org/jboss/dna/search/SearchEngineTest.java (rev 0)
+++ trunk/dna-search/src/test/java/org/jboss/dna/search/SearchEngineTest.java 2009-11-24 17:43:33 UTC (rev 1337)
@@ -0,0 +1,193 @@
+/*
+ * JBoss DNA (http://www.jboss.org/dna)
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ * See the AUTHORS.txt file in the distribution for a full listing of
+ * individual contributors.
+ *
+ * JBoss DNA is free software. Unless otherwise indicated, all code in JBoss DNA
+ * is licensed to you under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation; either version 2.1 of
+ * the License, or (at your option) any later version.
+ *
+ * JBoss DNA is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this software; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+ */
+package org.jboss.dna.search;
+
+import static org.hamcrest.core.Is.is;
+import static org.hamcrest.core.IsNull.notNullValue;
+import static org.junit.Assert.assertThat;
+import java.io.IOException;
+import java.util.List;
+import org.jboss.dna.graph.ExecutionContext;
+import org.jboss.dna.graph.Graph;
+import org.jboss.dna.graph.Location;
+import org.jboss.dna.graph.connector.RepositoryConnection;
+import org.jboss.dna.graph.connector.RepositoryConnectionFactory;
+import org.jboss.dna.graph.connector.RepositorySourceException;
+import org.jboss.dna.graph.connector.inmemory.InMemoryRepositorySource;
+import org.jboss.dna.graph.property.Path;
+import org.jboss.dna.graph.search.SearchEngine;
+import org.jboss.dna.graph.search.SearchProvider;
+import org.junit.Before;
+import org.junit.Test;
+import org.xml.sax.SAXException;
+
+public class SearchEngineTest {
+
+ private SearchEngine engine;
+ private SearchProvider provider;
+ private ExecutionContext context;
+ private String sourceName;
+ private String workspaceName1;
+ private String workspaceName2;
+ private InMemoryRepositorySource source;
+ private RepositoryConnectionFactory connectionFactory;
+ private Graph content;
+
+ @Before
+ public void beforeEach() throws Exception {
+ context = new ExecutionContext();
+ sourceName = "sourceA";
+ workspaceName1 = "workspace1";
+ workspaceName2 = "workspace2";
+
+ // Set up the source and graph instance ...
+ source = new InMemoryRepositorySource();
+ source.setName(sourceName);
+ content = Graph.create(source, context);
+
+ // Create the workspaces ...
+ content.createWorkspace().named(workspaceName1);
+ content.createWorkspace().named(workspaceName2);
+
+ // Set up the connection factory ...
+ connectionFactory = new RepositoryConnectionFactory() {
+ @SuppressWarnings( "synthetic-access" )
+ public RepositoryConnection createConnection( String sourceName ) throws RepositorySourceException {
+ return source.getConnection();
+ }
+ };
+
+ // Set up the provider and the search engine ...
+ IndexRules rules = DualIndexSearchProvider.DEFAULT_RULES;
+ LuceneConfiguration luceneConfig = LuceneConfigurations.inMemory();
+ // LuceneConfiguration luceneConfig = LuceneConfigurations.using(new File("target/testIndexes"));
+ provider = new DualIndexSearchProvider(luceneConfig, rules);
+ engine = new SearchEngine(context, sourceName, connectionFactory, provider);
+ loadContent();
+ }
+
+ protected Path path( String path ) {
+ return context.getValueFactories().getPathFactory().create(path);
+ }
+
+ protected void loadContent() throws IOException, SAXException {
+ // Load the content ...
+ content.useWorkspace(workspaceName1);
+ content.importXmlFrom(getClass().getClassLoader().getResourceAsStream("cars.xml")).into("/");
+ content.useWorkspace(workspaceName2);
+ content.importXmlFrom(getClass().getClassLoader().getResourceAsStream("aircraft.xml")).into("/");
+ }
+
+ @Test
+ public void shouldIndexAllContentInRepositorySource() throws Exception {
+ engine.index(3);
+ }
+
+ @Test
+ public void shouldIndexAllContentInWorkspace() throws Exception {
+ engine.index(workspaceName1, 3);
+ engine.index(workspaceName2, 5);
+ }
+
+ @Test
+ public void shouldIndexAllContentInWorkspaceBelowPath() throws Exception {
+ engine.index(workspaceName1, path("/Cars/Hybrid"), 3);
+ engine.index(workspaceName2, path("/Aircraft/Commercial"), 5);
+ }
+
+ @Test
+ public void shouldReIndexAllContentInWorkspaceBelowPath() throws Exception {
+ for (int i = 0; i != 0; i++) {
+ engine.index(workspaceName1, path("/Cars/Hybrid"), 3);
+ engine.index(workspaceName2, path("/Aircraft/Commercial"), 5);
+ }
+ }
+
+ @Test
+ public void shouldHaveLoadedTestContentIntoRepositorySource() {
+ content.useWorkspace(workspaceName1);
+ assertThat(content.getNodeAt("/Cars/Hybrid/Toyota Prius").getProperty("msrp").getFirstValue(), is((Object)"$21,500"));
+ }
+
+ @Test
+ public void shouldIndexRepositoryContentStartingAtRootAndUsingDepthOfOne() {
+ engine.index(workspaceName1, path("/"), 1);
+ }
+
+ @Test
+ public void shouldIndexRepositoryContentStartingAtRootAndUsingDepthOfTwo() {
+ engine.index(workspaceName1, path("/"), 2);
+ }
+
+ @Test
+ public void shouldIndexRepositoryContentStartingAtRootAndUsingDepthOfThree() {
+ engine.index(workspaceName1, path("/"), 3);
+ }
+
+ @Test
+ public void shouldIndexRepositoryContentStartingAtRootAndUsingDepthOfFour() {
+ engine.index(workspaceName1, path("/"), 4);
+ }
+
+ @Test
+ public void shouldIndexRepositoryContentStartingAtRootAndUsingDepthOfTen() {
+ engine.index(workspaceName1, path("/"), 10);
+ }
+
+ @Test
+ public void shouldIndexRepositoryContentStartingAtNonRootNode() {
+ engine.index(workspaceName1, path("/Cars"), 10);
+ }
+
+ @Test
+ public void shouldReIndexRepositoryContentStartingAtNonRootNode() {
+ engine.index(workspaceName1, path("/Cars"), 10);
+ engine.index(workspaceName1, path("/Cars"), 10);
+ engine.index(workspaceName1, path("/Cars"), 10);
+ }
+
+ @Test
+ public void shouldFindNodesByFullTextSearch() {
+ engine.index(workspaceName1, path("/"), 100);
+ List<Location> results = engine.fullTextSearch(context, workspaceName1, "Toyota Prius", 10, 0);
+ assertThat(results, is(notNullValue()));
+ assertThat(results.size(), is(2));
+ assertThat(results.get(0).getPath(), is(path("/Cars/Hybrid/Toyota Prius")));
+ assertThat(results.get(1).getPath(), is(path("/Cars/Hybrid/Toyota Highlander")));
+ }
+
+ @Test
+ public void shouldFindNodesByFullTextSearchWithOffset() {
+ engine.index(workspaceName1, path("/"), 100);
+ List<Location> results = engine.fullTextSearch(context, workspaceName1, "toyota prius", 1, 0);
+ assertThat(results, is(notNullValue()));
+ assertThat(results.size(), is(1));
+ assertThat(results.get(0).getPath(), is(path("/Cars/Hybrid/Toyota Prius")));
+
+ results = engine.fullTextSearch(context, workspaceName1, "+Toyota", 1, 1);
+ assertThat(results, is(notNullValue()));
+ assertThat(results.size(), is(1));
+ assertThat(results.get(0).getPath(), is(path("/Cars/Hybrid/Toyota Highlander")));
+ }
+}
Property changes on: trunk/dna-search/src/test/java/org/jboss/dna/search/SearchEngineTest.java
___________________________________________________________________
Name: svn:keywords
+ Id Revision
Name: svn:eol-style
+ LF
14 years, 5 months
DNA SVN: r1336 - in trunk/web: dna-web-jcr-rest-client and 1 other directory.
by dna-commits@lists.jboss.org
Author: rhauch
Date: 2009-11-23 21:19:50 -0500 (Mon, 23 Nov 2009)
New Revision: 1336
Modified:
trunk/web/dna-web-jcr-rest-client/pom.xml
trunk/web/dna-web-jcr-rest/pom.xml
Log:
Merge branch 'patches'
Modified: trunk/web/dna-web-jcr-rest/pom.xml
===================================================================
--- trunk/web/dna-web-jcr-rest/pom.xml 2009-11-23 23:25:59 UTC (rev 1335)
+++ trunk/web/dna-web-jcr-rest/pom.xml 2009-11-24 02:19:50 UTC (rev 1336)
@@ -15,17 +15,23 @@
<dependency>
<groupId>org.jboss.resteasy</groupId>
<artifactId>resteasy-jaxrs</artifactId>
- <version>1.2.GA</version>
+ <version>1.2.1.GA</version>
</dependency>
<dependency>
<groupId>org.jboss.resteasy</groupId>
<artifactId>resteasy-jaxb-provider</artifactId>
- <version>1.2.GA</version>
+ <version>1.2.1.GA</version>
+ <exclusions>
+ <exclusion>
+ <groupId>com.sun.xml.bind</groupId>
+ <artifactId>jaxb-impl</artifactId>
+ </exclusion>
+ </exclusions>
</dependency>
<dependency>
<groupId>org.jboss.resteasy</groupId>
<artifactId>resteasy-jettison-provider</artifactId>
- <version>1.2.GA</version>
+ <version>1.2.1.GA</version>
</dependency>
<dependency>
<groupId>org.jboss.dna</groupId>
Modified: trunk/web/dna-web-jcr-rest-client/pom.xml
===================================================================
--- trunk/web/dna-web-jcr-rest-client/pom.xml 2009-11-23 23:25:59 UTC (rev 1335)
+++ trunk/web/dna-web-jcr-rest-client/pom.xml 2009-11-24 02:19:50 UTC (rev 1336)
@@ -37,6 +37,27 @@
<version>${pom.version}</version>
<scope>integration-test</scope>
</dependency>
+ <dependency>
+ <groupId>org.jboss.resteasy</groupId>
+ <artifactId>resteasy-jaxrs</artifactId>
+ <version>1.2.1.GA</version>
+ </dependency>
+ <dependency>
+ <groupId>org.jboss.resteasy</groupId>
+ <artifactId>resteasy-jaxb-provider</artifactId>
+ <version>1.2.1.GA</version>
+ <exclusions>
+ <exclusion>
+ <groupId>com.sun.xml.bind</groupId>
+ <artifactId>jaxb-impl</artifactId>
+ </exclusion>
+ </exclusions>
+ </dependency>
+ <dependency>
+ <groupId>org.jboss.resteasy</groupId>
+ <artifactId>resteasy-jettison-provider</artifactId>
+ <version>1.2.1.GA</version>
+ </dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
@@ -83,16 +104,6 @@
<groupId>net.jcip</groupId>
<artifactId>jcip-annotations</artifactId>
</dependency>
- <dependency>
- <groupId>org.jboss.resteasy</groupId>
- <artifactId>resteasy-jaxrs</artifactId>
- <version>1.1.GA</version>
- </dependency>
- <dependency>
- <groupId>org.jboss.resteasy</groupId>
- <artifactId>resteasy-jaxb-provider</artifactId>
- <version>1.1.GA</version>
- </dependency>
</dependencies>
<reporting>
<plugins>
14 years, 5 months
DNA SVN: r1335 - trunk/web/dna-web-jcr-rest.
by dna-commits@lists.jboss.org
Author: rhauch
Date: 2009-11-23 18:25:59 -0500 (Mon, 23 Nov 2009)
New Revision: 1335
Modified:
trunk/web/dna-web-jcr-rest/pom.xml
Log:
Merge branch 'patches'
Modified: trunk/web/dna-web-jcr-rest/pom.xml
===================================================================
--- trunk/web/dna-web-jcr-rest/pom.xml 2009-11-23 22:46:41 UTC (rev 1334)
+++ trunk/web/dna-web-jcr-rest/pom.xml 2009-11-23 23:25:59 UTC (rev 1335)
@@ -12,39 +12,25 @@
<description>JBoss DNA REST support library</description>
<url>http://labs.jboss.org/dna</url>
<dependencies>
+ <dependency>
+ <groupId>org.jboss.resteasy</groupId>
+ <artifactId>resteasy-jaxrs</artifactId>
+ <version>1.2.GA</version>
+ </dependency>
<dependency>
<groupId>org.jboss.resteasy</groupId>
- <artifactId>resteasy-jaxrs</artifactId>
- <version>1.1.GA</version>
- </dependency>
- <dependency>
- <groupId>org.jboss.resteasy</groupId>
<artifactId>resteasy-jaxb-provider</artifactId>
- <version>1.1.GA</version>
- <exclusions>
- <exclusion>
- <groupId>com.sun.xml.bind</groupId>
- <artifactId>jaxb-impl</artifactId>
- </exclusion>
- </exclusions>
+ <version>1.2.GA</version>
</dependency>
-
- <!--
- This is only included as a temp. workaround. Current release of
- RESTEasy depends on 2.1.8, which is not in our repo at this time This
- should be removed after RESTEasy 1.1GA is released and added to this
- pom.
- -->
+ <dependency>
+ <groupId>org.jboss.resteasy</groupId>
+ <artifactId>resteasy-jettison-provider</artifactId>
+ <version>1.2.GA</version>
+ </dependency>
<dependency>
- <groupId>com.sun.xml.bind</groupId>
- <artifactId>jaxb-impl</artifactId>
- <version>2.1.9</version>
- </dependency>
- <dependency>
<groupId>org.jboss.dna</groupId>
<artifactId>dna-jcr</artifactId>
</dependency>
-
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
14 years, 5 months
DNA SVN: r1334 - trunk/dna-graph/src/main/java/org/jboss/dna/graph/request.
by dna-commits@lists.jboss.org
Author: rhauch
Date: 2009-11-23 17:46:41 -0500 (Mon, 23 Nov 2009)
New Revision: 1334
Modified:
trunk/dna-graph/src/main/java/org/jboss/dna/graph/request/ChangeRequest.java
trunk/dna-graph/src/main/java/org/jboss/dna/graph/request/CloneBranchRequest.java
trunk/dna-graph/src/main/java/org/jboss/dna/graph/request/CopyBranchRequest.java
trunk/dna-graph/src/main/java/org/jboss/dna/graph/request/CreateNodeRequest.java
trunk/dna-graph/src/main/java/org/jboss/dna/graph/request/DeleteBranchRequest.java
trunk/dna-graph/src/main/java/org/jboss/dna/graph/request/DeleteChildrenRequest.java
trunk/dna-graph/src/main/java/org/jboss/dna/graph/request/LockBranchRequest.java
trunk/dna-graph/src/main/java/org/jboss/dna/graph/request/MoveBranchRequest.java
trunk/dna-graph/src/main/java/org/jboss/dna/graph/request/RemovePropertyRequest.java
trunk/dna-graph/src/main/java/org/jboss/dna/graph/request/RenameNodeRequest.java
trunk/dna-graph/src/main/java/org/jboss/dna/graph/request/SetPropertyRequest.java
trunk/dna-graph/src/main/java/org/jboss/dna/graph/request/UnlockBranchRequest.java
trunk/dna-graph/src/main/java/org/jboss/dna/graph/request/UpdatePropertiesRequest.java
Log:
Merge branch 'patches'
Modified: trunk/dna-graph/src/main/java/org/jboss/dna/graph/request/ChangeRequest.java
===================================================================
--- trunk/dna-graph/src/main/java/org/jboss/dna/graph/request/ChangeRequest.java 2009-11-23 20:41:11 UTC (rev 1333)
+++ trunk/dna-graph/src/main/java/org/jboss/dna/graph/request/ChangeRequest.java 2009-11-23 22:46:41 UTC (rev 1334)
@@ -47,7 +47,8 @@
Path path );
/**
- * Get the location of the top-most node that is to be changed by this request.
+ * Get the location of the top-most node that is to be changed by this request. If this request has been completed, this
+ * location will always have a {@link Location#getPath() path}.
*
* @return the location changed by this request
*/
Modified: trunk/dna-graph/src/main/java/org/jboss/dna/graph/request/CloneBranchRequest.java
===================================================================
--- trunk/dna-graph/src/main/java/org/jboss/dna/graph/request/CloneBranchRequest.java 2009-11-23 20:41:11 UTC (rev 1333)
+++ trunk/dna-graph/src/main/java/org/jboss/dna/graph/request/CloneBranchRequest.java 2009-11-23 22:46:41 UTC (rev 1334)
@@ -261,7 +261,7 @@
*/
@Override
public Location changedLocation() {
- return into;
+ return actualIntoLocation != null ? actualIntoLocation : into;
}
/**
Modified: trunk/dna-graph/src/main/java/org/jboss/dna/graph/request/CopyBranchRequest.java
===================================================================
--- trunk/dna-graph/src/main/java/org/jboss/dna/graph/request/CopyBranchRequest.java 2009-11-23 20:41:11 UTC (rev 1333)
+++ trunk/dna-graph/src/main/java/org/jboss/dna/graph/request/CopyBranchRequest.java 2009-11-23 22:46:41 UTC (rev 1334)
@@ -268,7 +268,7 @@
*/
@Override
public Location changedLocation() {
- return into;
+ return actualIntoLocation != null ? actualIntoLocation : into;
}
/**
Modified: trunk/dna-graph/src/main/java/org/jboss/dna/graph/request/CreateNodeRequest.java
===================================================================
--- trunk/dna-graph/src/main/java/org/jboss/dna/graph/request/CreateNodeRequest.java 2009-11-23 20:41:11 UTC (rev 1333)
+++ trunk/dna-graph/src/main/java/org/jboss/dna/graph/request/CreateNodeRequest.java 2009-11-23 22:46:41 UTC (rev 1334)
@@ -322,7 +322,7 @@
*/
@Override
public Location changedLocation() {
- return actualLocation;
+ return actualLocation != null ? actualLocation : under;
}
/**
Modified: trunk/dna-graph/src/main/java/org/jboss/dna/graph/request/DeleteBranchRequest.java
===================================================================
--- trunk/dna-graph/src/main/java/org/jboss/dna/graph/request/DeleteBranchRequest.java 2009-11-23 20:41:11 UTC (rev 1333)
+++ trunk/dna-graph/src/main/java/org/jboss/dna/graph/request/DeleteBranchRequest.java 2009-11-23 22:46:41 UTC (rev 1334)
@@ -131,7 +131,7 @@
*/
@Override
public Location changedLocation() {
- return at;
+ return actualLocation != null ? actualLocation : at;
}
/**
Modified: trunk/dna-graph/src/main/java/org/jboss/dna/graph/request/DeleteChildrenRequest.java
===================================================================
--- trunk/dna-graph/src/main/java/org/jboss/dna/graph/request/DeleteChildrenRequest.java 2009-11-23 20:41:11 UTC (rev 1333)
+++ trunk/dna-graph/src/main/java/org/jboss/dna/graph/request/DeleteChildrenRequest.java 2009-11-23 22:46:41 UTC (rev 1334)
@@ -217,7 +217,7 @@
*/
@Override
public Location changedLocation() {
- return at;
+ return actualLocation != null ? actualLocation : at;
}
/**
Modified: trunk/dna-graph/src/main/java/org/jboss/dna/graph/request/LockBranchRequest.java
===================================================================
--- trunk/dna-graph/src/main/java/org/jboss/dna/graph/request/LockBranchRequest.java 2009-11-23 20:41:11 UTC (rev 1333)
+++ trunk/dna-graph/src/main/java/org/jboss/dna/graph/request/LockBranchRequest.java 2009-11-23 22:46:41 UTC (rev 1334)
@@ -167,7 +167,7 @@
*/
@Override
public Location changedLocation() {
- return actualLocation;
+ return actualLocation != null ? actualLocation : at;
}
/**
Modified: trunk/dna-graph/src/main/java/org/jboss/dna/graph/request/MoveBranchRequest.java
===================================================================
--- trunk/dna-graph/src/main/java/org/jboss/dna/graph/request/MoveBranchRequest.java 2009-11-23 20:41:11 UTC (rev 1333)
+++ trunk/dna-graph/src/main/java/org/jboss/dna/graph/request/MoveBranchRequest.java 2009-11-23 22:46:41 UTC (rev 1334)
@@ -297,12 +297,15 @@
/**
* {@inheritDoc}
+ * <p>
+ * This method returns the {@link #getActualLocationAfter()} location, or if null the {@link #into()} location.
+ * </p>
*
* @see org.jboss.dna.graph.request.ChangeRequest#changedLocation()
*/
@Override
public Location changedLocation() {
- return into != null ? into : before;
+ return actualNewLocation != null ? actualNewLocation : into != null ? into : before;
}
/**
Modified: trunk/dna-graph/src/main/java/org/jboss/dna/graph/request/RemovePropertyRequest.java
===================================================================
--- trunk/dna-graph/src/main/java/org/jboss/dna/graph/request/RemovePropertyRequest.java 2009-11-23 20:41:11 UTC (rev 1333)
+++ trunk/dna-graph/src/main/java/org/jboss/dna/graph/request/RemovePropertyRequest.java 2009-11-23 22:46:41 UTC (rev 1334)
@@ -186,7 +186,7 @@
*/
@Override
public Location changedLocation() {
- return from;
+ return actualLocation != null ? actualLocation : from;
}
/**
Modified: trunk/dna-graph/src/main/java/org/jboss/dna/graph/request/RenameNodeRequest.java
===================================================================
--- trunk/dna-graph/src/main/java/org/jboss/dna/graph/request/RenameNodeRequest.java 2009-11-23 20:41:11 UTC (rev 1333)
+++ trunk/dna-graph/src/main/java/org/jboss/dna/graph/request/RenameNodeRequest.java 2009-11-23 22:46:41 UTC (rev 1334)
@@ -138,6 +138,7 @@
String msg = GraphI18n.actualNewLocationMustHaveSameNameAsRequest.text(newLocation, toName());
throw new IllegalArgumentException(msg);
}
+ this.actualOldLocation = oldLocation;
this.actualNewLocation = newLocation;
}
@@ -172,12 +173,15 @@
/**
* {@inheritDoc}
+ * <p>
+ * This method returns the {@link #getActualLocationAfter()} location, or if null the {@link #at()} location.
+ * </p>
*
* @see org.jboss.dna.graph.request.ChangeRequest#changedLocation()
*/
@Override
public Location changedLocation() {
- return at;
+ return actualNewLocation != null ? actualNewLocation : at;
}
/**
Modified: trunk/dna-graph/src/main/java/org/jboss/dna/graph/request/SetPropertyRequest.java
===================================================================
--- trunk/dna-graph/src/main/java/org/jboss/dna/graph/request/SetPropertyRequest.java 2009-11-23 20:41:11 UTC (rev 1333)
+++ trunk/dna-graph/src/main/java/org/jboss/dna/graph/request/SetPropertyRequest.java 2009-11-23 22:46:41 UTC (rev 1334)
@@ -187,7 +187,7 @@
*/
@Override
public Location changedLocation() {
- return on;
+ return actualLocation != null ? actualLocation : on;
}
/**
Modified: trunk/dna-graph/src/main/java/org/jboss/dna/graph/request/UnlockBranchRequest.java
===================================================================
--- trunk/dna-graph/src/main/java/org/jboss/dna/graph/request/UnlockBranchRequest.java 2009-11-23 20:41:11 UTC (rev 1333)
+++ trunk/dna-graph/src/main/java/org/jboss/dna/graph/request/UnlockBranchRequest.java 2009-11-23 22:46:41 UTC (rev 1334)
@@ -133,7 +133,7 @@
*/
@Override
public Location changedLocation() {
- return actualLocation;
+ return actualLocation != null ? actualLocation : at;
}
/**
Modified: trunk/dna-graph/src/main/java/org/jboss/dna/graph/request/UpdatePropertiesRequest.java
===================================================================
--- trunk/dna-graph/src/main/java/org/jboss/dna/graph/request/UpdatePropertiesRequest.java 2009-11-23 20:41:11 UTC (rev 1333)
+++ trunk/dna-graph/src/main/java/org/jboss/dna/graph/request/UpdatePropertiesRequest.java 2009-11-23 22:46:41 UTC (rev 1334)
@@ -204,7 +204,7 @@
*/
@Override
public Location changedLocation() {
- return on;
+ return actualLocation != null ? actualLocation : on;
}
/**
14 years, 5 months
DNA SVN: r1333 - trunk/dna-graph/src/main/java/org/jboss/dna/graph/session.
by dna-commits@lists.jboss.org
Author: rhauch
Date: 2009-11-23 15:41:11 -0500 (Mon, 23 Nov 2009)
New Revision: 1333
Modified:
trunk/dna-graph/src/main/java/org/jboss/dna/graph/session/GraphSession.java
Log:
DNA-554 Corrected the logic of the GraphSession.Node.containsChangesWithExternalDependencies() method, which returned a boolean value that was opposite of the documented result. All unit tests and TCK tests continue to pass.
Modified: trunk/dna-graph/src/main/java/org/jboss/dna/graph/session/GraphSession.java
===================================================================
--- trunk/dna-graph/src/main/java/org/jboss/dna/graph/session/GraphSession.java 2009-11-19 23:08:36 UTC (rev 1332)
+++ trunk/dna-graph/src/main/java/org/jboss/dna/graph/session/GraphSession.java 2009-11-23 20:41:11 UTC (rev 1333)
@@ -705,7 +705,7 @@
boolean keepChanges ) throws InvalidStateException, RepositorySourceException {
if (!node.isRoot() && node.isChanged(true)) {
// Need to make sure that changes to this branch are not dependent upon changes to nodes outside of this branch...
- if (!node.containsChangesWithExternalDependencies()) {
+ if (node.containsChangesWithExternalDependencies()) {
I18n msg = GraphI18n.unableToRefreshBranchBecauseChangesDependOnChangesToNodesOutsideOfBranch;
String path = node.getPath().getString(context.getNamespaceRegistry());
throw new InvalidStateException(msg.text(path, workspaceName));
@@ -847,7 +847,7 @@
}
// Need to make sure that changes to this branch are not dependent upon changes to nodes outside of this branch...
- if (!node.containsChangesWithExternalDependencies()) {
+ if (node.containsChangesWithExternalDependencies()) {
I18n msg = GraphI18n.unableToSaveBranchBecauseChangesDependOnChangesToNodesOutsideOfBranch;
String path = node.getPath().getString(context.getNamespaceRegistry());
throw new ValidationException(msg.text(path, workspaceName));
@@ -1772,13 +1772,15 @@
if (!changedNode.isAtOrBelow(this)) {
// The node is not within this branch, so the original parent must not be at or below this node ...
if (cache.nodes.get(dependency.getMovedFrom()).isAtOrBelow(this)) {
- return false;
+ // The original parent is below 'this' but the changed node is not ...
+ return true;
}
// None of the other dependencies can be within this branch ...
for (NodeId dependentId : dependency.getRequireChangesTo()) {
// The dependent node must not be at or below this node ...
if (cache.nodes.get(dependentId).isAtOrBelow(this)) {
- return false;
+ // The other node that must change is at or below 'this'
+ return true;
}
}
// Otherwise, continue with the next change ...
@@ -1789,20 +1791,26 @@
// Second, check whether this node was moved from outside this branch ...
if (dependency.getMovedFrom() != null) {
Node<Payload, PropertyPayload> originalParent = cache.nodes.get(dependency.getMovedFrom());
+ // If the original parent cannot be found ...
+ if (originalParent == null) {
+ continue;
+ }
// The original parent must be at or below this node ...
if (!originalParent.isAtOrBelow(this)) {
- return false;
+ // The original parent is not within this branch (but the new parent is)
+ return true;
}
// All of the other dependencies must be within this branch ...
for (NodeId dependentId : dependency.getRequireChangesTo()) {
// The dependent node must not be at or below this node ...
if (!cache.nodes.get(dependentId).isAtOrBelow(this)) {
- return false;
+ // Another dependent node is not at or below this branch either ...
+ return true;
}
}
}
}
- return true;
+ return false;
}
/**
14 years, 5 months
DNA SVN: r1332 - in branches/ddl_sequencer/dna-graph/src: test/java/org/jboss/dna/graph/query/parse and 1 other directory.
by dna-commits@lists.jboss.org
Author: blafond
Date: 2009-11-19 18:08:36 -0500 (Thu, 19 Nov 2009)
New Revision: 1332
Modified:
branches/ddl_sequencer/dna-graph/src/main/java/org/jboss/dna/graph/query/parse/SqlQueryParser.java
branches/ddl_sequencer/dna-graph/src/test/java/org/jboss/dna/graph/query/parse/SqlQueryParserTest.java
Log:
Fixed problem in token positions having the wrong column number.
Modified: branches/ddl_sequencer/dna-graph/src/main/java/org/jboss/dna/graph/query/parse/SqlQueryParser.java
===================================================================
--- branches/ddl_sequencer/dna-graph/src/main/java/org/jboss/dna/graph/query/parse/SqlQueryParser.java 2009-11-19 23:07:26 UTC (rev 1331)
+++ branches/ddl_sequencer/dna-graph/src/main/java/org/jboss/dna/graph/query/parse/SqlQueryParser.java 2009-11-19 23:08:36 UTC (rev 1332)
@@ -398,15 +398,12 @@
}
protected Term parseFullTextSearchExpression( String expression,
- Position position ) {
+ Position startOfExpression ) {
try {
return new FullTextSearchParser().parse(expression);
} catch (ParsingException e) {
// Convert the position in the exception into a position in the query.
- Position exprPos = e.getPosition();
- int line = position.getLine() + exprPos.getLine() - 1;
- int column = exprPos.getLine() == 1 ? exprPos.getColumn() + position.getColumn() : exprPos.getColumn();
- Position queryPos = new Position(line, column);
+ Position queryPos = startOfExpression.add(e.getPosition());
throw new ParsingException(queryPos, e.getMessage());
}
}
@@ -864,14 +861,14 @@
case '|':
case '=':
case ':':
- tokens.addToken(input.position(), input.index(), input.index() + 1, SYMBOL);
+ tokens.addToken(input.position(input.index()), input.index(), input.index() + 1, SYMBOL);
break;
case '\'':
case '[':
case '\"':
int startIndex = input.index();
char closingChar = c == '[' ? ']' : c;
- Position pos = input.position();
+ Position pos = input.position(startIndex);
boolean foundClosingQuote = false;
while (input.hasNext()) {
c = input.next();
@@ -896,7 +893,7 @@
break;
case '-':
startIndex = input.index();
- pos = input.position();
+ pos = input.position(input.index());
if (input.isNext('-')) {
// End-of-line comment ...
boolean foundLineTerminator = false;
@@ -914,13 +911,13 @@
tokens.addToken(pos, startIndex, endIndex, COMMENT);
}
} else {
- tokens.addToken(input.position(), input.index(), input.index() + 1, SYMBOL);
+ tokens.addToken(input.position(input.index()), input.index(), input.index() + 1, SYMBOL);
break;
}
break;
case '/':
startIndex = input.index();
- pos = input.position();
+ pos = input.position(input.index());
if (input.isNext('*')) {
// Multi-line comment ...
while (input.hasNext() && !input.isNext('*', '/')) {
@@ -933,13 +930,13 @@
tokens.addToken(pos, startIndex, endIndex, COMMENT);
}
} else {
- tokens.addToken(input.position(), input.index(), input.index() + 1, SYMBOL);
+ tokens.addToken(input.position(input.index()), input.index(), input.index() + 1, SYMBOL);
break;
}
break;
default:
startIndex = input.index();
- pos = input.position();
+ pos = input.position(input.index());
// Read as long as there is a valid XML character ...
int tokenType = (Character.isLetterOrDigit(c) || c == '_') ? WORD : OTHER;
while (input.isNextLetterOrDigit() || input.isNext('_')) {
Modified: branches/ddl_sequencer/dna-graph/src/test/java/org/jboss/dna/graph/query/parse/SqlQueryParserTest.java
===================================================================
--- branches/ddl_sequencer/dna-graph/src/test/java/org/jboss/dna/graph/query/parse/SqlQueryParserTest.java 2009-11-19 23:07:26 UTC (rev 1331)
+++ branches/ddl_sequencer/dna-graph/src/test/java/org/jboss/dna/graph/query/parse/SqlQueryParserTest.java 2009-11-19 23:08:36 UTC (rev 1332)
@@ -625,7 +625,7 @@
@Test
public void shouldParseFullTextSearchExpressionFromStringWithValidExpression() {
- Position pos = new Position(100, 13);
+ Position pos = new Position(500, 100, 13);
FullTextSearch.Term result = parser.parseFullTextSearchExpression("term1 term2 OR -term3 OR -term4 OR term5", pos);
assertThat(result, is(notNullValue()));
assertThat(result, is(instanceOf(Disjunction.class)));
@@ -644,11 +644,12 @@
@Test
public void shouldConvertPositionWhenUnableToParseFullTextSearchExpression() {
try {
- parser.parseFullTextSearchExpression("", new Position(100, 13));
+ parser.parseFullTextSearchExpression("", new Position(500, 100, 13));
fail("Should have thrown an exception");
} catch (ParsingException e) {
assertThat(e.getPosition().getLine(), is(100));
assertThat(e.getPosition().getColumn(), is(13));
+ assertThat(e.getPosition().getIndexInContent(), is(500));
}
}
14 years, 5 months
DNA SVN: r1331 - in branches/ddl_sequencer/dna-common/src: main/java/org/jboss/dna/common/text and 2 other directories.
by dna-commits@lists.jboss.org
Author: blafond
Date: 2009-11-19 18:07:26 -0500 (Thu, 19 Nov 2009)
New Revision: 1331
Added:
branches/ddl_sequencer/dna-common/src/test/java/org/jboss/dna/common/text/PositionTest.java
Modified:
branches/ddl_sequencer/dna-common/src/main/java/org/jboss/dna/common/CommonI18n.java
branches/ddl_sequencer/dna-common/src/main/java/org/jboss/dna/common/text/Position.java
branches/ddl_sequencer/dna-common/src/main/java/org/jboss/dna/common/text/TokenStream.java
branches/ddl_sequencer/dna-common/src/main/resources/org/jboss/dna/common/CommonI18n.properties
branches/ddl_sequencer/dna-common/src/test/java/org/jboss/dna/common/text/TokenStreamTest.java
Log:
Added starting Index "in content" to Position object. Changed integer Token Stream constants to bit-mask values.
Modified: branches/ddl_sequencer/dna-common/src/main/java/org/jboss/dna/common/CommonI18n.java
===================================================================
--- branches/ddl_sequencer/dna-common/src/main/java/org/jboss/dna/common/CommonI18n.java 2009-11-18 19:42:04 UTC (rev 1330)
+++ branches/ddl_sequencer/dna-common/src/main/java/org/jboss/dna/common/CommonI18n.java 2009-11-19 23:07:26 UTC (rev 1331)
@@ -104,6 +104,7 @@
public static I18n expectingValidIntegerAtLineAndColumn;
public static I18n expectingValidLongAtLineAndColumn;
public static I18n expectingValidBooleanAtLineAndColumn;
+ public static I18n endPositionMustBeGreaterThanStartingPosition;
static {
try {
Modified: branches/ddl_sequencer/dna-common/src/main/java/org/jboss/dna/common/text/Position.java
===================================================================
--- branches/ddl_sequencer/dna-common/src/main/java/org/jboss/dna/common/text/Position.java 2009-11-18 19:42:04 UTC (rev 1330)
+++ branches/ddl_sequencer/dna-common/src/main/java/org/jboss/dna/common/text/Position.java 2009-11-19 23:07:26 UTC (rev 1331)
@@ -7,14 +7,37 @@
*/
@Immutable
public final class Position {
+ /**
+ * The position is used when there is no content.
+ */
+ public final static Position EMPTY_CONTENT_POSITION = new Position(-1, 1, 0);
+
private final int line;
private final int column;
+ private final int indexInContent;
- public Position( int line,
+ public Position( int indexInContent,
+ int line,
int column ) {
+ this.indexInContent = indexInContent < 0 ? -1:indexInContent;
this.line = line;
this.column = column;
+
+ assert this.indexInContent >= -1;
+ assert this.line > 0;
+ assert this.column >= 0;
+ // make sure that negative index means an EMPTY_CONTENT_POSITION
+ assert this.indexInContent < 0 ? this.line == 1 && this.column == 0: true;
}
+
+ /**
+ * Get the 0-based index of this position in the content character array.
+ *
+ * @return the index; never negative except for the first position in an empty content.
+ */
+ public int getIndexInContent() {
+ return indexInContent;
+ }
/**
* Get the 1-based column number of the character.
@@ -41,7 +64,7 @@
*/
@Override
public int hashCode() {
- return line;
+ return indexInContent;
}
/**
@@ -51,6 +74,28 @@
*/
@Override
public String toString() {
- return "" + line + ':' + column;
+ return "" + indexInContent + ':' + line + ':' + column;
}
+
+ /**
+ * Return a new position that is the addition of this position and that supplied.
+ *
+ * @param position the position to add to this object; may not be null
+ * @return the combined position
+ */
+ public Position add(Position position) {
+ if( this.getIndexInContent() < 0 ) {
+ return position.getIndexInContent() < 0 ? EMPTY_CONTENT_POSITION:position;
+ }
+
+ if( position.getIndexInContent() < 0 ) {
+ return this;
+ }
+
+ int index = this.getIndexInContent() + position.getIndexInContent();
+ int line = position.getLine() + this.getLine() - 1;
+ int column = this.getLine() == 1 ? this.getColumn() + position.getColumn() : this.getColumn();
+
+ return new Position(index, line, column);
+ }
}
Modified: branches/ddl_sequencer/dna-common/src/main/java/org/jboss/dna/common/text/TokenStream.java
===================================================================
--- branches/ddl_sequencer/dna-common/src/main/java/org/jboss/dna/common/text/TokenStream.java 2009-11-18 19:42:04 UTC (rev 1330)
+++ branches/ddl_sequencer/dna-common/src/main/java/org/jboss/dna/common/text/TokenStream.java 2009-11-19 23:07:26 UTC (rev 1331)
@@ -384,6 +384,20 @@
private final boolean caseSensitive;
private final Tokenizer tokenizer;
private List<Token> tokens;
+ /**
+ * This class navigates the Token objects using this iterator. However, because it very often needs to access the
+ * "current token" in the "consume(...)" and "canConsume(...)" and "matches(...)" methods, the class caches a "current token"
+ * and makes this iterator point to the 2nd token.
+ *
+ * <pre>
+ * T1 T2 T3 T4 T5
+ * ˆ ˆ ˆ
+ * | | |
+ * | | +- The position of the tokenIterator, where tokenIterator.hasNext() will return T3
+ * | +---- The token referenced by currentToken
+ * +-------- The logical position of the TokenStream object, where the "consume()" would return T2
+ * </pre>
+ */
private ListIterator<Token> tokenIterator;
private Token currentToken;
private boolean completed;
@@ -412,7 +426,7 @@
TokenFactory tokenFactory = caseSensitive ? new CaseSensitiveTokenFactory() : new CaseInsensitiveTokenFactory();
CharacterStream characterStream = new CharacterArrayStream(inputContent);
tokenizer.tokenize(characterStream, tokenFactory);
- this.tokens = tokenFactory.getTokens();
+ this.tokens = initializeTokens(tokenFactory.getTokens());
}
// Create the iterator ...
@@ -420,6 +434,28 @@
moveToNextToken();
return this;
}
+
+ /**
+ * Method to allow subclasses to preprocess the set of tokens and return the correct tokens to use.
+ * The default behavior is to simply return the supplied tokens.
+ *
+ * @param tokens
+ * @return list of tokens.
+ */
+ protected List<Token> initializeTokens( List<Token> tokens) {
+ return tokens;
+ }
+
+ /**
+ * Method to allow tokens to be re-used from the start without re-tokenizing content.
+ */
+ public void rewind() {
+ // recreate the iterator ...
+ tokenIterator = this.tokens.listIterator();
+ completed = false;
+ currentToken = null;
+ moveToNextToken();
+ }
/**
* Get the position of the previous token.
@@ -526,7 +562,7 @@
protected void throwNoMoreContent() throws ParsingException {
String msg = CommonI18n.noMoreContent.text();
- Position pos = tokens.isEmpty() ? new Position(1, 0) : tokens.get(tokens.size() - 1).position();
+ Position pos = tokens.isEmpty() ? new Position(-1, 1, 0) : tokens.get(tokens.size() - 1).position();
throw new ParsingException(pos, msg);
}
@@ -954,7 +990,7 @@
* @throws IllegalStateException if this method was called before the stream was {@link #start() started}
*/
public boolean matches( int expectedType ) throws IllegalStateException {
- return !completed && (expectedType == ANY_TYPE || currentToken().type() == expectedType);
+ return !completed && currentToken().matches(expectedType);
}
/**
@@ -1047,7 +1083,7 @@
ListIterator<Token> iter = tokens.listIterator(tokenIterator.previousIndex());
if (!iter.hasNext()) return false;
Token token = iter.next();
- if (currentExpectedType != ANY_TYPE || currentToken().type() != currentExpectedType) return false;
+ if (currentExpectedType != ANY_TYPE && currentToken().type() != currentExpectedType) return false;
for (int nextExpectedType : expectedTypeForNextTokens) {
if (!iter.hasNext()) return false;
token = iter.next();
@@ -1075,7 +1111,7 @@
if (!iter.hasNext()) return false;
token = iter.next();
if (nextExpectedType == ANY_TYPE) continue;
- if (token.type() != nextExpectedType) return false;
+ if (!token.matches(nextExpectedType)) return false;
}
return true;
}
@@ -1233,6 +1269,29 @@
}
/**
+ * Gets the content string starting at the first position (inclusive) and continuing up to the end position (exclusive).
+ *
+ * @param starting the position marking the beginning of the desired content string.
+ * @param end the position located directly after the returned content string; can be null, which means end of content
+ * @return the content string; never null
+ */
+ public String getContentBetween(Position starting, Position end) {
+ CheckArg.isNotNull(starting, "starting");
+
+ int startIndex = starting.getIndexInContent();
+ int endIndex = inputString.length();
+ if( end != null ) {
+ endIndex = end.getIndexInContent();
+ }
+
+ if( startIndex >= endIndex ) {
+ throw new IllegalArgumentException(CommonI18n.endPositionMustBeGreaterThanStartingPosition.text(startIndex, endIndex));
+ }
+
+ return inputString.substring(startIndex, endIndex);
+ }
+
+ /**
* Get the previous token. This does not modify the state.
*
* @return the previous token; never null
@@ -1249,11 +1308,10 @@
}
throw new IllegalStateException(CommonI18n.startMethodMustBeCalledBeforeConsumingOrMatching.text());
}
- if (!tokenIterator.hasPrevious()) {
+ if (tokenIterator.previousIndex() == 0 ) {
throw new NoSuchElementException(CommonI18n.noMoreContent.text());
}
- ListIterator<Token> temp = tokens.listIterator(tokenIterator.previousIndex());
- return temp.next();
+ return tokens.get(tokenIterator.previousIndex()-1);
}
String generateFragment() {
@@ -1336,10 +1394,11 @@
/**
* Get the position for the last character returned from {@link #next()}.
+ * @param startIndex
*
* @return the position of the last character returned; never null
*/
- Position position();
+ Position position(int startIndex);
/**
* Determine if the next character on the sream is a {@link Character#isWhitespace(char) whitespace character}. This
@@ -1495,6 +1554,14 @@
* @return true if the token's value matches the supplied character value, or false otherwise
*/
boolean matches( char expected );
+
+ /**
+ * Determine if the token matches the supplied type.
+ *
+ * @param expectedType the expected integer type
+ * @return true if the token's value matches the supplied integer type, or false otherwise
+ */
+ boolean matches( int expectedType );
/**
* Get the type of the token.
@@ -1530,6 +1597,14 @@
* @return the position; never null
*/
Position position();
+
+ /**
+ * Bitmask ORed with existing type value.
+ *
+ * @param typeMask
+ * @return copy of Token with new type
+ */
+ Token withType( int typeMask);
}
/**
@@ -1553,6 +1628,17 @@
}
/**
+ * {@inheritDoc}
+ *
+ * @see org.jboss.dna.common.text.TokenStream.Token#withType(int)
+ */
+ @Override
+ public Token withType(int typeMask) {
+ int type = this.type | typeMask;
+ return new CaseSensitiveToken(startIndex, endIndex, type, position);
+ }
+
+ /**
* {@inheritDoc}
*
* @see org.jboss.dna.common.text.TokenStream.Token#type()
@@ -1607,6 +1693,16 @@
}
/**
+ * {@inheritDoc}
+ *
+ * @see org.jboss.dna.common.text.TokenStream.Token#matches(int)
+ */
+ @Override
+ public final boolean matches(int expectedType) {
+ return expectedType == ANY_TYPE || (currentToken().type() & expectedType) == expectedType;
+ }
+
+ /**
* {@inheritDoc}
*
* @see org.jboss.dna.common.text.TokenStream.Token#value()
@@ -1657,6 +1753,17 @@
protected String matchString() {
return inputUppercased;
}
+
+ /**
+ * {@inheritDoc}
+ *
+ * @see org.jboss.dna.common.text.TokenStream.Token#withType(int)
+ */
+ @Override
+ public Token withType(int typeMask) {
+ int type = this.type() | typeMask;
+ return new CaseInsensitiveToken(startIndex(), endIndex(), type, position());
+ }
}
protected abstract class TokenFactory implements Tokens {
@@ -1755,11 +1862,13 @@
/**
* {@inheritDoc}
+ * @param startIndex
+ * @return the position of the token. never null
*
- * @see org.jboss.dna.common.text.TokenStream.CharacterStream#position()
+ * @see org.jboss.dna.common.text.TokenStream.CharacterStream#position(int)
*/
- public Position position() {
- return new Position(lineNumber, columnNumber);
+ public Position position(int startIndex) {
+ return new Position(startIndex, lineNumber, columnNumber);
}
/**
@@ -1776,10 +1885,10 @@
if (result == '\r') {
nextCharMayBeLineFeed = true;
++lineNumber;
- columnNumber = 1;
+ columnNumber = 0;
} else if (result == '\n') {
if (!nextCharMayBeLineFeed) ++lineNumber;
- columnNumber = 1;
+ columnNumber = 0;
} else if (nextCharMayBeLineFeed) {
nextCharMayBeLineFeed = false;
}
@@ -1922,22 +2031,22 @@
/**
* The {@link Token#type() token type} for tokens that consist of an individual '.' character.
*/
- public static final int DECIMAL = 3;
+ public static final int DECIMAL = 4;
/**
* The {@link Token#type() token type} for tokens that consist of all the characters within single-quotes. Single quote
* characters are included if they are preceded (escaped) by a '\' character.
*/
- public static final int SINGLE_QUOTED_STRING = 4;
+ public static final int SINGLE_QUOTED_STRING = 8;
/**
* The {@link Token#type() token type} for tokens that consist of all the characters within double-quotes. Double quote
* characters are included if they are preceded (escaped) by a '\' character.
*/
- public static final int DOUBLE_QUOTED_STRING = 5;
+ public static final int DOUBLE_QUOTED_STRING = 16;
/**
* The {@link Token#type() token type} for tokens that consist of all the characters between "/*" and "*/" or between
* "//" and the next line terminator (e.g., '\n', '\r' or "\r\n").
*/
- public static final int COMMENT = 6;
+ public static final int COMMENT = 32;
private final boolean useComments;
@@ -1981,14 +2090,14 @@
case '|':
case '=':
case ':':
- tokens.addToken(input.position(), input.index(), input.index() + 1, SYMBOL);
+ tokens.addToken(input.position(input.index()), input.index(), input.index() + 1, SYMBOL);
break;
case '.':
- tokens.addToken(input.position(), input.index(), input.index() + 1, DECIMAL);
+ tokens.addToken(input.position(input.index()), input.index(), input.index() + 1, DECIMAL);
break;
case '\"':
int startIndex = input.index();
- Position startingPosition = input.position();
+ Position startingPosition = input.position(startIndex);
boolean foundClosingQuote = false;
while (input.hasNext()) {
c = input.next();
@@ -2005,11 +2114,11 @@
throw new ParsingException(startingPosition, msg);
}
int endIndex = input.index() + 1; // beyond last character read
- tokens.addToken(input.position(), startIndex, endIndex, DOUBLE_QUOTED_STRING);
+ tokens.addToken(startingPosition, startIndex, endIndex, DOUBLE_QUOTED_STRING);
break;
case '\'':
startIndex = input.index();
- startingPosition = input.position();
+ startingPosition = input.position(startIndex);
foundClosingQuote = false;
while (input.hasNext()) {
c = input.next();
@@ -2026,10 +2135,11 @@
throw new ParsingException(startingPosition, msg);
}
endIndex = input.index() + 1; // beyond last character read
- tokens.addToken(input.position(), startIndex, endIndex, SINGLE_QUOTED_STRING);
+ tokens.addToken(startingPosition, startIndex, endIndex, SINGLE_QUOTED_STRING);
break;
case '/':
startIndex = input.index();
+ startingPosition = input.position(startIndex);
if (input.isNext('/')) {
// End-of-line comment ...
boolean foundLineTerminator = false;
@@ -2044,7 +2154,7 @@
if (!foundLineTerminator) ++endIndex; // must point beyond last char
if (c == '\r' && input.isNext('\n')) input.next();
if (useComments) {
- tokens.addToken(input.position(), startIndex, endIndex, COMMENT);
+ tokens.addToken(startingPosition, startIndex, endIndex, COMMENT);
}
} else if (input.isNext('*')) {
// Multi-line comment ...
@@ -2055,21 +2165,22 @@
if (input.hasNext()) input.next(); // consume the '/'
if (useComments) {
endIndex = input.index() + 1; // the token will include the '/' and '*' characters
- tokens.addToken(input.position(), startIndex, endIndex, COMMENT);
+ tokens.addToken(startingPosition, startIndex, endIndex, COMMENT);
}
} else {
// just a regular slash ...
- tokens.addToken(input.position(), startIndex, startIndex + 1, SYMBOL);
+ tokens.addToken(startingPosition, startIndex, startIndex + 1, SYMBOL);
}
break;
default:
startIndex = input.index();
+ startingPosition = input.position(startIndex);
// Read until another whitespace/symbol/decimal/slash is found
while (input.hasNext() && !(input.isNextWhitespace() || input.isNextAnyOf("/.-(){}*,;+%?$[]!<>|=:"))) {
c = input.next();
}
endIndex = input.index() + 1; // beyond last character that was included
- tokens.addToken(input.position(), startIndex, endIndex, WORD);
+ tokens.addToken(startingPosition, startIndex, endIndex, WORD);
}
}
}
Modified: branches/ddl_sequencer/dna-common/src/main/resources/org/jboss/dna/common/CommonI18n.properties
===================================================================
--- branches/ddl_sequencer/dna-common/src/main/resources/org/jboss/dna/common/CommonI18n.properties 2009-11-18 19:42:04 UTC (rev 1330)
+++ branches/ddl_sequencer/dna-common/src/main/resources/org/jboss/dna/common/CommonI18n.properties 2009-11-19 23:07:26 UTC (rev 1331)
@@ -93,3 +93,4 @@
expectingValidIntegerAtLineAndColumn = Expecting a valid integer value but found '{0}' at line {1}, column {2}
expectingValidLongAtLineAndColumn = Expecting a valid long value but found '{0}' at line {1}, column {2}
expectingValidBooleanAtLineAndColumn = Expecting a valid boolean value but found '{0}' at line {1}, column {2}
+endPositionMustBeGreaterThanStartingPosition = End position {1} must be greater than starting position {0}
Added: branches/ddl_sequencer/dna-common/src/test/java/org/jboss/dna/common/text/PositionTest.java
===================================================================
--- branches/ddl_sequencer/dna-common/src/test/java/org/jboss/dna/common/text/PositionTest.java (rev 0)
+++ branches/ddl_sequencer/dna-common/src/test/java/org/jboss/dna/common/text/PositionTest.java 2009-11-19 23:07:26 UTC (rev 1331)
@@ -0,0 +1,85 @@
+/*
+ * JBoss DNA (http://www.jboss.org/dna)
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ * See the AUTHORS.txt file in the distribution for a full listing of
+ * individual contributors.
+ *
+ * JBoss DNA is free software. Unless otherwise indicated, all code in JBoss DNA
+ * is licensed to you under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation; either version 2.1 of
+ * the License, or (at your option) any later version.
+ *
+ * JBoss DNA is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this software; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+ */
+package org.jboss.dna.common.text;
+
+import static org.junit.Assert.assertThat;
+
+import static org.hamcrest.core.Is.is;
+
+import org.junit.Test;
+
+
+public class PositionTest {
+
+ private int combinedIndex(int firstIndex, int secondIndex) {
+ Position first = new Position(firstIndex, 1, 0);
+ Position second = new Position(secondIndex, 1, 0);
+
+ int firstPlusSecond = first.add(second).getIndexInContent();
+ int secondPlusFirst = second.add(first).getIndexInContent();
+
+ assertThat(firstPlusSecond, is(secondPlusFirst));
+
+ return firstPlusSecond;
+ }
+
+ @Test
+ public void shouldAddNoContentPositionToValidPosition() {
+ // -1 to >=0
+ assertThat(combinedIndex(-1, 0), is(0));
+ assertThat(combinedIndex(-1, 1), is(1));
+ assertThat(combinedIndex(-1, 10), is(10));
+ }
+
+ @Test
+ public void shouldAddValidPositionToNoContentPosition() {
+ // >= 0 to -1
+ assertThat(combinedIndex(0, -1), is(0));
+ assertThat(combinedIndex(1, -1), is(1));
+ assertThat(combinedIndex(10, -1), is(10));
+ }
+
+ @Test
+ public void shouldAddValidPositionToValidPosition() {
+ // positive to positive
+ assertThat(combinedIndex(1, 1), is(2));
+ assertThat(combinedIndex(10, 1), is(11));
+ assertThat(combinedIndex(1, 10), is(11));
+ assertThat(combinedIndex(10, 10), is(20));
+ }
+
+ @Test
+ public void shouldAddStartingPositionToStartingPosition() {
+ // 0 to 0
+ assertThat(combinedIndex(0, 0), is(0));
+ }
+
+ @Test
+ public void shouldAddNoContentPositionToNoContentPosition() {
+ // -1 to -1
+ assertThat(combinedIndex(-1, -1), is(-1));
+ assertThat(combinedIndex(-10, -1), is(-1));
+ assertThat(combinedIndex(-1, -10), is(-1));
+ }
+}
Property changes on: branches/ddl_sequencer/dna-common/src/test/java/org/jboss/dna/common/text/PositionTest.java
___________________________________________________________________
Name: svn:mime-type
+ text/plain
Modified: branches/ddl_sequencer/dna-common/src/test/java/org/jboss/dna/common/text/TokenStreamTest.java
===================================================================
--- branches/ddl_sequencer/dna-common/src/test/java/org/jboss/dna/common/text/TokenStreamTest.java 2009-11-18 19:42:04 UTC (rev 1330)
+++ branches/ddl_sequencer/dna-common/src/test/java/org/jboss/dna/common/text/TokenStreamTest.java 2009-11-19 23:07:26 UTC (rev 1331)
@@ -25,7 +25,9 @@
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;
+
import java.util.Arrays;
+
import org.jboss.dna.common.text.TokenStream.BasicTokenizer;
import org.jboss.dna.common.text.TokenStream.Tokenizer;
import org.junit.Before;
@@ -336,6 +338,19 @@
assertThat(tokens.canConsume("FROM", "THIS", "TABLE"), is(true));
assertThat(tokens.hasNext(), is(false));
}
+
+ @Test
+ public void shouldReturnTrueFromMatchIfAllTypeValuesMatch() {
+ makeCaseInsensitive();
+ assertThat(tokens.matches(BasicTokenizer.WORD, BasicTokenizer.WORD), is(true));
+ }
+
+ @Test
+ public void shouldReturnFalseFromMatchIfAllTypeValuesDoNotMatch() {
+ makeCaseInsensitive();
+ assertThat(tokens.matches(BasicTokenizer.WORD, BasicTokenizer.DECIMAL), is(false));
+ assertThat(tokens.matches(BasicTokenizer.DECIMAL, BasicTokenizer.WORD), is(false));
+ }
@Test
public void shouldConsumeMultipleTokensWithAnyValueConstant() {
@@ -397,4 +412,51 @@
assertThat(tokens.canConsume(TokenStream.ANY_VALUE), is(false));
assertThat(tokens.canConsume(BasicTokenizer.SYMBOL), is(false));
}
+
+ @Test
+ public void shouldFindNextPositionStartIndex() {
+ makeCaseInsensitive();
+ // "Select all columns from this table";
+ tokens.consume();
+ // Next position should be line 1, column 8
+ assertThat(tokens.nextPosition().getIndexInContent(), is(7));
+ assertThat(tokens.nextPosition().getColumn(), is(8));
+ assertThat(tokens.nextPosition().getLine(), is(1));
+ }
+
+ @Test
+ public void shouldFindPreviousPositionStartIndex() {
+ makeCaseInsensitive();
+ // "Select all columns from this table";
+ tokens.consume();
+ tokens.consume();
+ // previous position should be line 1, column 8
+ assertThat(tokens.previousPosition().getIndexInContent(), is(7));
+ assertThat(tokens.previousPosition().getColumn(), is(8));
+ assertThat(tokens.previousPosition().getLine(), is(1));
+ }
+
+ @Test
+ public void shouldParseMultiLineString() {
+ makeCaseInsensitive();
+ String content = "ALTER DATABASE \n"
+ + "DO SOMETHING; \n"
+ + "ALTER DATABASE \n"
+ + " SET DEFAULT BIGFILE TABLESPACE;";
+ tokens = new TokenStream(content, tokenizer, true);
+ tokens.start();
+
+ tokens.consume(); // LINE
+ tokens.consume(); // ONE
+ tokens.consume(); // DO
+ tokens.consume(); // SOMETHING
+ tokens.consume(); // ;
+
+ assertThat(tokens.nextPosition().getIndexInContent(), is(31));
+ assertThat(tokens.nextPosition().getColumn(), is(1));
+ tokens.consume(); // ALTER
+ assertThat(tokens.nextPosition().getIndexInContent(), is(37));
+ assertThat(tokens.nextPosition().getColumn(), is(7));
+
+ }
}
14 years, 5 months