org.eclipse.rdf4j.query.parser.ParsedQuery Java Examples

The following examples show how to use org.eclipse.rdf4j.query.parser.ParsedQuery. 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: StrictEvaluationStrategyTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Verifies if only those input bindings that actually occur in the query are returned in the result. See SES-2373.
 */
@Test
public void testBindings() throws Exception {
	String query = "SELECT ?a ?b WHERE {}";
	ParsedQuery pq = QueryParserUtil.parseQuery(QueryLanguage.SPARQL, query, null);

	final ValueFactory vf = SimpleValueFactory.getInstance();
	QueryBindingSet constants = new QueryBindingSet();
	constants.addBinding("a", vf.createLiteral("foo"));
	constants.addBinding("b", vf.createLiteral("bar"));
	constants.addBinding("x", vf.createLiteral("X"));
	constants.addBinding("y", vf.createLiteral("Y"));

	CloseableIteration<BindingSet, QueryEvaluationException> result = strategy.evaluate(pq.getTupleExpr(),
			constants);
	assertNotNull(result);
	assertTrue(result.hasNext());
	BindingSet bs = result.next();
	assertTrue(bs.hasBinding("a"));
	assertTrue(bs.hasBinding("b"));
	assertFalse(bs.hasBinding("x"));
	assertFalse(bs.hasBinding("y"));
}
 
Example #2
Source File: ConstructProjectionTest.java    From rya with Apache License 2.0 6 votes vote down vote up
@Test
public void testConstructProjectionBNodes() throws MalformedQueryException {
    String query = "select ?o where { _:b <uri:talksTo> ?o }";
    
    SPARQLParser parser = new SPARQLParser();
    ParsedQuery pq = parser.parseQuery(query, null);
    List<StatementPattern> patterns = StatementPatternCollector.process(pq.getTupleExpr());
    ConstructProjection projection = new ConstructProjection(patterns.get(0));
    
    QueryBindingSet bs = new QueryBindingSet();
    bs.addBinding("o", VF.createIRI("uri:Bob"));
    VisibilityBindingSet vBs = new VisibilityBindingSet(bs);
    BNode bNode = VF.createBNode();
    Map<String, BNode> bNodeMap = new HashMap<>();
    bNodeMap.put(VarNameUtils.prependAnonymous("1"), bNode);
    RyaStatement statement = projection.projectBindingSet(vBs,bNodeMap);
    
    RyaStatement expected = new RyaStatement(RdfToRyaConversions.convertResource(bNode), new RyaIRI("uri:talksTo"), new RyaIRI("uri:Bob"));
    expected.setTimestamp(statement.getTimestamp());
    expected.setColumnVisibility(new byte[0]);
    
    assertEquals(expected, statement);
}
 
Example #3
Source File: TupleReArrangerTest.java    From rya with Apache License 2.0 6 votes vote down vote up
@Test
public void tupleReArrangeTest2() throws MalformedQueryException {

    String queryString = ""//
            + "SELECT ?a ?b ?c ?d ?e ?x ?y" //
            + "{" //
            + " ?e <uri:laughsAt> ?x ." //
            + " ?e <uri:livesIn> ?y . "//
            + "{ ?a a ?b .  ?a <http://www.w3.org/2000/01/rdf-schema#label> ?c  }"//
            + " UNION { ?a <uri:talksTo> ?d .  ?a <http://www.w3.org/2000/01/rdf-schema#label> ?e  }"//
            + "}";//

    SPARQLParser sp = new SPARQLParser();
    ParsedQuery pq = sp.parseQuery(queryString, null);
    List<TupleExpr> tuples = TupleReArranger.getTupleReOrderings(pq.getTupleExpr());


    Assert.assertEquals(24, tuples.size());

}
 
Example #4
Source File: PeriodicQueryUtilTest.java    From rya with Apache License 2.0 6 votes vote down vote up
@Test
public void testPeriodicNodePlacement() throws MalformedQueryException {
     String query = "prefix function: <http://org.apache.rya/function#> " //n
            + "prefix time: <http://www.w3.org/2006/time#> " //n
            + "prefix fn: <http://www.w3.org/2006/fn#> " //n
            + "select ?obs ?time ?lat where {" //n
            + "Filter(function:periodic(?time, 12.0, 6.0,time:hours)) " //n
            + "Filter(fn:test(?lat, 25)) " //n
            + "?obs <uri:hasTime> ?time. " //n
            + "?obs <uri:hasLattitude> ?lat }"; //n
     
     SPARQLParser parser = new SPARQLParser();
     ParsedQuery pq = parser.parseQuery(query, null);
     TupleExpr te = pq.getTupleExpr();
     te.visit(new PeriodicQueryNodeVisitor());
     
     PeriodicNodeCollector collector = new PeriodicNodeCollector();
     te.visit(collector);
     
     PeriodicQueryNode node2 = new PeriodicQueryNode(12*60*60*1000L, 6*3600*1000L, TimeUnit.MILLISECONDS, "time", new Join());

     Assert.assertEquals(true, periodicNodesEqualIgnoreArg(node2, collector.getPeriodicQueryNode()));
     
}
 
Example #5
Source File: TestPropPathMisbehaviour.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * reproduces GH-2343: the obj var of the nested statement pattern should be equal to the objVar of the ALP path
 * that is using the PE
 */
@Test
public void testGH2343() {
	String query1 = "select ?iri ?value where { \n" +
			"    ?iri (<urn:p>+) / <urn:q> ?value .\n" +
			"}";
	ParsedQuery q = parser.parseQuery(query1, "http://base.org/");

	assertNotNull(q);
	assertTrue("expect projection", q.getTupleExpr() instanceof Projection);
	Projection proj = (Projection) q.getTupleExpr();

	assertTrue("expect join", proj.getArg() instanceof Join);
	assertTrue("expect left arg to be ALP", ((Join) proj.getArg()).getLeftArg() instanceof ArbitraryLengthPath);
	ArbitraryLengthPath alp = (ArbitraryLengthPath) ((Join) proj.getArg()).getLeftArg();

	assertTrue("expect single statement pattern in alp PE", alp.getPathExpression() instanceof StatementPattern);
	StatementPattern sp = (StatementPattern) alp.getPathExpression();
	assertNotNull(sp.getSubjectVar());

	assertTrue("expect subj var to be iri", "iri".equals(sp.getSubjectVar().getName()));

	assertTrue("expect obj var of the pattern to be same as the objVar of ALP",
			alp.getObjectVar().equals(sp.getObjectVar()));
}
 
Example #6
Source File: ConstructProjectionTest.java    From rya with Apache License 2.0 6 votes vote down vote up
@Test
public void testConstructProjectionProjPred() throws MalformedQueryException {
    String query = "select ?p where { <uri:Joe> ?p <uri:Bob> }";
    
    SPARQLParser parser = new SPARQLParser();
    ParsedQuery pq = parser.parseQuery(query, null);
    List<StatementPattern> patterns = StatementPatternCollector.process(pq.getTupleExpr());
    ConstructProjection projection = new ConstructProjection(patterns.get(0));
    
    QueryBindingSet bs = new QueryBindingSet();
    bs.addBinding("p", VF.createIRI("uri:worksWith"));
    VisibilityBindingSet vBs = new VisibilityBindingSet(bs);
    RyaStatement statement = projection.projectBindingSet(vBs, new HashMap<>());
    
    RyaStatement expected = new RyaStatement(new RyaIRI("uri:Joe"), new RyaIRI("uri:worksWith"), new RyaIRI("uri:Bob"));
    expected.setTimestamp(statement.getTimestamp());
    expected.setColumnVisibility(new byte[0]);
    
    assertEquals(expected, statement);
}
 
Example #7
Source File: SparqlToPigTransformVisitorTest.java    From rya with Apache License 2.0 6 votes vote down vote up
public void testMutlipleJoins() throws Exception {
        String query = "select * where {\n" +
                "?subj <urn:lubm:rdfts#name> 'Department0'.\n" +
                "?subj <urn:lubm:rdfts#subOrganizationOf> <http://www.University0.edu>.\n" +
                "?subj <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <urn:lubm:rdfts#Department>.\n" +
                "}";
//        System.out.println(query);
        QueryParser parser = new SPARQLParser();
        ParsedQuery parsedQuery = parser.parseQuery(query, null);

//        System.out.println(parsedQuery);

        SparqlToPigTransformVisitor visitor = new SparqlToPigTransformVisitor();
        visitor.setTablePrefix(tablePrefix);
        visitor.setInstance(instance);
        visitor.setZk(zk);
        visitor.setUser(user);
        visitor.setPassword(password);
        visitor.meet(new QueryRoot(parsedQuery.getTupleExpr()));
//        System.out.println(visitor.getPigScript());
    }
 
Example #8
Source File: StatementMetadataExternalSetProviderTest.java    From rya with Apache License 2.0 6 votes vote down vote up
@Test
public void createSingleAccumuloMetadataNode() throws MalformedQueryException {

    AccumuloRdfConfiguration conf = (AccumuloRdfConfiguration) getConf(false);
    Set<RyaIRI> propertySet = new HashSet<>();
    propertySet.add(new RyaIRI("http://createdBy"));
    conf.setStatementMetadataProperties(propertySet);
    StatementMetadataExternalSetProvider metaProvider = new StatementMetadataExternalSetProvider(
            conf);
    SPARQLParser parser = new SPARQLParser();
    ParsedQuery pq = parser.parseQuery(query, null);

    List<QueryModelNode> patterns = new ArrayList<>();
    List<StatementMetadataNode<?>> expected = new ArrayList<>();
    Set<StatementPattern> sp = StatementMetadataTestUtils.getMetadataStatementPatterns(pq.getTupleExpr(), propertySet);

    patterns.addAll(StatementPatternCollector.process(pq.getTupleExpr()));
    JoinSegment<StatementMetadataNode<?>> segment = new JoinSegment<>(
            new HashSet<>(patterns), patterns, new HashMap<ValueExpr, Filter>());
    List<StatementMetadataNode<?>> extSets = metaProvider.getExternalSets(segment);

    expected.add(new StatementMetadataNode<>(sp, conf));

    Assert.assertEquals(expected, extSets);

}
 
Example #9
Source File: ConvertSpinRDFToString.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
public Value evaluate(ValueFactory valueFactory, Value... args) throws ValueExprEvaluationException {
	if (args.length < 1 || args.length > 2) {
		throw new ValueExprEvaluationException("Incorrect number of arguments");
	}
	if (!(args[0] instanceof Resource)) {
		throw new ValueExprEvaluationException("First argument must be the root of a SPIN RDF query");
	}
	if (args.length == 2 && !(args[1] instanceof Literal)) {
		throw new ValueExprEvaluationException("Second argument must be a string");
	}
	Resource q = (Resource) args[0];
	boolean useHtml = (args.length == 2) ? ((Literal) args[1]).booleanValue() : false;
	String sparqlString;
	try {
		ParsedOperation op = parser.parse(q, getCurrentQueryPreparer().getTripleSource());
		sparqlString = new SPARQLQueryRenderer().render((ParsedQuery) op);
	} catch (Exception e) {
		throw new ValueExprEvaluationException(e);
	}
	return valueFactory.createLiteral(sparqlString);
}
 
Example #10
Source File: QueryVariableNormalizerTest.java    From rya with Apache License 2.0 6 votes vote down vote up
@Test
public void testSimpleVarGraph() throws Exception {

	SPARQLParser parser1 = new SPARQLParser();
	SPARQLParser parser2 = new SPARQLParser();

	ParsedQuery pq1 = parser1.parseQuery(q22, null);
	ParsedQuery pq2 = parser2.parseQuery(q23, null);

	List<TupleExpr> normalize = QueryVariableNormalizer.getNormalizedIndex(pq1.getTupleExpr(),
			pq2.getTupleExpr());

	Assert.assertTrue(normalize.size() == 1);
	for (TupleExpr s : normalize) {
		Assert.assertTrue(tupleEquals(s, pq1.getTupleExpr()));
	}

}
 
Example #11
Source File: TupleReArrangerTest.java    From rya with Apache License 2.0 6 votes vote down vote up
@Test
public void tupleReArrangeTest4() throws MalformedQueryException {

    String queryString = ""//
            + "SELECT ?a ?b ?c ?d ?e ?x ?y" //
            + "{" //
            + " Filter(?c = <uri:label2>)" //
            + " Filter(?x = <uri:somethingFunny>) "//
            + " Filter(?d = <uri:Fred> ) " //
            + " ?e <uri:laughsAt> ?x ." //
            + " ?e <uri:livesIn> ?y . "//
            + "{ ?a a ?b .  ?a <http://www.w3.org/2000/01/rdf-schema#label> ?c  }"//
            + " UNION { ?a <uri:talksTo> ?d .  ?a <http://www.w3.org/2000/01/rdf-schema#label> ?e  }"//
            + "}";//

    SPARQLParser sp = new SPARQLParser();
    ParsedQuery pq = sp.parseQuery(queryString, null);
    TupleExpr te = pq.getTupleExpr();
    new FilterOptimizer().optimize(te, null, null);
    System.out.println(te);
    List<TupleExpr> tuples = TupleReArranger.getTupleReOrderings(te);
    System.out.println(tuples);

    Assert.assertEquals(24, tuples.size());

}
 
Example #12
Source File: TupleReArrangerTest.java    From rya with Apache License 2.0 6 votes vote down vote up
@Test
public void tupleReArrangeTest3() throws MalformedQueryException {

    String queryString = ""//
            + "SELECT ?a ?b ?c ?d ?e ?x ?y" //
            + "{" //
            + " Filter(?c = <uri:label2>)" //
            + " Filter(?x = <uri:somethingFunny>) "//
            + " ?e <uri:laughsAt> ?x ." //
            + " ?e <uri:livesIn> ?y . "//
            + "{ ?a a ?b .  ?a <http://www.w3.org/2000/01/rdf-schema#label> ?c  }"//
            + " UNION { ?a <uri:talksTo> ?d .  ?a <http://www.w3.org/2000/01/rdf-schema#label> ?e  }"//
            + "}";//

    SPARQLParser sp = new SPARQLParser();
    ParsedQuery pq = sp.parseQuery(queryString, null);
    List<TupleExpr> tuples = TupleReArranger.getTupleReOrderings(pq.getTupleExpr());

    Assert.assertEquals(24, tuples.size());

}
 
Example #13
Source File: SparqlQueryPigEngine.java    From rya with Apache License 2.0 6 votes vote down vote up
public String generatePigScript(final String sparql) throws Exception {
        Preconditions.checkNotNull(sparql, "Sparql query cannot be null");
        final QueryParser parser = new SPARQLParser();
        final ParsedQuery parsedQuery = parser.parseQuery(sparql, null);
        final QueryRoot tupleExpr = new QueryRoot(parsedQuery.getTupleExpr());

//        SimilarVarJoinOptimizer similarVarJoinOptimizer = new SimilarVarJoinOptimizer();
//        similarVarJoinOptimizer.optimize(tupleExpr, null, null);

        if (inference || stats) {
            if (inference) {
                tupleExpr.visit(new TransitivePropertyVisitor(conf, inferenceEngine));
                tupleExpr.visit(new SymmetricPropertyVisitor(conf, inferenceEngine));
                tupleExpr.visit(new InverseOfVisitor(conf, inferenceEngine));
            }
            if (stats) {
                (new QueryJoinOptimizer(rdfCloudTripleStoreEvaluationStatistics)).optimize(tupleExpr, null, null);
            }
        }

        sparqlToPigTransformVisitor.meet(tupleExpr);
        return sparqlToPigTransformVisitor.getPigScript();
    }
 
Example #14
Source File: AntecedentVisitorTest.java    From rya with Apache License 2.0 6 votes vote down vote up
@Test
public void testComplexQuery() throws Exception {
    String text = "PREFIX foaf: <" + FOAF.NAMESPACE + ">\n"
            + "PREFIX ex: <" + EX + ">\n"
            + "SELECT * WHERE {\n"
            + "  { ?x a foaf:Person } UNION {\n"
            + "    GRAPH ex:Graph1 { ?y a foaf:Person }\n"
            + "  } .\n"
            + "  GRAPH ex:Graph2 {\n"
            + "    ?x foaf:knows ?y .\n"
            + "  }\n ."
            + "  OPTIONAL { ?x foaf:mbox ?m } .\n"
            + "  FILTER (?x != ?y) .\n"
            + "}";
    ParsedQuery query = new SPARQLParser().parseQuery(text, null);
    AntecedentVisitor visitor = new AntecedentVisitor();
    query.getTupleExpr().visit(visitor);
    Set<StatementPattern> expected = Sets.newHashSet(
            new StatementPattern(Scope.NAMED_CONTEXTS, new Var("y"), c(RDF.TYPE), c(FOAF.PERSON), c(G1)),
            new StatementPattern(new Var("x"), c(RDF.TYPE), c(FOAF.PERSON)),
            new StatementPattern(Scope.NAMED_CONTEXTS, new Var("x"), c(FOAF.KNOWS), new Var("y"), c(G2)),
            new StatementPattern(new Var("x"), c(FOAF.MBOX), new Var("m")));
    Assert.assertEquals(expected, visitor.getAntecedents());
}
 
Example #15
Source File: QueryJoinOptimizerTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Test
public void testSES2306AggregateOrderBy() throws Exception {
	String select = "PREFIX ex: <ex:>\n" + "SELECT ((MIN(?x+1) + MAX(?y-1))/2 AS ?r) {\n"
			+ "	?this ex:name ?n . ?this ex:id ?id . ?this ex:prop1 ?x . ?this ex:prop2 ?y .\n"
			+ "} GROUP BY concat(?n, ?id) HAVING (SUM(?x) + SUM(?y) < 5) ORDER BY (COUNT(?x) + COUNT(?y))";

	SPARQLParser parser = new SPARQLParser();
	ParsedQuery q = parser.parseQuery(select, null);
	q.getTupleExpr().visit(new AbstractQueryModelVisitor<Exception>() {

		@Override
		protected void meetUnaryTupleOperator(UnaryTupleOperator node) throws Exception {
			assertNotEquals(node, node.getArg());
			super.meetUnaryTupleOperator(node);
		}
	});
}
 
Example #16
Source File: AntecedentVisitorTest.java    From rya with Apache License 2.0 6 votes vote down vote up
@Test
public void testBNodeQuery() throws Exception {
    String text = "PREFIX foaf: <" + FOAF.NAMESPACE + ">\n"
            + "SELECT * WHERE {\n"
            + "  ?x a [ rdfs:subClassOf foaf:Person ] .\n"
            + "  ?x foaf:knows ?y .\n"
            + "}";
    ParsedQuery query = new SPARQLParser().parseQuery(text, null);
    AntecedentVisitor visitor = new AntecedentVisitor();
    query.getTupleExpr().visit(visitor);
    Set<StatementPattern> actual = visitor.getAntecedents();
    Assert.assertEquals(3, actual.size());
    StatementPattern knows = new StatementPattern(new Var("x"), c(FOAF.KNOWS), new Var("y"));
    Assert.assertTrue(actual.remove(knows));
    Assert.assertTrue(actual.removeIf(sp -> {
        return sp.getSubjectVar().equals(new Var("x"))
                && RDF.TYPE.equals(sp.getPredicateVar().getValue())
                && sp.getObjectVar().getValue() == null;
    }));
    Assert.assertTrue(actual.removeIf(sp -> {
        return sp.getSubjectVar().getValue() == null
                && RDFS.SUBCLASSOF.equals(sp.getPredicateVar().getValue())
                && FOAF.PERSON.equals(sp.getObjectVar().getValue());
    }));
}
 
Example #17
Source File: QueryJoinOptimizerTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Test
public void bindSubselectJoinOrder() throws Exception {
	String query = "SELECT * WHERE {\n" + "    BIND (bnode() as ?ct01) \n" + "    { SELECT ?s WHERE {\n"
			+ "            ?s ?p ?o .\n" + "      }\n" + "      LIMIT 10\n" + "    }\n" + "}";

	SPARQLParser parser = new SPARQLParser();
	ParsedQuery q = parser.parseQuery(query, null);
	QueryJoinOptimizer opt = new QueryJoinOptimizer();
	QueryRoot optRoot = new QueryRoot(q.getTupleExpr());
	opt.optimize(optRoot, null, null);

	JoinFinder joinFinder = new JoinFinder();
	optRoot.visit(joinFinder);
	Join join = joinFinder.getJoin();

	assertThat(join.getLeftArg()).as("BIND clause should be left-most argument of join")
			.isInstanceOf(Extension.class);
}
 
Example #18
Source File: ConstructGraphTest.java    From rya with Apache License 2.0 6 votes vote down vote up
@Test
public void testConstructGraph() throws MalformedQueryException, UnsupportedEncodingException {
    String query = "select ?x where { ?x <uri:talksTo> <uri:Bob>. ?y <uri:worksAt> ?z }";

    SPARQLParser parser = new SPARQLParser();
    ParsedQuery pq = parser.parseQuery(query, null);
    List<StatementPattern> patterns = StatementPatternCollector.process(pq.getTupleExpr());
    ConstructGraph graph = new ConstructGraph(patterns);

    QueryBindingSet bs = new QueryBindingSet();
    bs.addBinding("x", VF.createIRI("uri:Joe"));
    bs.addBinding("y", VF.createIRI("uri:Bob"));
    bs.addBinding("z", VF.createIRI("uri:BurgerShack"));
    VisibilityBindingSet vBs = new VisibilityBindingSet(bs,"FOUO");
    Set<RyaStatement> statements = graph.createGraphFromBindingSet(vBs);
    
    RyaStatement statement1 = new RyaStatement(new RyaIRI("uri:Joe"), new RyaIRI("uri:talksTo"), new RyaIRI("uri:Bob"));
    RyaStatement statement2 = new RyaStatement(new RyaIRI("uri:Bob"), new RyaIRI("uri:worksAt"), new RyaIRI("uri:BurgerShack"));
    Set<RyaStatement> expected = Sets.newHashSet(Arrays.asList(statement1, statement2));
    expected.forEach(x-> x.setColumnVisibility("FOUO".getBytes()));
    ConstructGraphTestUtils.ryaStatementSetsEqualIgnoresTimestamp(expected, statements);
}
 
Example #19
Source File: QuerySpecTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Test
public void testReplaceQueryPatternsWithNonEmptyResults() {
	final String expectedQueryPlan = "Join\n" +
			"   Join\n" +
			"      SingletonSet\n" +
			"      SingletonSet\n" +
			"   BindingSetAssignment ([[searchR=urn:1]])\n";
	final ParsedQuery query = parseQuery(QUERY);
	final List<SearchQueryEvaluator> queries = new ArrayList<>();
	new QuerySpecBuilder(true)
			.process(query.getTupleExpr(), EmptyBindingSet.getInstance(), queries);
	assertEquals(1, queries.size());
	QuerySpec querySpec = (QuerySpec) queries.get(0);
	BindingSetAssignment bsa = new BindingSetAssignment();
	bsa.setBindingSets(createBindingSet("searchR", "urn:1"));
	querySpec.replaceQueryPatternsWithResults(bsa);
	String result = querySpec.getParentQueryModelNode().getParentNode().toString().replaceAll("\r\n|\r", "\n");
	assertEquals(expectedQueryPlan, result);
}
 
Example #20
Source File: QueryVariableNormalizerTest.java    From rya with Apache License 2.0 6 votes vote down vote up
/**
 * @throws Exception
 *             Tests QueryVariableNormalizerContext with same query passed
 *             in as query and index. Tests that only one index is produced
 *             and that it equals original query.
 */
@Test
public void testSameTuples() throws Exception {

	SPARQLParser parser1 = new SPARQLParser();
	SPARQLParser parser2 = new SPARQLParser();

	ParsedQuery pq1 = parser1.parseQuery(q11, null);
	ParsedQuery pq2 = parser2.parseQuery(q11, null);

	List<TupleExpr> normalize = QueryVariableNormalizer.getNormalizedIndex(pq1.getTupleExpr(),
			pq2.getTupleExpr());

	Assert.assertTrue(normalize.size() == 1);
	Assert.assertTrue(normalize.get(0).equals(pq1.getTupleExpr()) && normalize.get(0).equals(pq2.getTupleExpr()));

}
 
Example #21
Source File: AntecedentVisitorTest.java    From rya with Apache License 2.0 6 votes vote down vote up
@Test
public void testSelectQuery() throws Exception {
    String text = "PREFIX foaf: <" + FOAF.NAMESPACE + ">\n"
            + "SELECT * WHERE {\n"
            + "  ?x a foaf:Person .\n"
            + "  ?y a foaf:Person .\n"
            + "  ?x foaf:knows ?y .\n"
            + "}";
    ParsedQuery query = new SPARQLParser().parseQuery(text, null);
    AntecedentVisitor visitor = new AntecedentVisitor();
    query.getTupleExpr().visit(visitor);
    Set<StatementPattern> expected = Sets.newHashSet(
            new StatementPattern(new Var("x"), c(RDF.TYPE), c(FOAF.PERSON)),
            new StatementPattern(new Var("y"), c(RDF.TYPE), c(FOAF.PERSON)),
            new StatementPattern(new Var("x"), c(FOAF.KNOWS), new Var("y")));
    Assert.assertEquals(expected, visitor.getAntecedents());
}
 
Example #22
Source File: RyaClientExample.java    From rya with Apache License 2.0 5 votes vote down vote up
private static String[] prettyFormatSparql(final String sparql) throws Exception {
    final SPARQLParser parser = new SPARQLParser();
    final SPARQLQueryRenderer renderer = new SPARQLQueryRenderer();
    final ParsedQuery pq = parser.parseQuery(sparql, null);
    final String prettySparql = renderer.render(pq);
    return StringUtils.split(prettySparql, '\n');
}
 
Example #23
Source File: StatementPatternEvalTest.java    From rya with Apache License 2.0 5 votes vote down vote up
@Test
public void simpleQueryWithBindingSetConstantContext()
        throws MalformedQueryException, QueryEvaluationException, RyaDAOException {
    //query is used to build statement that will be evaluated
    String query = "select ?x ?c where{ graph <uri:context1>  {?x <uri:talksTo> <uri:Bob>. }}";
    SPARQLParser parser = new SPARQLParser();
    ParsedQuery pq = parser.parseQuery(query, null);
    List<StatementPattern> spList = StatementPatternCollector.process(pq.getTupleExpr());
    
    RyaStatement statement1 = new RyaStatement(new RyaIRI("uri:Joe"), new RyaIRI("uri:talksTo"),
            new RyaType("uri:Bob"), new RyaIRI("uri:context1"), "", new StatementMetadata());
    dao.add(statement1);
    
    RyaStatement statement2 = new RyaStatement(new RyaIRI("uri:Doug"), new RyaIRI("uri:talksTo"),
            new RyaType("uri:Bob"), new RyaIRI("uri:context1"), "", new StatementMetadata());
    dao.add(statement2);
    
    RyaStatement statement3 = new RyaStatement(new RyaIRI("uri:Doug"), new RyaIRI("uri:talksTo"),
            new RyaType("uri:Bob"), new RyaIRI("uri:context2"), "", new StatementMetadata());
    dao.add(statement3);

    QueryBindingSet bsConstraint1 = new QueryBindingSet();
    bsConstraint1.addBinding("x", VF.createIRI("uri:Doug"));
    
    CloseableIteration<BindingSet, QueryEvaluationException> iteration = eval.evaluate(spList.get(0), Arrays.asList(bsConstraint1));

    List<BindingSet> bsList = new ArrayList<>();
    while (iteration.hasNext()) {
        bsList.add(iteration.next());
    }

    Assert.assertEquals(1, bsList.size());
    
    QueryBindingSet expected = new QueryBindingSet();
    expected.addBinding("x", VF.createIRI("uri:Doug"));

    Assert.assertEquals(expected, bsList.get(0));
    
    dao.delete(Arrays.asList(statement1, statement2, statement3).iterator(), conf);
}
 
Example #24
Source File: PCJNodeConsolidatorTest.java    From rya with Apache License 2.0 5 votes vote down vote up
@Test
public void testSwitchBoundVars() throws Exception {

	String query1 = ""//
			+ "SELECT ?a ?b " //
			+ "{" //
			+ "  ?a <uri:p0> ?b ." //
			+ " OPTIONAL{ ?a <uri:p1> <uri:o1> } ." //
			+ " ?a <uri:p2> <uri:o2> " //
			+ "}";//

	String query2 = ""//
			+ "SELECT ?a ?b " //
			+ "{" //
			+ " ?a <uri:p2> <uri:o2> " //
			+ " OPTIONAL{ ?a <uri:p1> <uri:o1> } ." //
			+ "  ?a <uri:p0> ?b ." //
			+ "}";//

	SPARQLParser parser = new SPARQLParser();
	ParsedQuery pq1 = parser.parseQuery(query1, null);
	ParsedQuery pq2 = parser.parseQuery(query2, null);
	TupleExpr te1 = pq1.getTupleExpr();
	TupleExpr te2 = pq2.getTupleExpr();
	Join join1 = (Join) ((Projection) te1).getArg();
	Join join2 = (Join) ((Projection) te2).getArg();

	QuerySegment<ExternalTupleSet> seg1 = qFactory.getQuerySegment(join1);
    QuerySegment<ExternalTupleSet> seg2 = qFactory.getQuerySegment(join2);

	QueryNodeConsolidator consolidator = new QueryNodeConsolidator(seg1.getOrderedNodes(), seg2.getOrderedNodes());
	List<QueryModelNode> queryNodes = new ArrayList<>(seg2.getOrderedNodes());

	Assert.assertTrue(consolidator.consolidateNodes());
	Assert.assertEquals(consolidator.getQueryNodes(), queryNodes);
}
 
Example #25
Source File: IndexedExecutionPlanGeneratorTest.java    From rya with Apache License 2.0 5 votes vote down vote up
@Test
public void testThrowsException1() throws Exception {

	SPARQLParser parser = new SPARQLParser();

	ParsedQuery pq1 = parser.parseQuery(q16, null);
	ParsedQuery pq2 = parser.parseQuery(q17, null);
	ParsedQuery pq3 = parser.parseQuery(q18, null);

	SimpleExternalTupleSet extTup1 = new SimpleExternalTupleSet(
			(Projection) pq2.getTupleExpr());
	SimpleExternalTupleSet extTup2 = new SimpleExternalTupleSet(
			(Projection) pq3.getTupleExpr());

	List<ExternalTupleSet> list = new ArrayList<ExternalTupleSet>();

	list.add(extTup2);
	list.add(extTup1);

	IndexedExecutionPlanGenerator iep = new IndexedExecutionPlanGenerator(
			pq1.getTupleExpr(), list);
	List<ExternalTupleSet> indexSet = iep.getNormalizedIndices();
	Assert.assertEquals(6, indexSet.size());

	Iterator<TupleExpr> processedTups = iep.getIndexedTuples();

	boolean exceptionThrown = false;

	try {
		processedTups.remove();
	} catch (UnsupportedOperationException e) {
		exceptionThrown = true;
	}

	Assert.assertTrue(exceptionThrown);

}
 
Example #26
Source File: MongoStatementMetadataNodeIT.java    From rya with Apache License 2.0 5 votes vote down vote up
/**
 * Tests if results are filtered correctly using the metadata properties. In
 * this case, the date for the ingested RyaStatement differs from the date
 * specified in the query.
 */
@Test
public void simpleQueryWithoutBindingSetInvalidProperty() throws Exception {
    final MongoDBRyaDAO dao = new MongoDBRyaDAO();
    try {
        dao.setConf(conf);
        dao.init();

        final StatementMetadata metadata = new StatementMetadata();
        metadata.addMetadata(new RyaIRI("http://createdBy"), new RyaType("Doug"));
        metadata.addMetadata(new RyaIRI("http://createdOn"), new RyaType(XMLSchema.DATE, "2017-02-15"));

        final RyaStatement statement = new RyaStatement(new RyaIRI("http://Joe"), new RyaIRI("http://worksAt"),
                new RyaType("CoffeeShop"), new RyaIRI("http://context"), "", metadata);
        dao.add(statement);

        final SPARQLParser parser = new SPARQLParser();
        final ParsedQuery pq = parser.parseQuery(query, null);
        final List<StatementPattern> spList = StatementPatternCollector.process(pq.getTupleExpr());
        final StatementMetadataNode<MongoDBRdfConfiguration> node = new StatementMetadataNode<>(spList, conf);
        final CloseableIteration<BindingSet, QueryEvaluationException> iteration = node.evaluate(new QueryBindingSet());

        final List<BindingSet> bsList = new ArrayList<>();
        while (iteration.hasNext()) {
            bsList.add(iteration.next());
        }
        Assert.assertEquals(0, bsList.size());
        dao.delete(statement, conf);
    } finally {
        dao.destroy();
    }
}
 
Example #27
Source File: PrecompJoinOptimizerTest2.java    From rya with Apache License 2.0 5 votes vote down vote up
@Test
public void testVarRelableIndexSameSize() throws Exception {

    final SPARQLParser parser1 = new SPARQLParser();
    final SPARQLParser parser2 = new SPARQLParser();

    final ParsedQuery pq1 = parser1.parseQuery(q1, null);
    final ParsedQuery pq2 = parser2.parseQuery(q2, null);

    final SimpleExternalTupleSet extTup = new SimpleExternalTupleSet(
            new Projection(pq2.getTupleExpr()));

    final List<ExternalTupleSet> list = new ArrayList<ExternalTupleSet>();
    list.add(extTup);

    final TupleExpr tup = pq1.getTupleExpr().clone();
    provider.setIndices(list);
    final PCJOptimizer pcj = new PCJOptimizer(list, false, provider);
    pcj.optimize(tup, null, null);

    final Set<StatementPattern> qSet = Sets
            .newHashSet(StatementPatternCollector.process(pq1
                    .getTupleExpr()));
    final Set<QueryModelNode> eTupSet = PcjIntegrationTestingUtil
            .getTupleSets(tup);

    final Set<StatementPattern> set = Sets.newHashSet();
    for (final QueryModelNode s : eTupSet) {
        set.addAll(StatementPatternCollector.process(((ExternalTupleSet) s)
                .getTupleExpr()));
    }

    Assert.assertTrue(set.equals(qSet));

}
 
Example #28
Source File: RdfTestUtil.java    From rya with Apache License 2.0 5 votes vote down vote up
/**
 * Get the first {@link Filter} node from a SPARQL query.
 *
 * @param sparql - The query that contains a single Projection node.
 * @return The first {@link Filter} that is encountered.
 * @throws Exception The query could not be parsed.
 */
public static @Nullable Filter getFilter(final String sparql) throws Exception {
    requireNonNull(sparql);

    final AtomicReference<Filter> filter = new AtomicReference<>();
    final ParsedQuery parsed = new SPARQLParser().parseQuery(sparql, null);
    parsed.getTupleExpr().visit(new AbstractQueryModelVisitor<Exception>() {
        @Override
        public void meet(final Filter node) throws Exception {
            filter.set(node);
        }
    });

    return filter.get();
}
 
Example #29
Source File: AccumuloSelectivityEvalDAOTest.java    From rya with Apache License 2.0 5 votes vote down vote up
private List<StatementPattern> getSpList(String query) throws MalformedQueryException {

        SPARQLParser sp = new SPARQLParser();
        ParsedQuery pq = sp.parseQuery(query, null);
        TupleExpr te = pq.getTupleExpr();

        return StatementPatternCollector.process(te);
    }
 
Example #30
Source File: QueryJoinOptimizerTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private void testOptimizer(String expectedQuery, String actualQuery)
		throws MalformedQueryException, UnsupportedQueryLanguageException {
	ParsedQuery pq = QueryParserUtil.parseQuery(QueryLanguage.SPARQL, actualQuery, null);
	QueryJoinOptimizer opt = new QueryJoinOptimizer();
	QueryRoot optRoot = new QueryRoot(pq.getTupleExpr());
	opt.optimize(optRoot, null, null);

	ParsedQuery expectedParsedQuery = QueryParserUtil.parseQuery(QueryLanguage.SPARQL, expectedQuery, null);
	QueryRoot root = new QueryRoot(expectedParsedQuery.getTupleExpr());
	assertQueryModelTrees(root, optRoot);
}