ruby-rdf / sparql

Ruby SPARQL library
http://rubygems.org/gems/sparql
The Unlicense
89 stars 14 forks source link

Reverse SSE serializer #38

Closed gkellogg closed 2 years ago

gkellogg commented 2 years ago

As discussed in the email thread, which has been discussed elsewhere, it would be useful to be able to turn a SPARQL S-Expression (SSE) back into the SPARQL Grammar. A motivating use case is a query rewriter, which parses SPARQL to SSE (actually, the object representation based on SPARQL Algebra class instances) for easier manipulation, getting back to the SPARQL Grammar. For example:

query = SPARQL.parse 'SELECT ?s WHERE { ?s ?p ?o }'
sxp = query.to_sxp_bin
sxp2 = rewriting(exp) # Using custom query rewriter
grammar = sxp2.to_sparql # the hypothetical method for producing SPARQL

Jena has a mechanism for doing this here.

abrisse commented 2 years ago

To start : https://gist.github.com/abrisse/8f9893549f00e94c25cbe0bea93e532d

danielhz commented 2 years ago

A solution is to add the #to_sparql method in class SPARQL::Algebra::Operator (and its descendants). However, this method is also needed for class RDF::Query. The reason is that these classes have no common superclass (except Object) and that the result of parsing a query can produce both.

sxp1 = SPARQL::Algebra.parse SPARQL.parse('SELECT * WHERE { ?s ?p ?o }').to_sxp
sxp1.class  #=> RDF::Query
sxp1.class.superclass #=> Object

sxp2 = SPARQL::Algebra.parse SPARQL.parse('SELECT ?s WHERE { ?s ?p ?o }').to_sxp
sxp2.class #=> SPARQL::Algebra::Operator::Project
sxp2.class.superclass #=> SPARQL::Algebra::Operator::Binary
sxp2.class.superclass.superclass #=> SPARQL::Algebra::Operator
sxp2.class.superclass.superclass.superclass #=> Object
danielhz commented 2 years ago

To start : https://gist.github.com/abrisse/8f9893549f00e94c25cbe0bea93e532d

Thanks! I will review your code.

gkellogg commented 2 years ago

However, this method is also needed for class RDF::Query. The reason is that these classes have no common superclass (except Object) and that the result of parsing a query can produce both.

yes, there are other classes that need similar methods, which is generally true for classes used in a SPARQL expression.

gkellogg commented 2 years ago

Fairly comprehensive support, at least for simple queries, now on the develop branch.