Hi Martynas,

A string substitution example in Python would be:

runtime_vars = ['https://test', 'https://test2']
template_query = 'VALUES ?this { UNDEF }'
query = template_query.replace(
            "VALUES ?this { UNDEF }", f"VALUES ?this {{ { ' '.join(['<' +
binding + '>' for binding in runtime_vars]) if runtime_vars else 'UNDEF'}
}}"
        )

There's a stub HTTP server which allows saving + substituting queries in
the above format here:
https://github.com/Kurrawong/sparql-template-lib/blob/main/server/api.py,
it uses a lark grammar for SPARQL a colleague wrote and targets the inline
data (VALUES) clauses (see stl/transformers), so it's safer than the string
method. You populate the templates with an "inverted" sparql results JSON
i.e. bindings for the query vars including types rather than results.

I think you could use ParameterizedSparqlString to do something similar
https://jena.apache.org/documentation/javadoc/arq/org.apache.jena.arq/org/apache/jena/query/ParameterizedSparqlString.html#setValues(java.lang.String,java.util.Collection)
. But not sure if you can set the valueName to the token UNDEF

Thanks

On Mon, Nov 25, 2024 at 6:43 PM Martynas Jusevičius <marty...@atomgraph.com>
wrote:

> Hi David,
>
> Yes this would work for me in this case -- I do know the variables so
> I could use UNDEF as placeholders.
>
> Maybe you have a code snippet for this logic? :)
>
> Martynas
>
> On Mon, Nov 25, 2024 at 1:03 AM David Habgood <dcchabg...@gmail.com>
> wrote:
> >
> > Hi Martynas,
> >
> > Do you know ahead of time which variable(s) you're going to be injecting
> > the VALUES clause for?
> >
> > I've been using a pattern where I add VALUES ?this { UNDEF } in
> "template"
> > queries, then at runtime parse the query and replace "UNDEF" (where all
> of
> > the DataBlockValue <
> https://www.w3.org/TR/sparql11-query/#rDataBlockValue>s
> > in a binding within a InlineDataFull are "UNDEF") with a set of bindings
> > supplied at runtime. This has the benefit that if you do not supply a
> > binding for ?this, UNDEF means it is left unbound.
> >
> > Thanks,
> >
> > On Mon, Nov 25, 2024 at 9:40 AM Martynas Jusevičius <
> marty...@atomgraph.com>
> > wrote:
> >
> > > Hi,
> > >
> > > What would be the simplest way to safely (i.e. using query builder or
> > > algebra) to inject a VALUES block at the beginning of a query?
> > >
> > > For example
> > >
> > > SELECT *
> > > {
> > >   ?this ?p ?o
> > > }
> > >
> > > should become
> > >
> > > SELECT *
> > > {
> > >   VALUES ?this <http://localhost>
> > >   ?this ?p ?o
> > > }
> > >
> > > after the injection.
> > >
> > > Thanks,
> > >
> > > Martynas
> > >
>

Reply via email to