kasei / perlrdf

Deprecated in favor of the Attean package
26 stars 25 forks source link

How to add a custom function in a SPARQL query #170

Closed yayamamo closed 3 years ago

yayamamo commented 3 years ago

Could you add a document that explains how we can register our own function if it is not difficult? For example, a special predicate to bind results of a function I code to a variable ( e.g. BIND(my:function(?x, ?y) AS ?z) ).

kasei commented 3 years ago

I'll add some docs, but in general, you can call RDF::Query->add_function to register a function before the endpoint is started (e.g. at the top of the included endpoint.psgi):

RDF::Query->add_function( 'http://example.org/upper', sub {
    my $query   = shift;
    my $node    = shift;
    my $value   = $node->value;
    return RDF::Query::Node::Literal->new(uc($value));
} );

and use it like this:

PREFIX ex: <http://example.org/>
SELECT * {
    BIND(ex:upper("hello") AS ?x)
}
yayamamo commented 3 years ago

Thank you. I confirmed my customized function works.