2

String qb = "PREFIX dc: <http://purl.org/dc/elements/1.1/>\n" +
                "INSERT DATA\n" +
                "{ \n" +
                "  <http://example/book1> dc:title \"A new book\" ;\n" +
                "                         dc:creator \"A.N.Other\" .\n" +
                "}";

// Here I need to check what type of query I got
String type = ... //some code for checking

if (type == "select") {
   ParsedTupleQuery q = (ParsedTupleQuery)parser.parseQuery(qb, null);
}else if(type == "costruct") {
   ParsedGraphQuery q = (ParsedGraphQuery)parser.parseQuery(qb, null);
}else if(type == "update"){ //here can be insert or delete
   ParsedUpdate q = parser.parseUpdate(qb, null);
}

I can't find a way to find out what type of query it is. Maybe somebody's ever seen it before?

  • Type check can be done by `instanceOf` operator of Java. Moreover, an SPARQL 1.1 Update can contain a sequence of multiple update expressions like `DELETE ...; INSERT ...; ...` - that's why you have to get the list of update expressions with `q.getUpdateExprs()` and for each [`UpdateExpr`](http://docs.rdf4j.org/javadoc/latest/org/eclipse/rdf4j/query/algebra/UpdateExpr.html) you can check which type is it by again using `instanceOf` for all the possible interfaces – UninformedUser May 08 '19 at 11:53
  • Before using a parser, you probably have to check for some keyword in the query string. Indeed you could also use both parsers and catch a parse exception. – UninformedUser May 08 '19 at 12:02
  • Note you have a typo at `if(type == "costruct")` -- should be `"construct"`. – TallTed May 08 '19 at 20:13
  • And also note that string comparison with `==` compares object identity, and two strings with the same characters aren't necessarily the same object. – Joshua Taylor May 15 '19 at 00:50

1 Answers1

2

Rdf4j has a QueryParserUtil with a convenience method for this. You can use it as follows:

ParsedOperation operation = QueryParserUtil.parseOperation(QueryLanguage.SPARQL, qb, null); 
if (operation instanceof ParsedTupleQuery) {
   ParsedTupleQuery q = (ParsedTupleQuery)operation;
   ...
} else if (operation instanceof ParsedGraphQuery) {
   ParsedGraphQuery q = (ParsedGraphQuery)operation;
   ...
} else if (operation instance ParsedUpdate) {
   ParsedUpdate u = (ParsedUpdate)operation;
   ...
}
Jeen Broekstra
  • 21,642
  • 4
  • 51
  • 73
  • Faced with the following problem, when executing this code from the jar library produces the following error: **"No factory available for query language SPARQL"**. Maybe you know what the problem is. – Gevorg Arutiunian May 23 '19 at 10:23