RdfStorePrivate::ResultMap RdfStorePrivate::ExecuteTupleQuery(const std::string& query) const { RdfStorePrivate::ResultMap resultMap; const std::string completeQuery = this->PrependPrefixes(query); librdf_query* rdfQuery = librdf_new_query(m_World, "sparql", nullptr, (const unsigned char*) completeQuery.c_str(), nullptr); if (!rdfQuery) return resultMap; librdf_query_results* results = librdf_query_execute(rdfQuery, m_Model); if (!results) { librdf_free_query(rdfQuery); return resultMap; } if (!librdf_query_results_is_bindings(results)) { librdf_free_query_results(results); librdf_free_query(rdfQuery); return resultMap; } while (!librdf_query_results_finished(results)) { int count = librdf_query_results_get_bindings_count(results); for (int i = 0; i < count; ++i) { const char *name = librdf_query_results_get_binding_name(results, i); if (!name) continue; std::string key = name; std::list<RdfNode> list; if(!resultMap[key].empty()) { list = resultMap[key]; } librdf_node *node = librdf_query_results_get_binding_value(results, i); list.push_back(LibRdfNodeToRdfNode(node)); resultMap[key] = list; } librdf_query_results_next(results); } librdf_free_query_results(results); librdf_free_query(rdfQuery); return resultMap; }
/** * @brief Executes the given delete query * @attention DELETE-Statement not supported in Redland, so the Query has to be SELECT with < ?s ?p ?o > statements! * These statements are removed out of the storage. * * * @param query The query to execute. */ bool RDF_ExecDiscardQuery(unsigned char* query) { librdf_query* rdfquery; librdf_query_results* results; rdfquery = librdf_new_query(world, "sparql", NULL, query, NULL); results = librdf_model_query_execute(model, rdfquery); librdf_free_query(rdfquery); //Get all statements from the select query and remove them from storage while(!librdf_query_results_finished(results)) { const char **names = NULL; librdf_node* values[10]; if(librdf_query_results_get_bindings(results, &names, values)) { break; } librdf_node* subject_tmp = values[0]; librdf_node* predicate_tmp = values[1]; librdf_node* object_tmp = values[2]; librdf_statement* statement_tmp = librdf_new_statement_from_nodes(world, subject_tmp, predicate_tmp, object_tmp); librdf_storage_remove_statement(storage, statement_tmp); librdf_free_node(subject_tmp); librdf_free_node(predicate_tmp); librdf_free_node(object_tmp); librdf_free_statement(statement_tmp); int i = 0; for (i = 0; i < 10; i++) { librdf_free_node(values[i]); } librdf_query_results_next(results); free(names); } if (results == NULL) { printf("Failed to execute discard query!\n"); } librdf_free_query_results(results); return true; }
bool RdfStorePrivate::ExecuteBooleanQuery(const std::string& query) const { const std::string completeQuery = this->PrependPrefixes(query); librdf_query* rdfQuery = librdf_new_query(m_World, "sparql", nullptr, (const unsigned char*) completeQuery.c_str(), nullptr); if (!rdfQuery) { mitkThrow() << "failed to create query object"; } librdf_query_results* results = librdf_query_execute(rdfQuery, m_Model); if (!results) { librdf_free_query(rdfQuery); mitkThrow() << "SPARQL syntax error"; } if (!librdf_query_results_is_boolean(results)) { librdf_free_query_results(results); librdf_free_query(rdfQuery); mitkThrow() << "unexpected result type error: tried to request a boolean result with a non-boolean query"; } int rawResult = librdf_query_results_get_boolean(results); bool booleanResult; if (rawResult > 0) { booleanResult = true; } else if (rawResult == 0) { booleanResult = false; } else { mitkThrow() << "error while retrieving result"; } librdf_free_query_results(results); librdf_free_query(rdfQuery); return booleanResult; }
static int query_results(request_rec *r, librdf_world *w, librdf_model *m, char *query) { int ret = 0; librdf_query *q = NULL; librdf_query_results *qr = NULL; if ((q = librdf_new_query(w, "sparql", NULL, (unsigned char *)query, NULL)) != NULL) { if ((qr = librdf_query_execute(q, m)) != NULL) { for (; !librdf_query_results_finished(qr); librdf_query_results_next(qr)); ret = librdf_query_results_get_count(qr); ap_log_rerror(APLOG_MARK, APLOG_WARNING, 0, r, "[ACL] [query] %d results, sparql: %s", ret, query); librdf_free_query_results(qr); } else ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, "librdf_query_execute returned NULL"); librdf_free_query(q); } else ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, "librdf_new_query returned NULL"); return ret; }
/** * @brief Executes the given query and returns the result in the given format. * * * @param query The query to execute. * @param format The format of the result. * * @return The results. */ unsigned char* RDF_ExecQuery(unsigned char* query, unsigned char* format) { librdf_query* rdfquery; librdf_query_results* results; rdfquery = librdf_new_query(world, "sparql", NULL, query, NULL); results = librdf_model_query_execute(model, rdfquery); librdf_serializer* serializer; librdf_stream* stream; serializer = librdf_new_serializer(world, format, NULL, NULL); if(!serializer) { fprintf(stderr, "Failed to create triples serializer for format '%s'\n", format); return NULL; } stream = librdf_query_results_as_stream(results); unsigned char* result = librdf_serializer_serialize_stream_to_string(serializer, NULL, stream); if(!result) { fprintf(stderr, "Failed to turn query results to format '%s'\n", format); return NULL; } librdf_free_query(rdfquery); librdf_free_query_results(results); librdf_free_serializer(serializer); librdf_free_stream(stream); return result; }
SLV2Results slv2_plugin_query_sparql(SLV2Plugin plugin, const char* sparql_str) { slv2_plugin_load_if_necessary(plugin); librdf_uri* base_uri = slv2_value_as_librdf_uri(plugin->plugin_uri); char* query_str = slv2_strjoin(slv2_query_prefixes, sparql_str, NULL); //printf("******** Query \n%s********\n", query_str); librdf_query* query = librdf_new_query(plugin->world->world, "sparql", NULL, (const unsigned char*)query_str, base_uri); if (!query) { fprintf(stderr, "ERROR: Could not create query\n"); return NULL; } // FIXME: locale kludges to work around librdf bug char* locale = strdup(setlocale(LC_NUMERIC, NULL)); setlocale(LC_NUMERIC, "POSIX"); librdf_query_results* results = librdf_query_execute(query, plugin->rdf); setlocale(LC_NUMERIC, locale); free(locale); librdf_free_query(query); free(query_str); SLV2Results ret = (SLV2Results)malloc(sizeof(struct _SLV2Results)); ret->world = plugin->world; ret->rdf_results = results; return ret; }
UT_Error IE_Imp_OpenDocument::_handleRDFStreams () { #ifndef WITH_REDLAND return UT_OK; #else UT_Error error = UT_OK; UT_DEBUGMSG(("IE_Imp_OpenDocument::_handleRDFStreams()\n")); // // DEBUG. // { // PD_DocumentRDFHandle rdf = getDoc()->getDocumentRDF(); // PD_DocumentRDFMutationHandle m = rdf->createMutation(); // m->add( PD_URI("http://www.example.com/foo#bar" ), // PD_URI("http://www.example.com/foo#bar" ), // PD_Object("http://www.example.com/foo#bar" ) ); // m->commit(); // rdf->dumpModel("added foo"); // } RDFArguments args; librdf_model* model = args.model; // check if we can load a manifest.rdf file GsfInput* pRdfManifest = gsf_infile_child_by_name(m_pGsfInfile, "manifest.rdf"); if (pRdfManifest) { UT_DEBUGMSG(("IE_Imp_OpenDocument::_handleRDFStreams() have manifest.rdf\n")); error = _loadRDFFromFile( pRdfManifest, "manifest.rdf", &args ); g_object_unref (G_OBJECT (pRdfManifest)); if (error != UT_OK) return error; } // find other RDF/XML files referenced in the manifest const char* query_string = "" "prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> \n" "prefix odf: <http://docs.oasis-open.org/opendocument/meta/package/odf#> \n" "prefix odfcommon: <http://docs.oasis-open.org/opendocument/meta/package/common#> \n" "select ?subj ?fileName \n" " where { \n" " ?subj rdf:type odf:MetaDataFile . \n" " ?subj odfcommon:path ?fileName \n" " } \n"; librdf_uri* base_uri = 0; librdf_query* query = librdf_new_query( args.world, "sparql", 0, (unsigned char*)query_string, base_uri ); librdf_query_results* results = librdf_query_execute( query, model ); if( !results ) { // Query failed is a failure to execute the SPARQL, // in which case there might be results but we couldn't find them UT_DEBUGMSG(("IE_Imp_OpenDocument::_handleRDFStreams() SPARQL query to find auxillary RDF/XML files failed! q:%p\n", query )); error = UT_ERROR; } else { UT_DEBUGMSG(("IE_Imp_OpenDocument::_handleRDFStreams() aux RDF/XML file count:%d\n", librdf_query_results_get_count( results ))); // parse auxillary RDF/XML files too for( ; !librdf_query_results_finished( results ) ; librdf_query_results_next( results )) { librdf_node* fnNode = librdf_query_results_get_binding_value_by_name ( results, "fileName" ); UT_DEBUGMSG(("_handleRDFStreams() fnNode:%p\n", fnNode )); std::string fn = toString(fnNode); UT_DEBUGMSG(("_handleRDFStreams() loading auxilary RDF/XML file from:%s\n", fn.c_str())); GsfInput* pAuxRDF = gsf_infile_child_by_name(m_pGsfInfile, fn.c_str()); if (pAuxRDF) { error = _loadRDFFromFile( pAuxRDF, fn.c_str(), &args ); g_object_unref (G_OBJECT (pAuxRDF)); if( error != UT_OK ) break; } else { UT_ASSERT_HARMLESS(UT_SHOULD_NOT_HAPPEN); return UT_ERROR; } } librdf_free_query_results( results ); } librdf_free_query( query ); UT_DEBUGMSG(("_handleRDFStreams() error:%d model.sz:%d\n", error, librdf_model_size( model ))); if( error != UT_OK ) { return error; } // convert the redland model into native AbiWord RDF triples { PD_DocumentRDFHandle rdf = getDoc()->getDocumentRDF(); PD_DocumentRDFMutationHandle m = rdf->createMutation(); librdf_statement* statement = librdf_new_statement( args.world ); librdf_stream* stream = librdf_model_find_statements( model, statement ); while (!librdf_stream_end(stream)) { librdf_statement* current = librdf_stream_get_object( stream ); int objectType = PD_Object::OBJECT_TYPE_URI; std::string xsdType = ""; if( librdf_node_is_blank( librdf_statement_get_object( current ))) { objectType = PD_Object::OBJECT_TYPE_BNODE; } if( librdf_node_is_literal( librdf_statement_get_object( current ))) { objectType = PD_Object::OBJECT_TYPE_LITERAL; if( librdf_uri* u = librdf_node_get_literal_value_datatype_uri( librdf_statement_get_object( current ))) { xsdType = toString(u); } } if( DEBUG_RDF_IO ) { UT_DEBUGMSG(("_handleRDFStreams() adding s:%s p:%s o:%s rotv:%d otv:%d ots:%s\n", toString( librdf_statement_get_subject( current )).c_str(), toString( librdf_statement_get_predicate( current )).c_str(), toString( librdf_statement_get_object( current )).c_str(), librdf_node_get_type(librdf_statement_get_object( current )), objectType, xsdType.c_str() )); } m->add( PD_URI( toString( librdf_statement_get_subject( current ))), PD_URI( toString( librdf_statement_get_predicate( current ))), PD_Object( toString( librdf_statement_get_object( current )), objectType, xsdType )); // m->add( PD_URI( toString( librdf_statement_get_subject( current ))), // PD_URI( toString( librdf_statement_get_predicate( current ))), // PD_Object( toString( librdf_statement_get_object( current )), // objectType, // xsdType )); librdf_stream_next(stream); } librdf_free_stream( stream ); librdf_free_statement( statement ); // m->add( PD_URI("http://www.example.com/foo#bar" ), // PD_URI("http://www.example.com/foo#bar" ), // PD_Object("http://www.example.com/foo#bar" ) ); m->commit(); } if( DEBUG_RDF_IO ) { getDoc()->getDocumentRDF()->dumpModel("Loaded RDF from ODF file"); } return error; #endif }
static int validate_webid(request_rec *request, const char *subjAltName, char *pkey_n, unsigned int pkey_e_i) { int r = HTTP_UNAUTHORIZED; librdf_world *rdf_world = NULL; librdf_storage *rdf_storage = NULL; librdf_model *rdf_model = NULL; librdf_query *rdf_query = NULL; librdf_query_results *rdf_query_results = NULL; rdf_world = librdf_new_world(); if (rdf_world != NULL) { librdf_world_open(rdf_world); librdf_world_set_logger(rdf_world, (void *)request, ap_rdf_log_proxy); rdf_storage = librdf_new_storage(rdf_world, "uri", subjAltName, NULL); if (rdf_storage != NULL) { rdf_model = librdf_new_model(rdf_world, rdf_storage, NULL); } else ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, request, "WebID: librdf_new_storage returned NULL"); } if (rdf_model != NULL) { char *c_query = apr_psprintf(request->pool, SPARQL_WEBID, subjAltName); ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, request, "WebID: SPARQL query = %s", c_query); rdf_query = librdf_new_query(rdf_world, "sparql", NULL, (unsigned char*)c_query, NULL); } else { ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, request, "WebID: librdf_new_query returned NULL"); } if (rdf_query != NULL) { rdf_query_results = librdf_query_execute(rdf_query, rdf_model); if (rdf_query_results != NULL) { for (; r != OK && librdf_query_results_finished(rdf_query_results)==0; librdf_query_results_next(rdf_query_results)) { librdf_node *m_node, *e_node; unsigned char *rdf_mod; unsigned char *rdf_exp; if (r != OK && NULL != (m_node = librdf_query_results_get_binding_value_by_name(rdf_query_results, "m")) && NULL != (e_node = librdf_query_results_get_binding_value_by_name(rdf_query_results, "e"))) { if (librdf_node_get_type(m_node) == LIBRDF_NODE_TYPE_LITERAL && librdf_node_get_type(e_node) == LIBRDF_NODE_TYPE_LITERAL) { rdf_mod = librdf_node_get_literal_value(m_node); rdf_exp = librdf_node_get_literal_value(e_node); ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, request, "WebID: modulus = %s", rdf_mod); ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, request, "WebID: exponent = %s", rdf_exp); if (rdf_exp != NULL && apr_strtoi64((char*)rdf_exp, NULL, 10) == pkey_e_i && matches_pkey(rdf_mod, pkey_n)) r = OK; librdf_free_node(m_node); librdf_free_node(e_node); } } } librdf_free_query_results(rdf_query_results); } else ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, request, "WebID: librdf_query_execute returned NULL"); librdf_free_query(rdf_query); } else ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, request, "WebID: librdf_new_query returned NULL"); if (rdf_model) librdf_free_model(rdf_model); if (rdf_storage) librdf_free_storage(rdf_storage); if (rdf_world) librdf_free_world(rdf_world); return r; }
void run_query(librdf_world* world, librdf_model* model, const std::string& q) { librdf_stream* strm; std::cout << "** Query: " << q << std::endl; librdf_uri* uri1 = librdf_new_uri(world, (const unsigned char*) "http://bunchy.org"); if (uri1 == 0) throw std::runtime_error("Couldn't parse URI"); librdf_uri* uri2 = librdf_new_uri(world, (const unsigned char*) "http://bunchy.org"); if (uri2 == 0) throw std::runtime_error("Couldn't parse URI"); librdf_query* qry = librdf_new_query(world, "sparql", uri1, (const unsigned char*) q.c_str(), uri2); librdf_free_uri(uri1); librdf_free_uri(uri2); if (qry == 0) throw std::runtime_error("Couldn't parse query."); librdf_query_results* results = librdf_query_execute(qry, model); if (results == 0) throw std::runtime_error("Couldn't execute query"); librdf_free_query(qry); strm = librdf_query_results_as_stream(results); if (strm == 0) throw std::runtime_error("Couldn't stream results"); librdf_serializer* srl = librdf_new_serializer(world, "ntriples", 0, 0); if (srl == 0) throw std::runtime_error("Couldn't create serialiser"); size_t len; unsigned char* out = librdf_serializer_serialize_stream_to_counted_string(srl, 0, strm, &len); std::cout << "--------------------------------------------------------" << std::endl; write(1, out, len); std::cout << "--------------------------------------------------------" << std::endl; free(out); librdf_free_serializer(srl); librdf_free_stream(strm); librdf_free_query_results(results); }
void run_query2(librdf_world* world, librdf_model* model, const std::string& q) { librdf_stream* strm; std::cout << "** Query: " << q << std::endl; librdf_uri* uri1 = librdf_new_uri(world, (const unsigned char*) "http://bunchy.org"); if (uri1 == 0) throw std::runtime_error("Couldn't parse URI"); librdf_uri* uri2 = librdf_new_uri(world, (const unsigned char*) "http://bunchy.org"); if (uri2 == 0) throw std::runtime_error("Couldn't parse URI"); librdf_query* qry = librdf_new_query(world, "sparql", uri1, (const unsigned char*) q.c_str(), uri2); librdf_free_uri(uri1); librdf_free_uri(uri2); if (qry == 0) throw std::runtime_error("Couldn't parse query."); librdf_query_results* results = librdf_query_execute(qry, model); if (results == 0) throw std::runtime_error("Couldn't execute query"); librdf_free_query(qry); std::cout << "--------------------------------------------------------" << std::endl; while (true) { if (librdf_query_results_finished(results)) break; int bcount = librdf_query_results_get_bindings_count(results); if (bcount < 0) throw std::runtime_error("Couldn't get query bindings count"); for(int i = 0; i < bcount; i++) { if (i != 0) std::cout << " "; librdf_node* value = librdf_query_results_get_binding_value(results, i); if (value == 0) throw std::runtime_error("Couldn't get results binding"); output_node(value); librdf_free_node(value); } std::cout << std::endl; librdf_query_results_next(results); } std::cout << "--------------------------------------------------------" << std::endl; librdf_free_query_results(results); }
int main(int argc, char *argv[]) { librdf_world* world; librdf_parser* parser; librdf_serializer* serializer; librdf_storage *storage; librdf_model* model; librdf_node *source, *arc, *target, *node; librdf_node *subject, *predicate, *object; librdf_node* context_node=NULL; librdf_stream* stream; librdf_iterator* iterator; librdf_uri *uri; librdf_uri *base_uri=NULL; librdf_query *query; librdf_query_results *results; librdf_hash *options; int count; int rc; int transactions=0; const char* storage_name; const char* storage_options; const char* context; const char* identifier; const char* results_format; librdf_statement* statement=NULL; char* query_cmd=NULL; char* s; /* * Initialize */ storage_name="virtuoso"; results_format="xml"; context=DEFAULT_CONTEXT; identifier=DEFAULT_IDENTIFIER; /* * Get connection options */ if(argc == 2 && argv[1][0] != '\0') storage_options=argv[1]; else if((s=getenv ("VIRTUOSO_STORAGE_OPTIONS")) != NULL) storage_options=s; else storage_options=DEFAULT_STORAGE_OPTIONS; world=librdf_new_world(); librdf_world_set_logger(world, world, log_handler); librdf_world_open(world); options=librdf_new_hash(world, NULL); librdf_hash_open(options, NULL, 0, 1, 1, NULL); librdf_hash_put_strings(options, "contexts", "yes"); transactions=1; librdf_hash_from_string(options, storage_options); storage=librdf_new_storage_with_options(world, storage_name, identifier, options); if(!storage) { fprintf(stderr, ": Failed to open %s storage '%s'\n", storage_name, identifier); return(1); } model=librdf_new_model(world, storage, NULL); if(!model) { fprintf(stderr, ": Failed to create model\n"); return(1); } if(transactions) librdf_model_transaction_start(model); /* Do this or gcc moans */ stream=NULL; iterator=NULL; parser=NULL; serializer=NULL; source=NULL; arc=NULL; target=NULL; subject=NULL; predicate=NULL; object=NULL; uri=NULL; node=NULL; query=NULL; results=NULL; context_node=librdf_new_node_from_uri_string(world, (const unsigned char *)context); /**** Test 1 *******/ startTest(1, " Remove all triples in <%s> context\n", context); { rc=librdf_model_context_remove_statements(model, context_node); if(rc) endTest(0, " failed to remove context triples from the graph\n"); else endTest(1, " removed context triples from the graph\n"); } /**** Test 2 *******/ startTest(2, " Add triples to <%s> context\n", context); { rc=0; rc |= add_triple(world, context_node, model, "aa", "bb", "cc"); rc |= add_triple(world, context_node, model, "aa", "bb1", "cc"); rc |= add_triple(world, context_node, model, "aa", "a2", "_:cc"); rc |= add_triple_typed(world, context_node, model, "aa", "a2", "cc"); rc |= add_triple_typed(world, context_node, model, "mm", "nn", "Some long literal with language@en"); rc |= add_triple_typed(world, context_node, model, "oo", "pp", "12345^^<http://www.w3.org/2001/XMLSchema#int>"); if(rc) endTest(0, " failed add triple\n"); else endTest(1, " add triple to context\n"); } /**** Test 3 *******/ startTest(3, " Print all triples in <%s> context\n", context); { raptor_iostream* iostr = raptor_new_iostream_to_file_handle(librdf_world_get_raptor(world), stdout); librdf_model_write(model, iostr); raptor_free_iostream(iostr); endTest(1, "\n"); } /***** Test 4 *****/ startTest(4, " Count of triples in <%s> context\n", context); { count=librdf_model_size(model); if(count >= 0) endTest(1, " graph has %d triples\n", count); else endTest(0, " graph has unknown number of triples\n"); } /***** Test 5 *****/ startTest(5, " Exec: ARC aa bb \n"); { subject=librdf_new_node_from_uri_string(world, (const unsigned char*)"aa"); predicate=librdf_new_node_from_uri_string(world, (const unsigned char*)"bb"); node=librdf_model_get_target(model, subject, predicate); librdf_free_node(subject); librdf_free_node(predicate); if(!node) { endTest(0, " Failed to get arc\n"); } else { print_node(stdout, node); librdf_free_node(node); endTest(1, "\n"); } } /***** Test 6 *****/ startTest(6, " Exec: ARCS aa cc \n"); { subject=librdf_new_node_from_uri_string(world, (const unsigned char*)"aa"); object=librdf_new_node_from_uri_string(world, (const unsigned char*)"cc"); iterator=librdf_model_get_arcs(model, subject, object); librdf_free_node(subject); librdf_free_node(object); if(!iterator) { endTest(0, " Failed to get arcs\n"); } else { print_nodes(stdout, iterator); endTest(1, "\n"); } } /***** Test 7 *****/ startTest(7, " Exec: ARCS-IN cc \n"); { object=librdf_new_node_from_uri_string(world, (const unsigned char*)"cc"); iterator=librdf_model_get_arcs_in(model, object); librdf_free_node(object); if(!iterator) { endTest(0, " Failed to get arcs in\n"); } else { int ok=1; count=0; while(!librdf_iterator_end(iterator)) { context_node=(librdf_node*)librdf_iterator_get_context(iterator); node=(librdf_node*)librdf_iterator_get_object(iterator); /*returns SHARED pointer */ if(!node) { ok=0; endTest(ok, " librdf_iterator_get_next returned NULL\n"); break; } fputs("Matched arc: ", stdout); librdf_node_print(node, stdout); if(context_node) { fputs(" with context ", stdout); librdf_node_print(context_node, stdout); } fputc('\n', stdout); count++; librdf_iterator_next(iterator); } librdf_free_iterator(iterator); endTest(ok, " matching arcs: %d\n", count); } } /***** Test 8 *****/ startTest(8, " Exec: ARCS-OUT aa \n"); { subject=librdf_new_node_from_uri_string(world, (const unsigned char*)"aa"); iterator=librdf_model_get_arcs_out(model, subject); librdf_free_node(subject); if(!iterator) endTest(0, " Failed to get arcs out\n"); else { int ok=1; count=0; while(!librdf_iterator_end(iterator)) { context_node=(librdf_node*)librdf_iterator_get_context(iterator); node=(librdf_node*)librdf_iterator_get_object(iterator); if(!node) { ok=0; endTest(ok, " librdf_iterator_get_next returned NULL\n"); break; } fputs("Matched arc: ", stdout); librdf_node_print(node, stdout); if(context_node) { fputs(" with context ", stdout); librdf_node_print(context_node, stdout); } fputc('\n', stdout); count++; librdf_iterator_next(iterator); } librdf_free_iterator(iterator); endTest(ok, " matching arcs: %d\n", count); } } /***** Test 9 *****/ startTest(9, " Exec: CONTAINS aa bb1 cc \n"); { subject=librdf_new_node_from_uri_string(world, (const unsigned char*)"aa"); predicate=librdf_new_node_from_uri_string(world, (const unsigned char*)"bb1"); object=librdf_new_node_from_uri_string(world, (const unsigned char*)"cc"); statement=librdf_new_statement(world); librdf_statement_set_subject(statement, subject); librdf_statement_set_predicate(statement, predicate); librdf_statement_set_object(statement, object); if(librdf_model_contains_statement(model, statement)) endTest(1, " the graph contains the triple\n"); else endTest(0, " the graph does not contain the triple\n"); librdf_free_statement(statement); } /***** Test 10 *****/ startTest(10, " Exec: FIND aa - - \n"); { subject=librdf_new_node_from_uri_string(world, (const unsigned char*)"aa"); statement=librdf_new_statement(world); librdf_statement_set_subject(statement, subject); stream=librdf_model_find_statements_in_context(model, statement, context_node); if(!stream) { endTest(0, " FIND returned no results (NULL stream)\n"); } else { librdf_node* ctxt_node=NULL; int ok=1; count=0; while(!librdf_stream_end(stream)) { librdf_statement *stmt=librdf_stream_get_object(stream); ctxt_node=(librdf_node*)librdf_stream_get_context(stream); if(!stmt) { ok=0; endTest(ok, " librdf_stream_next returned NULL\n"); break; } fputs("Matched triple: ", stdout); librdf_statement_print(stmt, stdout); if(context) { fputs(" with context ", stdout); librdf_node_print(ctxt_node, stdout); } fputc('\n', stdout); count++; librdf_stream_next(stream); } librdf_free_stream(stream); endTest(ok, " matching triples: %d\n", count); } librdf_free_statement(statement); } /***** Test 11 *****/ startTest(11, " Exec: HAS-ARC-IN cc bb \n"); { predicate=librdf_new_node_from_uri_string(world, (const unsigned char*)"bb"); object=librdf_new_node_from_uri_string(world, (const unsigned char*)"cc"); if(librdf_model_has_arc_in(model, object, predicate)) endTest(1, " the graph contains the arc\n"); else endTest(0, " the graph does not contain the arc\n"); librdf_free_node(predicate); librdf_free_node(object); } /***** Test 12 *****/ startTest(12, " Exec: HAS-ARC-OUT aa bb \n"); { subject=librdf_new_node_from_uri_string(world, (const unsigned char*)"aa"); predicate=librdf_new_node_from_uri_string(world, (const unsigned char*)"bb"); if(librdf_model_has_arc_out(model, subject, predicate)) endTest(1, " the graph contains the arc\n"); else endTest(0, " the graph does not contain the arc\n"); librdf_free_node(predicate); librdf_free_node(subject); } /***** Test 13 *****/ startTest(13, " Exec: SOURCE aa cc \n"); { predicate=librdf_new_node_from_uri_string(world, (const unsigned char*)"bb"); object=librdf_new_node_from_uri_string(world, (const unsigned char*)"cc"); node=librdf_model_get_source(model, predicate, object); librdf_free_node(predicate); librdf_free_node(object); if(!node) { endTest(0, " Failed to get source\n"); } else { print_node(stdout, node); librdf_free_node(node); endTest(1, "\n"); } } /***** Test 14 *****/ startTest(14, " Exec: SOURCES bb cc \n"); { predicate=librdf_new_node_from_uri_string(world, (const unsigned char*)"bb"); object=librdf_new_node_from_uri_string(world, (const unsigned char*)"cc"); iterator=librdf_model_get_sources(model, predicate, object); librdf_free_node(predicate); librdf_free_node(object); if(!iterator) { endTest(0, " Failed to get sources\n"); } else { print_nodes(stdout, iterator); endTest(1, "\n"); } } /***** Test 15 *****/ startTest(15, " Exec: TARGET aa bb \n"); { subject=librdf_new_node_from_uri_string(world, (const unsigned char*)"aa"); predicate=librdf_new_node_from_uri_string(world, (const unsigned char*)"bb"); node=librdf_model_get_target(model, subject, predicate); librdf_free_node(subject); librdf_free_node(predicate); if(!node) { endTest(0, " Failed to get target\n"); } else { print_node(stdout, node); librdf_free_node(node); endTest(1, "\n"); } } /***** Test 16 *****/ startTest(16, " Exec: TARGETS aa bb \n"); { subject=librdf_new_node_from_uri_string(world, (const unsigned char*)"aa"); predicate=librdf_new_node_from_uri_string(world, (const unsigned char*)"bb"); iterator=librdf_model_get_targets(model, subject, predicate); librdf_free_node(subject); librdf_free_node(predicate); if(!iterator) { endTest(0, " Failed to get targets\n"); } else { print_nodes(stdout, iterator); endTest(1, "\n"); } } /***** Test 17 *****/ startTest(17, " Exec: REMOVE aa bb1 cc \n"); { subject=librdf_new_node_from_uri_string(world, (const unsigned char*)"aa"); predicate=librdf_new_node_from_uri_string(world, (const unsigned char*)"bb1"); object=librdf_new_node_from_uri_string(world, (const unsigned char*)"cc"); statement=librdf_new_statement(world); librdf_statement_set_subject(statement, subject); librdf_statement_set_predicate(statement, predicate); librdf_statement_set_object(statement, object); if(librdf_model_context_remove_statement(model, context_node, statement)) endTest(0, " failed to remove triple from the graph\n"); else endTest(1, " removed triple from the graph\n"); librdf_free_statement(statement); } /***** Test 18 *****/ query_cmd=(char *)"CONSTRUCT {?s ?p ?o} FROM <http://red> WHERE {?s ?p ?o}"; startTest(18, " Exec: QUERY \"%s\" \n", query_cmd); { query=librdf_new_query(world, (char *)"vsparql", NULL, (const unsigned char *)query_cmd, NULL); if(!(results=librdf_model_query_execute(model, query))) { endTest(0, " Query of model with '%s' failed\n", query_cmd); librdf_free_query(query); query=NULL; } else { stream=librdf_query_results_as_stream(results); if(!stream) { endTest(0, " QUERY returned no results (NULL stream)\n"); } else { librdf_node* ctxt=NULL; count=0; while(!librdf_stream_end(stream)) { librdf_statement *stmt=librdf_stream_get_object(stream); /*returns SHARED pointer */ ctxt=(librdf_node*)librdf_stream_get_context(stream); if(!stmt) { endTest(0, " librdf_stream_next returned NULL\n"); break; } fputs("Matched triple: ", stdout); librdf_statement_print(stmt, stdout); if(ctxt) { fputs(" with context ", stdout); librdf_node_print(ctxt, stdout); } fputc('\n', stdout); count++; librdf_stream_next(stream); } librdf_free_stream(stream); endTest(1, " matching triples: %d\n", count); librdf_free_query_results(results); } } librdf_free_query(query); } /***** Test 19 *****/ query_cmd=(char *)"SELECT * WHERE {graph <http://red> { ?s ?p ?o }}"; startTest(19, " Exec1: QUERY_AS_BINDINGS \"%s\" \n", query_cmd); { query=librdf_new_query(world, (char *)"vsparql", NULL, (const unsigned char *)query_cmd, NULL); if(!(results=librdf_model_query_execute(model, query))) { endTest(0, " Query of model with '%s' failed\n", query_cmd); librdf_free_query(query); query=NULL; } else { raptor_iostream *iostr; librdf_query_results_formatter *formatter; fprintf(stderr, "**: Formatting query result as '%s':\n", results_format); iostr = raptor_new_iostream_to_file_handle(librdf_world_get_raptor(world), stdout); formatter = librdf_new_query_results_formatter2(results, results_format, NULL /* mime type */, NULL /* format_uri */); base_uri = librdf_new_uri(world, (const unsigned char*)"http://example.org/"); librdf_query_results_formatter_write(iostr, formatter, results, base_uri); librdf_free_query_results_formatter(formatter); raptor_free_iostream(iostr); librdf_free_uri(base_uri); endTest(1, "\n"); librdf_free_query_results(results); } librdf_free_query(query); } /***** Test 20 *****/ query_cmd=(char *)"SELECT * WHERE {graph <http://red> { ?s ?p ?o }}"; startTest(20, " Exec2: QUERY_AS_BINDINGS \"%s\" \n", query_cmd); { query=librdf_new_query(world, (char *)"vsparql", NULL, (const unsigned char *)query_cmd, NULL); if(!(results=librdf_model_query_execute(model, query))) { endTest(0, " Query of model with '%s' failed\n", query_cmd); librdf_free_query(query); query=NULL; } else { if(print_query_results(world, model, results)) endTest(0, "\n"); else endTest(1, "\n"); librdf_free_query_results(results); } librdf_free_query(query); } getTotal(); if(transactions) librdf_model_transaction_commit(model); librdf_free_node(context_node); librdf_free_node(context_node); librdf_free_hash(options); librdf_free_model(model); librdf_free_storage(storage); librdf_free_world(world); #ifdef LIBRDF_MEMORY_DEBUG librdf_memory_report(stderr); #endif /* keep gcc -Wall happy */ return(0); }
/* * call-seq: * graph.execute_query( qstring, language=:sparql, limit=nil, offset=nil ) -> queryresult * * Run the query in the given query string (+qstring+) against the graph. The query +language+ * specifies the query language, and +limit+, and +offset+ can be used to limit the results. The * #query method is the public interface to this method. * */ static VALUE rleaf_redleaf_graph_execute_query( int argc, VALUE *argv, VALUE self ) { rleaf_GRAPH *ptr = rleaf_get_graph( self ); VALUE qstring, language, limit, offset, base; const char *qlang_name = NULL; librdf_uri *qlang_uri = NULL, *base_uri = NULL; librdf_query *query; librdf_query_results *res; rb_scan_args( argc, argv, "14", &qstring, &language, &limit, &offset, &base ); rleaf_log_with_context( self, "debug", "Executing query=%s (%s) with offset=%s, limit=%s, and base=%s", RSTRING_PTR(rb_inspect( qstring )), RSTRING_PTR(rb_inspect( language )), RSTRING_PTR(rb_inspect( limit )), RSTRING_PTR(rb_inspect( offset )), RSTRING_PTR(rb_inspect( base )) ); /* Set the query language, from a URI or a language name string */ if ( RTEST(language) && IsURI(language) ) qlang_uri = rleaf_object_to_librdf_uri( language ); else if ( language != Qnil ) { VALUE langstring = rb_obj_as_string( language ); qlang_name = (const char *)(RSTRING_PTR(langstring)); } /* Set the baseuri if one is specified */ if ( RTEST(base) ) { VALUE basestr = rb_obj_as_string( base ); base_uri = librdf_new_uri( rleaf_rdf_world, (const unsigned char *)(RSTRING_PTR(basestr)) ); if ( !base_uri ) { if ( qlang_uri ) librdf_free_uri( qlang_uri ); rb_raise( rleaf_eRedleafError, "Couldn't make a librdf_uri out of %s", RSTRING_PTR(basestr) ); } } /* Make the query object */ rleaf_log_with_context( self, "debug", " creating a new '%s' query: %s", qlang_name, RSTRING_PTR(qstring) ); query = librdf_new_query( rleaf_rdf_world, qlang_name, qlang_uri, (unsigned char *)(StringValuePtr(qstring)), base_uri ); if ( !query ) { if ( qlang_uri ) librdf_free_uri( qlang_uri ); if ( base_uri ) librdf_free_uri( base_uri ); rb_raise( rleaf_eRedleafError, "Failed to create query %s", RSTRING_PTR(qstring) ); } /* Check for a non-nil limit and offset, setting them in the query object if they exist. */ if ( RTEST(limit) ) { rleaf_log_with_context( self, "debug", " setting limit to %d", FIX2INT(limit) ); librdf_query_set_limit( query, FIX2INT(limit) ); } if ( RTEST(offset) ) { rleaf_log_with_context( self, "debug", " setting offset to %d", FIX2INT(offset) ); librdf_query_set_offset( query, FIX2INT(offset) ); } /* Run the query against the model */ rleaf_log_with_context( self, "debug", " executing query <%p> against model <%p>", query, ptr->model ); res = librdf_model_query_execute( ptr->model, query ); if ( qlang_uri ) librdf_free_uri( qlang_uri ); if ( base_uri ) librdf_free_uri( base_uri ); if ( !res ) rb_raise( rleaf_eRedleafError, "Execution of query failed." ); rleaf_log_with_context( self, "debug", " creating result" ); return rleaf_new_queryresult( self, res ); }