org.eclipse.rdf4j.query.algebra.Union Java Examples

The following examples show how to use org.eclipse.rdf4j.query.algebra.Union. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: PCJOptimizerUtilities.java    From rya with Apache License 2.0 6 votes vote down vote up
@Override
public void meet(final Union union) {
    boolean filterMoved = false;
    if (Sets.intersection(union.getRightArg().getBindingNames(), filterVars).size() > 0) {
        relocate(filter, union.getRightArg());
        filterMoved = true;
    }
 
    if (Sets.intersection(union.getLeftArg().getBindingNames(), filterVars).size() > 0) {
        if (filterMoved) {
            final Filter clone = new Filter(filter.getArg(), filter.getCondition().clone());
            relocate(clone, union.getLeftArg());
        } else {
            relocate(filter, union.getLeftArg());
        }
    }
}
 
Example #2
Source File: StrictEvaluationStrategy.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@SuppressWarnings("unchecked")
public CloseableIteration<BindingSet, QueryEvaluationException> evaluate(final Union union,
		final BindingSet bindings) throws QueryEvaluationException {
	Iteration<BindingSet, QueryEvaluationException> leftArg, rightArg;

	leftArg = new DelayedIteration<BindingSet, QueryEvaluationException>() {

		@Override
		protected Iteration<BindingSet, QueryEvaluationException> createIteration()
				throws QueryEvaluationException {
			return evaluate(union.getLeftArg(), bindings);
		}
	};

	rightArg = new DelayedIteration<BindingSet, QueryEvaluationException>() {

		@Override
		protected Iteration<BindingSet, QueryEvaluationException> createIteration()
				throws QueryEvaluationException {
			return evaluate(union.getRightArg(), bindings);
		}
	};

	return new UnionIteration<>(leftArg, rightArg);
}
 
Example #3
Source File: StrictEvaluationStrategy.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public CloseableIteration<BindingSet, QueryEvaluationException> evaluate(BinaryTupleOperator expr,
		BindingSet bindings) throws QueryEvaluationException {
	if (expr instanceof Join) {
		return evaluate((Join) expr, bindings);
	} else if (expr instanceof LeftJoin) {
		return evaluate((LeftJoin) expr, bindings);
	} else if (expr instanceof Union) {
		return evaluate((Union) expr, bindings);
	} else if (expr instanceof Intersection) {
		return evaluate((Intersection) expr, bindings);
	} else if (expr instanceof Difference) {
		return evaluate((Difference) expr, bindings);
	} else if (expr == null) {
		throw new IllegalArgumentException("expr must not be null");
	} else {
		throw new QueryEvaluationException("Unsupported binary tuple operator type: " + expr.getClass());
	}
}
 
Example #4
Source File: DisjunctiveConstraintOptimizer.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
public void meet(Filter filter) {
	if (filter.getCondition() instanceof Or && containsSameTerm(filter.getCondition())) {
		Or orNode = (Or) filter.getCondition();
		TupleExpr filterArg = filter.getArg();

		ValueExpr leftConstraint = orNode.getLeftArg();
		ValueExpr rightConstraint = orNode.getRightArg();

		// remove filter
		filter.replaceWith(filterArg);

		// Push UNION down below other filters to avoid cloning them
		TupleExpr node = findNotFilter(filterArg);

		Filter leftFilter = new Filter(node.clone(), leftConstraint);
		Filter rightFilter = new Filter(node.clone(), rightConstraint);
		Union union = new Union(leftFilter, rightFilter);
		node.replaceWith(union);

		filter.getParentNode().visit(this);
	} else {
		super.meet(filter);
	}
}
 
Example #5
Source File: ReflexivePropertyVisitorTest.java    From rya with Apache License 2.0 6 votes vote down vote up
@Test
public void testReflexiveProperty() throws Exception {
    // Define a reflexive property
    final InferenceEngine inferenceEngine = mock(InferenceEngine.class);
    when(inferenceEngine.isReflexiveProperty(HAS_FAMILY)).thenReturn(true);
    // Construct a query, then visit it
    final StatementPattern sp = new StatementPattern(new Var("s", ALICE), new Var("p", HAS_FAMILY), new Var("o"));
    final Projection query = new Projection(sp, new ProjectionElemList(new ProjectionElem("o", "member")));
    query.visit(new ReflexivePropertyVisitor(conf, inferenceEngine));
    // Expected structure after rewriting SP(:Alice :hasFamilyMember ?member):
    //
    // Union(
    //     originalSP(:Alice :hasFamilyMember ?member),
    //     ZeroLengthPath(:Alice, ?member)
    // )
    Assert.assertTrue(query.getArg() instanceof Union);
    final TupleExpr left = ((Union) query.getArg()).getLeftArg();
    final TupleExpr right = ((Union) query.getArg()).getRightArg();
    Assert.assertEquals(sp, left);
    Assert.assertTrue(right instanceof ZeroLengthPath);
    Assert.assertEquals(sp.getSubjectVar(), ((ZeroLengthPath) right).getSubjectVar());
    Assert.assertEquals(sp.getObjectVar(), ((ZeroLengthPath) right).getObjectVar());
}
 
Example #6
Source File: FederationJoinOptimizer.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private void addOwners(LeftJoin node, RepositoryConnection leftOwner, RepositoryConnection rightOwner,
		boolean local) {
	if (leftOwner == null && rightOwner == null) {
		if (local) {
			TupleExpr union = null;
			for (RepositoryConnection member : members) {
				OwnedTupleExpr arg = new OwnedTupleExpr(member, // NOPMD
						node.clone());
				union = union == null ? arg : new Union(union, arg); // NOPMD
			}
			node.replaceWith(union);
		}
	} else if (leftOwner == rightOwner) { // NOPMD
		node.replaceWith(new OwnedTupleExpr(leftOwner, node.clone()));
	} else {
		if (local) {
			addDistinctOwnersLocal(node, leftOwner, rightOwner);
		} else {
			addDistinctOwnersNonLocal(node, leftOwner, rightOwner);
		}
	}
}
 
Example #7
Source File: FederationJoinOptimizer.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private void performReplacementsInNode(NaryJoin node, List<LocalJoin> vars) {
	NaryJoin replacement = new NaryJoin();
	for (LocalJoin e : vars) {
		if (distinct || e.getVar() != null) {
			TupleExpr union = null;
			for (RepositoryConnection member : members) {
				TupleExpr arg = new OwnedTupleExpr(member, e.getJoin() // NOPMD
						.clone());
				union = union == null ? arg : new Union(union, arg); // NOPMD
			}
			if (union != null) {
				replacement.addArg(union);
			}
		} else {
			for (TupleExpr expr : e.getJoin().getArgs()) {
				replacement.addArg(expr);
			}
		}
	}
	node.replaceWith(replacement);
}
 
Example #8
Source File: HasSelfVisitorTest.java    From rya with Apache License 2.0 6 votes vote down vote up
@Test
public void testTypePattern() throws Exception {
    final InferenceEngine inferenceEngine = mock(InferenceEngine.class);
    final Set<IRI> narcissistProps = new HashSet<>();
    narcissistProps.add(love);
    when(inferenceEngine.getHasSelfImplyingType(narcissist)).thenReturn(narcissistProps);
    final Var subj = new Var("s");
    final Var obj = new Var("o", narcissist);
    obj.setConstant(true);
    final Var pred = new Var("p", RDF.TYPE);
    pred.setConstant(true);

    final Projection query = new Projection(new StatementPattern(subj, pred, obj),
            new ProjectionElemList(new ProjectionElem("s", "subject")));
    query.visit(new HasSelfVisitor(conf, inferenceEngine));

    Assert.assertTrue(query.getArg() instanceof Union);
    final Union union = (Union) query.getArg();
    Assert.assertTrue(union.getRightArg() instanceof StatementPattern);
    Assert.assertTrue(union.getLeftArg() instanceof StatementPattern);
    final StatementPattern expectedLeft = new StatementPattern(subj, pred, obj);
    final StatementPattern expectedRight = new StatementPattern(subj, new Var("urn:love", love), subj);
    Assert.assertEquals(expectedLeft, union.getLeftArg());
    Assert.assertEquals(expectedRight, union.getRightArg());
}
 
Example #9
Source File: IterativeEvaluationOptimizer.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
public void meet(Union union) {
	super.meet(union);

	TupleExpr leftArg = union.getLeftArg();
	TupleExpr rightArg = union.getRightArg();

	if (leftArg instanceof Join && rightArg instanceof Join) {
		Join leftJoinArg = (Join) leftArg;
		Join rightJoin = (Join) rightArg;

		if (leftJoinArg.getLeftArg().equals(rightJoin.getLeftArg())) {
			// factor out the left-most join argument
			Join newJoin = new Join();
			union.replaceWith(newJoin);
			newJoin.setLeftArg(leftJoinArg.getLeftArg());
			newJoin.setRightArg(union);
			union.setLeftArg(leftJoinArg.getRightArg());
			union.setRightArg(rightJoin.getRightArg());

			union.visit(this);
		}
	}
}
 
Example #10
Source File: SpinRenderer.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
public void meet(Union node) throws RDFHandlerException {
	listEntry();
	handler.handleStatement(valueFactory.createStatement(subject, RDF.TYPE, SP.UNION_CLASS));
	Resource elementsList = valueFactory.createBNode();
	handler.handleStatement(valueFactory.createStatement(subject, SP.ELEMENTS_PROPERTY, elementsList));
	ListContext elementsCtx = newList(elementsList);
	listEntry();
	ListContext leftCtx = newList(subject);
	node.getLeftArg().visit(this);
	endList(leftCtx);

	listEntry();
	ListContext rightCtx = newList(subject);
	node.getRightArg().visit(this);
	endList(rightCtx);
	endList(elementsCtx);
}
 
Example #11
Source File: HalyardTupleExprEvaluation.java    From Halyard with Apache License 2.0 6 votes vote down vote up
/**
 * Evaluate {@link Union} query model nodes.
 * @param parent
 * @param union
 * @param bindings
 */
private void evaluateUnion(BindingSetPipe parent, Union union, BindingSet bindings) {
    BindingSetPipe pipe = new BindingSetPipe(parent) {
        AtomicInteger args = new AtomicInteger(2);
        @Override
        public boolean push(BindingSet bs) throws InterruptedException {
            if (bs == null) {
                if (args.decrementAndGet() == 0) {
                    return parent.push(null);
                } else {
                    return false;
                }
            } else {
                return parent.push(bs);
            }
        }
    };
    evaluateTupleExpr(pipe, union.getLeftArg(), bindings);
    evaluateTupleExpr(pipe, union.getRightArg(), bindings);
}
 
Example #12
Source File: UnionOptimizer.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
public void meet(Union union) {

	// retrieve the union arguments, also those of nested unions
	List<TupleExpr> args = new ArrayList<>();
	handleUnionArgs(union, args);

	// remove any tuple expressions that do not produce any result
	List<TupleExpr> filtered = new ArrayList<>(args.size());
	for (TupleExpr arg : args) {
		if (arg instanceof EmptyResult) {
			continue;
		}
		filtered.add(arg);
	}

	// create a NUnion having the arguments in one layer
	// however, check if we only have zero or one argument first
	if (filtered.isEmpty()) {
		union.replaceWith(new EmptyNUnion(args, queryInfo));
	} else if (filtered.size() == 1) {
		union.replaceWith(filtered.get(0));
	} else {
		union.replaceWith(new NUnion(filtered, queryInfo));
	}
}
 
Example #13
Source File: QueryAlgebraUtil.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
protected static Union constructInnerUnion(StatementPattern stmt, int outerID, Set<String> varNames,
		List<BindingSet> bindings) {

	Union union = new Union();
	union.setLeftArg(constructStatementId(stmt, outerID + "_0", varNames, bindings.get(0)));
	Union tmp = union;
	int idx;
	for (idx = 1; idx < bindings.size() - 1; idx++) {
		Union _u = new Union();
		_u.setLeftArg(constructStatementId(stmt, outerID + "_" + idx, varNames, bindings.get(idx)));
		tmp.setRightArg(_u);
		tmp = _u;
	}
	tmp.setRightArg(constructStatementId(stmt, outerID + "_" + idx, varNames, bindings.get(idx)));

	return union;
}
 
Example #14
Source File: QueryAlgebraUtil.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Construct a SELECT query for a grouped bound check.
 *
 * Pattern:
 *
 * SELECT DISTINCT ?o_1 .. ?o_N WHERE { { s1 p1 ?o_1 FILTER ?o_1=o1 } UNION ... UNION { sN pN ?o_N FILTER ?o_N=oN }}
 *
 * @param stmt
 * @param unionBindings
 * @return the SELECT query
 */
public static TupleExpr selectQueryStringBoundCheck(StatementPattern stmt, List<BindingSet> unionBindings) {

	Set<String> varNames = new HashSet<>();

	Union union = new Union();
	union.setLeftArg(constructStatementCheckId(stmt, 0, varNames, unionBindings.get(0)));
	Union tmp = union;
	int idx;
	for (idx = 1; idx < unionBindings.size() - 1; idx++) {
		Union _u = new Union();
		_u.setLeftArg(constructStatementCheckId(stmt, idx, varNames, unionBindings.get(idx)));
		tmp.setRightArg(_u);
		tmp = _u;
	}
	tmp.setRightArg(constructStatementCheckId(stmt, idx, varNames, unionBindings.get(idx)));

	ProjectionElemList projList = new ProjectionElemList();
	for (String var : varNames) {
		projList.addElement(new ProjectionElem(var));
	}

	Projection proj = new Projection(union, projList);

	return proj;
}
 
Example #15
Source File: SPARQLTupleExprRenderer.java    From semagrow with Apache License 2.0 6 votes vote down vote up
/**
 * @inheritDoc
 */
@Override
public void meet(Union theOp)
        throws Exception
{
    ctxOpen(theOp);

    String aLeft = renderTupleExpr(theOp.getLeftArg());
    if (aLeft.endsWith("\n")) {
        aLeft = aLeft.substring(0, aLeft.length() - 1);
    }

    String aRight = renderTupleExpr(theOp.getRightArg());
    if (aRight.endsWith("\n")) {
        aRight = aRight.substring(0, aRight.length() - 1);
    }

    mJoinBuffer.append(indent()).append("{\n").append(aLeft).append("\n").append(indent()).append("}\n").append(
            indent()).append("union\n").append(indent()).append("{\n").append(aRight).append("\n").append(
            indent()).append("}.\n");

    ctxClose(theOp);
}
 
Example #16
Source File: HalyardTupleExprEvaluation.java    From Halyard with Apache License 2.0 6 votes vote down vote up
/**
 * Evaluate {@link BinaryTupleOperator} query model nodes
 * @param parent
 * @param expr
 * @param bindings
 */
private void evaluateBinaryTupleOperator(BindingSetPipe parent, BinaryTupleOperator expr, BindingSet bindings) {
    if (expr instanceof Join) {
        evaluateJoin(parent, (Join) expr, bindings);
    } else if (expr instanceof LeftJoin) {
        evaluateLeftJoin(parent, (LeftJoin) expr, bindings);
    } else if (expr instanceof Union) {
        evaluateUnion(parent, (Union) expr, bindings);
    } else if (expr instanceof Intersection) {
        evaluateIntersection(parent, (Intersection) expr, bindings);
    } else if (expr instanceof Difference) {
        evaluateDifference(parent, (Difference) expr, bindings);
    } else if (expr == null) {
        parent.handleException(new IllegalArgumentException("expr must not be null"));
    } else {
        parent.handleException(new QueryEvaluationException("Unsupported binary tuple operator type: " + expr.getClass()));
    }
}
 
Example #17
Source File: JoinOrderOptimizer.java    From CostFed with GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
protected void meetNode(QueryModelNode node) {
	if (node instanceof StatementPattern) {
		meet((StatementPattern)node);
	} else if (node instanceof Filter) {
		meet((Filter)node);
	} else if (node instanceof Union) {
		meet((Union)node);
	} else if (node instanceof ExclusiveGroup) {
		meet((ExclusiveGroup)node);
	} else if (node instanceof NJoin) {
		meet((NJoin)node);
	} else {
		super.meetNode(node);
	}
}
 
Example #18
Source File: TupleExprBuilder.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
public Object visit(ASTUnionGraphPattern node, Object data) throws VisitorException {
	GraphPattern parentGP = graphPattern;

	graphPattern = new GraphPattern(parentGP);
	node.jjtGetChild(0).jjtAccept(this, null);
	TupleExpr leftArg = graphPattern.buildTupleExpr();

	graphPattern = new GraphPattern(parentGP);
	node.jjtGetChild(1).jjtAccept(this, null);
	TupleExpr rightArg = graphPattern.buildTupleExpr();

	Union union = new Union(leftArg, rightArg);
	union.setVariableScopeChange(true);
	parentGP.addRequiredTE(union);
	graphPattern = parentGP;

	return null;
}
 
Example #19
Source File: UnionBlock.java    From semagrow with Apache License 2.0 6 votes vote down vote up
public Collection<Plan> getUnionPlan(CompilerContext context, Collection<Plan> p1, Collection<Plan> p2) {

        if (p1.isEmpty())
            return p2;

        if (p2.isEmpty())
            return p1;

        //FIXME: try also ordered union merge
        //FIXME: check that pp1 and pp2 is in the same site or need shipping

        RequestedPlanProperties props = new RequestedPlanProperties();
        props.setSite(LocalSite.getInstance());

        return context.enforceProps(p1, props).stream().flatMap(pp1 ->
                context.enforceProps(p2, props).stream().flatMap(pp2 ->
                        Stream.of(context.asPlan(new Union(pp1, pp2)))
                )
        ).collect(Collectors.toList());
    }
 
Example #20
Source File: QueryAlgebraUtil.java    From CostFed with GNU Affero General Public License v3.0 6 votes vote down vote up
protected static Union constructInnerUnion(StatementPattern stmt, int outerID, Set<String> varNames, List<BindingSet> bindings) {
	
	Union union = new Union();
	union.setLeftArg(constructStatementId(stmt, outerID + "_0", varNames, bindings.get(0)) );
	Union tmp = union;
	int idx;
	for (idx=1; idx<bindings.size()-1; idx++) {
		Union _u = new Union();
		_u.setLeftArg( constructStatementId(stmt, outerID + "_" + idx, varNames, bindings.get(idx)) );
		tmp.setRightArg(_u);
		tmp = _u;
	}
	tmp.setRightArg( constructStatementId(stmt, outerID + "_" + idx, varNames, bindings.get(idx)));
	
	return union;
}
 
Example #21
Source File: QueryAlgebraUtil.java    From CostFed with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Construct a SELECT query for a grouped bound check.
 * 
 * Pattern:
 * 
 * SELECT DISTINCT ?o_1 .. ?o_N WHERE { { s1 p1 ?o_1 FILTER ?o_1=o1 } UNION ... UNION { sN pN ?o_N FILTER ?o_N=oN }}
 * 
 * @param stmt
 * @param unionBindings
 * @return
 */
public static TupleExpr selectQueryStringBoundCheck(StatementPattern stmt, List<BindingSet> unionBindings) {
	
	Set<String> varNames = new HashSet<String>();
	
	Union union = new Union();
	union.setLeftArg(constructStatementCheckId(stmt, 0, varNames, unionBindings.get(0)) );
	Union tmp = union;
	int idx;
	for (idx=1; idx<unionBindings.size()-1; idx++) {
		Union _u = new Union();
		_u.setLeftArg( constructStatementCheckId(stmt, idx, varNames, unionBindings.get(idx)) );
		tmp.setRightArg(_u);
		tmp = _u;
	}
	tmp.setRightArg( constructStatementCheckId(stmt, idx, varNames, unionBindings.get(idx) ));
	
	ProjectionElemList projList = new ProjectionElemList();
	for (String var : varNames)
		projList.addElement( new ProjectionElem(var));
	
	Projection proj = new Projection(union, projList);

	return proj;
}
 
Example #22
Source File: ContextCollector.java    From semagrow with Apache License 2.0 5 votes vote down vote up
/**
 * @inheritDoc
 */
@Override
public void meet(Union theOp)
        throws Exception
{
    binaryOpMeet(theOp, theOp.getLeftArg(), theOp.getRightArg());
}
 
Example #23
Source File: PatternBlock.java    From semagrow with Apache License 2.0 5 votes vote down vote up
private Collection<Plan> union(CompilerContext context, Plan p1, Plan p2)
{
    RequestedPlanProperties props = new RequestedPlanProperties();

    props.setSite(LocalSite.getInstance());

    Collection<Plan> pc1 = context.enforceProps(p1, props);
    Collection<Plan> pc2 = context.enforceProps(p2, props);

    return pc1.stream()
            .flatMap( s1 -> pc2.stream().map( s2 ->
                        context.asPlan(new Union(s1, s2))
            )).collect(Collectors.toList());
}
 
Example #24
Source File: FederatedEvaluationStrategyImpl.java    From semagrow with Apache License 2.0 5 votes vote down vote up
public Flux<BindingSet> evaluateReactorInternal(TupleExpr expr, List<BindingSet> bindingList)
        throws QueryEvaluationException
{
    if (expr instanceof Plan)
        return evaluateReactorInternal(((Plan) expr).getArg(), bindingList);
    else if (expr instanceof Union)
        return evaluateReactorInternal((Union) expr, bindingList);
    else if (expr instanceof SourceQuery)
        return evaluateReactorInternal((SourceQuery) expr, bindingList);
    else
        return evaluateReactiveDefault(expr, bindingList);
}
 
Example #25
Source File: FederatedEvaluationStrategyImpl.java    From semagrow with Apache License 2.0 5 votes vote down vote up
public Flux<BindingSet> evaluateReactorInternal(Union expr, List<BindingSet> bindingList)
        throws QueryEvaluationException
{
    return Flux.just(expr.getLeftArg(), expr.getRightArg())
            .flatMap(e -> {
                try {
                    return evaluateReactorInternal(e, bindingList);
                } catch (Exception x) {
                    return Flux.error(x);
            }});
}
 
Example #26
Source File: HasSelfVisitorTest.java    From rya with Apache License 2.0 5 votes vote down vote up
@Test
public void testPropertyPattern_constantSubj() throws Exception {
    final InferenceEngine inferenceEngine = mock(InferenceEngine.class);
    final Set<Resource> loveTypes = new HashSet<>();
    loveTypes.add(narcissist);
    when(inferenceEngine.getHasSelfImplyingProperty(love)).thenReturn(loveTypes);
    final Var subj = new Var("s", self);
    subj.setConstant(true);
    final Var obj = new Var("o");
    final Var pred = new Var("p", love);
    pred.setConstant(true);

    final Projection query = new Projection(new StatementPattern(subj, pred, obj),
            new ProjectionElemList(new ProjectionElem("s", "subject")));
    query.visit(new HasSelfVisitor(conf, inferenceEngine));

    Assert.assertTrue(query.getArg() instanceof Union);
    final Union union = (Union) query.getArg();
    Assert.assertTrue(union.getRightArg() instanceof StatementPattern);
    Assert.assertTrue(union.getLeftArg() instanceof Extension);
    final StatementPattern expectedRight = new StatementPattern(subj, pred, obj);
    final Extension expectedLeft = new Extension(
            new StatementPattern(subj, new Var(RDF.TYPE.stringValue(), RDF.TYPE), new Var("urn:Narcissist", narcissist)),
            new ExtensionElem(subj, "o"));
    Assert.assertEquals(expectedLeft, union.getLeftArg());
    Assert.assertEquals(expectedRight, union.getRightArg());
}
 
Example #27
Source File: InverseOfVisitor.java    From rya with Apache License 2.0 5 votes vote down vote up
@Override
protected void meetSP(StatementPattern node) throws Exception {
    StatementPattern sp = node.clone();
    final Var predVar = sp.getPredicateVar();

    IRI pred = (IRI) predVar.getValue();
    String predNamespace = pred.getNamespace();

    final Var objVar = sp.getObjectVar();
    final Var cntxtVar = sp.getContextVar();
    if (objVar != null &&
            !RDF.NAMESPACE.equals(predNamespace) &&
            !SESAME.NAMESPACE.equals(predNamespace) &&
            !RDFS.NAMESPACE.equals(predNamespace)
            && !EXPANDED.equals(cntxtVar)) {
        /**
         *
         * { ?a ?pred ?b .}\n" +
         "       UNION " +
         "      { ?b ?pred ?a }
         */

        IRI predIri = (IRI) predVar.getValue();
        IRI invPropIri = inferenceEngine.findInverseOf(predIri);
        if (invPropIri != null) {
            Var subjVar = sp.getSubjectVar();
            Union union = new InferUnion();
            union.setLeftArg(sp);
            union.setRightArg(new StatementPattern(objVar, new Var(predVar.getName(), invPropIri), subjVar, cntxtVar));
            node.replaceWith(union);
        }
    }
}
 
Example #28
Source File: SPARQLParserTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test
public void testWildCardPathComplexSubjectHandling() {

	String query = "PREFIX : <http://example.org/>\n ASK { ?a (:comment/^(:subClassOf|(:type/:label))/:type)* ?b } ";

	ParsedQuery parsedQuery = parser.parseQuery(query, null);
	TupleExpr tupleExpr = parsedQuery.getTupleExpr();

	Slice slice = (Slice) tupleExpr;

	ArbitraryLengthPath path = (ArbitraryLengthPath) slice.getArg();
	Var pathStart = path.getSubjectVar();
	Var pathEnd = path.getObjectVar();

	assertThat(pathStart.getName()).isEqualTo("a");
	assertThat(pathEnd.getName()).isEqualTo("b");

	Join pathSequence = (Join) path.getPathExpression();
	Join innerJoin = (Join) pathSequence.getLeftArg();
	Var commentObjectVar = ((StatementPattern) innerJoin.getLeftArg()).getObjectVar();

	Union union = (Union) innerJoin.getRightArg();
	Var subClassOfSubjectVar = ((StatementPattern) union.getLeftArg()).getSubjectVar();
	assertThat(subClassOfSubjectVar).isNotEqualTo(commentObjectVar);

	Var subClassOfObjectVar = ((StatementPattern) union.getLeftArg()).getObjectVar();

	assertThat(subClassOfObjectVar).isEqualTo(commentObjectVar);
}
 
Example #29
Source File: TupleExprBuilder.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public Object visit(ASTPathAlternative pathAltNode, Object data) throws VisitorException {

	int altCount = pathAltNode.jjtGetNumChildren();

	if (altCount > 1) {
		GraphPattern parentGP = graphPattern;
		Union union = new Union();
		Union currentUnion = union;
		for (int i = 0; i < altCount - 1; i++) {
			graphPattern = new GraphPattern(parentGP);
			pathAltNode.jjtGetChild(i).jjtAccept(this, data);
			TupleExpr arg = graphPattern.buildTupleExpr();
			currentUnion.setLeftArg(arg);
			if (i == altCount - 2) { // second-to-last item
				graphPattern = new GraphPattern(parentGP);
				pathAltNode.jjtGetChild(i + 1).jjtAccept(this, data);
				arg = graphPattern.buildTupleExpr();
				currentUnion.setRightArg(arg);
			} else {
				Union newUnion = new Union();
				currentUnion.setRightArg(newUnion);
				currentUnion = newUnion;
			}
		}

		// when using union to execute path expressions, the scope does not not change
		union.setVariableScopeChange(false);
		parentGP.addRequiredTE(union);
		graphPattern = parentGP;
	} else {
		pathAltNode.jjtGetChild(0).jjtAccept(this, data);
	}

	return null;
}
 
Example #30
Source File: UnionBuilder.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * @inheritDoc
 */
@Override
public TupleExpr expr() {
	if (mLeft != null && mRight != null) {
		return new Union(mLeft.expr(), mRight.expr());
	} else if (mLeft != null && mRight == null) {
		return mLeft.expr();

	} else if (mRight != null && mLeft == null) {
		return mRight.expr();
	} else {
		return null;
	}
}