/// <summary> /// Saves a graph to the store. /// </summary> /// <param name="g">Graph to save.</param> public override void SaveGraph(IGraph g) { StringBuilder updates = new StringBuilder(); // Saving a Graph ovewrites a previous graph so start with a CLEAR SILENT GRAPH if (g.BaseUri == null) { updates.AppendLine("CLEAR SILENT DEFAULT;"); } else { updates.AppendLine("CLEAR SILENT GRAPH <" + _formatter.FormatUri(g.BaseUri) + ">;"); } // Insert preamble // Note that we use INSERT { } WHERE { } rather than INSERT DATA { } so we can insert blank nodes if (g.BaseUri != null) { updates.AppendLine("WITH <" + _formatter.FormatUri(g.BaseUri) + ">"); } updates.AppendLine("INSERT"); updates.AppendLine("{"); // Serialize triples foreach (Triple t in g.Triples) { updates.AppendLine(" " + _formatter.Format(t)); } // End updates.AppendLine("} WHERE { }"); // Save the graph Update(updates.ToString()); }
/// <summary> /// Returns the actual Query/Update String with parameter and variable values inserted /// </summary> /// <returns></returns> public override string ToString() { StringBuilder output = new StringBuilder(); // First prepend Base declaration if (BaseUri != null) { output.AppendLine("BASE <" + _formatter.FormatUri(BaseUri) + ">"); } // Next prepend any Namespace Declarations foreach (String prefix in _nsmap.Prefixes) { output.AppendLine("PREFIX " + prefix + ": <" + _formatter.FormatUri(_nsmap.GetNamespaceUri(prefix)) + ">"); } // Then append the text with variable and parameters replaced by their values if set INode value = null; for (int i = 0, l = _commandText.Count; i < l; i++) { String segment = _commandText[i]; switch (segment[0]) { case '@': String paramName = segment.Substring(1); _parameters.TryGetValue(paramName, out value); if (value != null) { output.Append(_formatter.Format(value)); } else { output.Append(segment); } break; case '?': case '$': String varName = segment.Substring(1); _variables.TryGetValue(varName, out value); if (value != null) { output.Append(_formatter.Format(value)); } else { output.Append(segment); } break; default: output.Append(_commandText[i]); break; } } return(output.ToString()); }
/// <summary> /// Processes a SPARQL Query. /// </summary> /// <param name="query">SPARQL Query.</param> /// <returns></returns> public object ProcessQuery(SparqlQuery query) { query.QueryExecutionTime = null; var start = DateTime.Now; try { return(_store.ExecuteQuery(_formatter.Format(query))); } finally { var elapsed = (DateTime.Now - start); query.QueryExecutionTime = elapsed; } }
public void SparqlGroupByAssignmentExpression3() { if (!TestConfigManager.GetSettingAsBoolean(TestConfigManager.UseRemoteParsing)) { throw new SkipTestException("Test Config marks Remote Parsing as unavailable, test cannot be run"); } String query = "SELECT ?lang (SAMPLE(?o) AS ?example) WHERE { ?s ?p ?o . FILTER(ISLITERAL(?o)) } GROUP BY (LANG(?o) AS ?lang) HAVING LANGMATCHES(?lang, \"*\")"; SparqlQueryParser parser = new SparqlQueryParser(); SparqlQuery q = parser.ParseFromString(query); SparqlFormatter formatter = new SparqlFormatter(); Console.WriteLine(formatter.Format(q)); Console.WriteLine(); QueryableGraph g = new QueryableGraph(); UriLoader.Load(g, new Uri("http://dbpedia.org/resource/Southampton")); Object results = g.ExecuteQuery(q); if (results is SparqlResultSet) { SparqlResultSet rset = (SparqlResultSet)results; TestTools.ShowResults(rset); Assert.True(rset.All(r => r.HasValue("lang") && r.HasValue("example")), "All Results should have a ?lang and a ?example variable"); } else { Assert.True(false, "Didn't get a Result Set as expected"); } }
public void SparqlGroupByAssignmentSimple2() { String query = "SELECT ?x (COUNT(?p) AS ?predicates) WHERE { ?s ?p ?o } GROUP BY ?s AS ?x"; SparqlQueryParser parser = new SparqlQueryParser(); SparqlQuery q = parser.ParseFromString(query); SparqlFormatter formatter = new SparqlFormatter(); Console.WriteLine(formatter.Format(q)); Console.WriteLine(); QueryableGraph g = new QueryableGraph(); FileLoader.Load(g, "resources\\InferenceTest.ttl"); Object results = g.ExecuteQuery(q); if (results is SparqlResultSet) { SparqlResultSet rset = (SparqlResultSet)results; TestTools.ShowResults(rset); Assert.True(rset.All(r => r.HasValue("x") && !r.HasValue("s") && r.HasValue("predicates")), "All Results should have a ?x and ?predicates variables and no ?s variable"); } else { Assert.True(false, "Didn't get a Result Set as expected"); } }
public void SparqlFormattingOptionalAtRoot() { SparqlQuery q = new SparqlQuery { QueryType = SparqlQueryType.Select }; q.AddVariable(new SparqlVariable("s", true)); GraphPattern gp = new GraphPattern(); gp.IsOptional = true; gp.AddTriplePattern(new TriplePattern(new VariablePattern("s"), new VariablePattern("p"), new VariablePattern("o"))); q.RootGraphPattern = gp; String toStr = q.ToString(); Console.WriteLine("ToString() Form:"); Console.WriteLine(toStr); Assert.AreEqual(2, toStr.ToCharArray().Where(c => c == '{').Count()); Assert.AreEqual(2, toStr.ToCharArray().Where(c => c == '}').Count()); Console.WriteLine(); SparqlFormatter formatter = new SparqlFormatter(); String fmtStr = formatter.Format(q); Console.WriteLine("SparqlFormatter Form:"); Console.WriteLine(fmtStr); Assert.AreEqual(2, fmtStr.ToCharArray().Where(c => c == '{').Count()); Assert.AreEqual(2, fmtStr.ToCharArray().Where(c => c == '}').Count()); }
public void SparqlGroupByAssignmentExpression3() { String query = "SELECT ?lang (SAMPLE(?o) AS ?example) WHERE { ?s ?p ?o . FILTER(ISLITERAL(?o)) } GROUP BY (LANG(?o) AS ?lang) HAVING LANGMATCHES(?lang, \"*\")"; SparqlQueryParser parser = new SparqlQueryParser(); SparqlQuery q = parser.ParseFromString(query); SparqlFormatter formatter = new SparqlFormatter(); Console.WriteLine(formatter.Format(q)); Console.WriteLine(); QueryableGraph g = new QueryableGraph(); UriLoader.Load(g, new Uri("http://dbpedia.org/resource/Southampton")); Object results = g.ExecuteQuery(q); if (results is SparqlResultSet) { SparqlResultSet rset = (SparqlResultSet)results; TestTools.ShowResults(rset); Assert.IsTrue(rset.All(r => r.HasValue("lang") && r.HasValue("example")), "All Results should have a ?lang and a ?example variable"); } else { Assert.Fail("Didn't get a Result Set as expected"); } }
public void SparqlGroupByAssignmentExpression() { String query = "SELECT ?s ?sum WHERE { ?s ?p ?o } GROUP BY ?s (1 + 2 AS ?sum)"; SparqlQueryParser parser = new SparqlQueryParser(); SparqlQuery q = parser.ParseFromString(query); SparqlFormatter formatter = new SparqlFormatter(); Console.WriteLine(formatter.Format(q)); Console.WriteLine(); QueryableGraph g = new QueryableGraph(); FileLoader.Load(g, "InferenceTest.ttl"); Object results = g.ExecuteQuery(q); if (results is SparqlResultSet) { SparqlResultSet rset = (SparqlResultSet)results; TestTools.ShowResults(rset); Assert.IsTrue(rset.All(r => r.HasValue("s") && r.HasValue("sum")), "All Results should have a ?s and a ?sum variable"); } else { Assert.Fail("Didn't get a Result Set as expected"); } }
public void SparqlFunctionsNow() { SparqlQueryParser parser = new SparqlQueryParser(); SparqlQuery q = parser.ParseFromFile("resources\\now01.rq"); Console.WriteLine("ToString Output:"); Console.WriteLine(q.ToString()); Console.WriteLine(); SparqlFormatter formatter = new SparqlFormatter(); Console.WriteLine("SparqlFormatter Output:"); Console.WriteLine(formatter.Format(q)); TripleStore store = new TripleStore(); LeviathanQueryProcessor processor = new LeviathanQueryProcessor(store); SparqlResultSet results = processor.ProcessQuery(q) as SparqlResultSet; if (results != null) { Assert.IsTrue(results.Result, "Result should be true"); } else { Assert.Fail("Expected a non-null result"); } }
/// <summary> /// Processes a SPARQL Query /// </summary> /// <param name="query">SPARQL Query</param> /// <returns></returns> public object ProcessQuery(SparqlQuery query) { query.QueryExecutionTime = null; DateTime start = DateTime.Now; try { Object temp = _store.ExecuteQuery(_formatter.Format(query)); return(temp); } finally { TimeSpan elapsed = (DateTime.Now - start); query.QueryExecutionTime = elapsed; } }
private void CheckThreadSafety(String query, bool expectThreadSafe) { var q = _parser.ParseFromString(query); Console.WriteLine(_formatter.Format(q)); Assert.Equal(expectThreadSafe, q.UsesDefaultDataset); }
private void RunTest(IFullTextIndexer indexer, String query, IEnumerable <INode> expected) { this.EnsureTestData(); indexer.Index(this._dataset); indexer.Dispose(); //Build the SPARQL Query and parse it SparqlParameterizedString queryString = new SparqlParameterizedString(query); queryString.Namespaces = this.GetQueryNamespaces(); SparqlQuery q = this._parser.ParseFromString(queryString); SparqlFormatter formatter = new SparqlFormatter(q.NamespaceMap); Console.WriteLine("Parsed Query:"); Console.WriteLine(formatter.Format(q)); Console.WriteLine("Expected Results:"); foreach (INode n in expected) { Console.WriteLine(n.ToString(formatter)); } Console.WriteLine(); LuceneSearchProvider provider = new LuceneSearchProvider(LuceneTestHarness.LuceneVersion, LuceneTestHarness.Index); try { q.AlgebraOptimisers = new IAlgebraOptimiser[] { new FullTextOptimiser(provider) }; LeviathanQueryProcessor processor = new LeviathanQueryProcessor(this._dataset); SparqlResultSet results = processor.ProcessQuery(q) as SparqlResultSet; if (results != null) { TestTools.ShowResults(results); foreach (INode n in expected) { Assert.IsTrue(results.Any(r => r.HasValue("match") && r["match"] != null && r["match"].Equals(n)), "Did not get expected ?match => " + formatter.Format(n)); } foreach (SparqlResult r in results) { Assert.IsTrue(r.HasValue("match") && r["match"] != null && expected.Contains(r["match"]), "Unexpected Match " + formatter.Format(r["match"])); } } else { Assert.Fail("Did not get a SPARQL Result Set as expected"); } } finally { provider.Dispose(); LuceneTestHarness.Index.Dispose(); } }
private void RunTest(IFullTextIndexer indexer, String query, int expectedResults, bool exact) { this.EnsureTestData(); indexer.Index(this._dataset); indexer.Dispose(); //Build the SPARQL Query and parse it SparqlParameterizedString queryString = new SparqlParameterizedString(query); queryString.Namespaces = this.GetQueryNamespaces(); SparqlQuery q = this._parser.ParseFromString(queryString); SparqlFormatter formatter = new SparqlFormatter(q.NamespaceMap); Console.WriteLine("Parsed Query:"); Console.WriteLine(formatter.Format(q)); LuceneSearchProvider provider = new LuceneSearchProvider(LuceneTestHarness.LuceneVersion, LuceneTestHarness.Index); FullTextPropertyFunctionFactory factory = new FullTextPropertyFunctionFactory(); try { PropertyFunctionFactory.AddFactory(factory); q.AlgebraOptimisers = new IAlgebraOptimiser[] { new FullTextOptimiser(provider) }; Options.AlgebraOptimisation = true; LeviathanQueryProcessor processor = new LeviathanQueryProcessor(this._dataset); SparqlResultSet results = processor.ProcessQuery(q) as SparqlResultSet; if (results != null) { TestTools.ShowResults(results); if (exact) { Assert.Equal(expectedResults, results.Count); } else { Assert.True(expectedResults >= results.Count, "Got more results that the expected maximum"); } } else { Assert.True(false, "Did not get a SPARQL Result Set as expected"); } } finally { PropertyFunctionFactory.RemoveFactory(factory); provider.Dispose(); LuceneTestHarness.Index.Dispose(); } }
private void ShowQueryInformation(QueryTask task) { if (task.Query != null) { SparqlFormatter formatter = new SparqlFormatter(task.Query.NamespaceMap); StringWriter writer = new StringWriter(); writer.WriteLine("Parsed Query:"); writer.WriteLine(formatter.Format(task.Query)); writer.WriteLine("SPARQL Algebra:"); writer.WriteLine(task.Query.ToAlgebra().ToString()); CrossThreadSetText(this.txtAdvInfo, writer.ToString()); } }
public void SparqlParsingSubqueries4() { String query = "SELECT * WHERE { { SELECT * WHERE { ?s ?p ?o } } }"; SparqlQueryParser parser = new SparqlQueryParser(); SparqlQuery q = parser.ParseFromString(query); Console.WriteLine("Parsed original input OK"); SparqlFormatter formatter = new SparqlFormatter(); String query2 = formatter.Format(q); SparqlQuery q2 = parser.ParseFromString(query2); Console.WriteLine("Parsed reserialized input OK"); }
private static string addProvenance(IEnumerable <Triple> additions, IEnumerable <Triple> removals) { Graph graph = new Graph(); StringBuilder sb = new StringBuilder(); SparqlFormatter sparqlFormatter = new SparqlFormatter(); DateTimeOffset dt = DateTimeOffset.UtcNow; sb.AppendLine(";INSERT DATA {"); foreach (Triple removed in removals) { sb.Append($@"[] <http://example.com/subject> {sparqlFormatter.Format(removed.Subject)}; <http://example.com/predicate> {sparqlFormatter.Format(removed.Predicate)}; <http://example.com/dateTime> {sparqlFormatter.Format(dt.ToLiteral(graph))}; <http://example.com/oldObject> {sparqlFormatter.Format(removed.Object)}"); IEnumerable <Triple> foundAdded = additions.Where(a => a.HasSubject(removed.Subject) && a.HasPredicate(removed.Predicate)); if (foundAdded.Any()) { sb.AppendLine(";"); foreach (Triple added in foundAdded) { sb.AppendLine($@"<http://example.com/newObject> {sparqlFormatter.Format(added.Object)}."); } } else { sb.AppendLine($@"."); } } foreach (Triple added in additions) { if (removals.Any(a => a.HasSubject(added.Subject) && a.HasPredicate(added.Predicate)) == false) { sb.Append($@"[] <http://example.com/subject> {sparqlFormatter.Format(added.Subject)}; <http://example.com/predicate> {sparqlFormatter.Format(added.Predicate)}; <http://example.com/dateTime> {sparqlFormatter.Format(dt.ToLiteral(graph))}; <http://example.com/newObject> {sparqlFormatter.Format(added.Object)}."); } } sb.AppendLine("}"); return(sb.ToString()); }
private static string SetUris(string sparql, IEnumerable <string> ids) { var formatter = new SparqlFormatter(); var factory = new NodeFactory(); string format(string id) { var uri = new Uri(Program.BaseUri, id); var node = factory.CreateUriNode(uri); return(formatter.Format(node)); } return(sparql.Replace("@concepts", string.Join(" ", ids.Select(format)))); }
public void SparqlParsingConstructShortForm() { List <String> valid = new List <string>() { "CONSTRUCT WHERE {?s ?p ?o }", "CONSTRUCT WHERE {?s a ?type }", }; List <String> invalid = new List <string>() { "CONSTRUCT {?s ?p ?o}", "CONSTRUCT WHERE { ?s ?p ?o . FILTER(ISLITERAL(?o)) }", "CONSTRUCT WHERE { GRAPH ?g { ?s ?p ?o } }", "CONSTRUCT WHERE { ?s ?p ?o . OPTIONAL {?s a ?type}}", "CONSTRUCT WHERE { ?s a ?type . BIND (<http://example.org> AS ?thing) }", "CONSTRUCT WHERE { {SELECT * WHERE { ?s ?p ?o } } }" }; SparqlQueryParser parser = new SparqlQueryParser(); SparqlFormatter formatter = new SparqlFormatter(); foreach (String v in valid) { Console.WriteLine("Valid Input: " + v); SparqlQuery q = parser.ParseFromString(v); Console.WriteLine(formatter.Format(q)); Console.WriteLine(); } foreach (String iv in invalid) { Console.WriteLine("Invalid Input: " + iv); try { SparqlQuery q = parser.ParseFromString(iv); Assert.Fail("Should have thrown a Parsing Error"); } catch (RdfParseException parseEx) { Console.WriteLine("Errored as expected"); TestTools.ReportError("Parsing Error", parseEx); } Console.WriteLine(); } }
private string GetSparqlQuery(string graph, IEnumerable <Triple> additions) { var stringBuilder = new StringBuilder() .AppendLine("INSERT DATA {") .AppendLine("GRAPH <" + formatter.FormatUri(graph) + "> {"); foreach (var addition in additions) { var formattedTriple = formatter.Format(addition); stringBuilder.AppendLine(formattedTriple); } return(stringBuilder .AppendLine("}") .AppendLine("}") .ToString()); }
private void TestExtractPatterns(String query, int expectedPatterns, int expectedSubjArgs, int expectedObjArgs) { FullTextPropertyFunctionFactory factory = new FullTextPropertyFunctionFactory(); try { PropertyFunctionFactory.AddFactory(factory); SparqlParameterizedString queryString = new SparqlParameterizedString(query); queryString.Namespaces.AddNamespace("pf", new Uri(FullTextHelper.FullTextMatchNamespace)); SparqlQuery q = this._parser.ParseFromString(queryString); SparqlFormatter formatter = new SparqlFormatter(queryString.Namespaces); Console.WriteLine(formatter.Format(q)); Console.WriteLine(); List <IPropertyFunctionPattern> ps = PropertyFunctionHelper.ExtractPatterns(q.RootGraphPattern.TriplePatterns); Console.WriteLine(ps.Count + " Pattern(s) extracted"); foreach (IPropertyFunctionPattern propFunc in ps.Where(p => p.PropertyFunction is FullTextMatchPropertyFunction)) { Console.WriteLine("Match Variable: " + propFunc.SubjectArgs.First().ToString()); Console.WriteLine("Score Variable: " + (propFunc.SubjectArgs.Count() > 1 ? propFunc.SubjectArgs.Skip(1).First().ToString() : "N/A")); Console.WriteLine("Search Term: " + propFunc.ObjectArgs.First().ToString()); Console.WriteLine("Threshold/Limit: " + (propFunc.ObjectArgs.Count() > 1 ? propFunc.ObjectArgs.Skip(1).First().ToString() : "N/A")); Console.WriteLine("Limit: " + (propFunc.ObjectArgs.Count() > 2 ? propFunc.ObjectArgs.Skip(2).First().ToString() : "N/A")); Console.WriteLine(); if (expectedSubjArgs > 0) { Assert.Equal(expectedSubjArgs, propFunc.SubjectArgs.Count()); } if (expectedObjArgs > 0) { Assert.Equal(expectedObjArgs, propFunc.ObjectArgs.Count()); } } Assert.Equal(expectedPatterns, ps.Count); } finally { PropertyFunctionFactory.RemoveFactory(factory); } }
private static void SetUris(SparqlParameterizedString query, string name, string value, Uri baseUri) { var formatter = new SparqlFormatter(); var factory = new NodeFactory(); Func <string, string> format = instanceId => { var uri = new Uri(baseUri, instanceId); var node = factory.CreateUriNode(uri); return(formatter.Format(node)); }; var formattedUris = value.Split(',').Select(format); value = string.Join(" ", formattedUris); var parameter = $"@{name}"; query.CommandText = query.CommandText.Replace(parameter, value); }
private void ShowQueryInformation(QueryTask task) { CrossThreadSetEnabled(this.btnViewResults, task.State == TaskState.Completed && task.Result != null); if (task.Query != null) { StringWriter writer = new StringWriter(); writer.WriteLine("Parsed Query:"); if (task.Query != null) { SparqlFormatter formatter = new SparqlFormatter(task.Query.NamespaceMap); writer.WriteLine(formatter.Format(task.Query)); writer.WriteLine("SPARQL Algebra:"); writer.WriteLine(task.Query.ToAlgebra().ToString()); } else { writer.WriteLine("Unavailable - Not standard SPARQL 1.0/1.1"); } CrossThreadSetText(this.txtAdvInfo, writer.ToString()); } }
/// <summary> /// Processes a SPARQL Query /// </summary> /// <param name="query">SPARQL Query</param> /// <returns></returns> public object ProcessQuery(SparqlQuery query) { query.QueryExecutionTime = null; DateTime start = DateTime.Now; Object temp; try { switch (query.QueryType) { case SparqlQueryType.Ask: case SparqlQueryType.Select: case SparqlQueryType.SelectAll: case SparqlQueryType.SelectAllDistinct: case SparqlQueryType.SelectAllReduced: case SparqlQueryType.SelectDistinct: case SparqlQueryType.SelectReduced: temp = _endpoint.QueryWithResultSet(_formatter.Format(query)); break; case SparqlQueryType.Construct: case SparqlQueryType.Describe: case SparqlQueryType.DescribeAll: temp = _endpoint.QueryWithResultGraph(_formatter.Format(query)); break; default: throw new RdfQueryException("Unable to execute an unknown query type against a Remote Endpoint"); } return(temp); } finally { TimeSpan elapsed = (DateTime.Now - start); query.QueryExecutionTime = elapsed; } }
public void SparqlBlankNodeVariables1() { this.EnsureTestData(); SparqlQuery q = this._parser.ParseFromString("SELECT ?o WHERE { _:s ?p1 ?o1 FILTER(ISURI(?o1)) ?o1 ?p2 ?o . FILTER(ISLITERAL(?o)) }"); q.AlgebraOptimisers = new IAlgebraOptimiser[] { new StrictAlgebraOptimiser() }; SparqlFormatter formatter = new SparqlFormatter(); Console.WriteLine(formatter.Format(q)); Console.WriteLine(q.ToAlgebra().ToString()); SparqlResultSet results = this._processor.ProcessQuery(q) as SparqlResultSet; if (results == null) { Assert.True(false, "Did not get a SPARQL Result Set as expected"); } Assert.False(results.Count == 0, "Result Set should not be empty"); Assert.True(results.All(r => r.HasValue("o") && r["o"] != null && r["o"].NodeType == NodeType.Literal), "All results should be literals"); }
public void SparqlParsingDescribeHangingWhere() { List <String> valid = new List <string>() { "DESCRIBE ?s WHERE { ?s a ?type }", "DESCRIBE <http://example.org/>", "PREFIX ex: <http://example.org/> DESCRIBE ex:" }; List <String> invalid = new List <string>() { "DESCRIBE ?s WHERE" }; SparqlQueryParser parser = new SparqlQueryParser(); SparqlFormatter formatter = new SparqlFormatter(); foreach (String v in valid) { SparqlQuery q = parser.ParseFromString(v); Console.WriteLine(formatter.Format(q)); Console.WriteLine(); } foreach (String iv in invalid) { try { SparqlQuery q = parser.ParseFromString(iv); Assert.Fail("Should have thrown a Parsing Error"); } catch (RdfParseException parseEx) { Console.WriteLine("Errored as expected"); TestTools.ReportError("Parsing Error", parseEx); } } }
/// <summary> /// Appends the given query as a sub-query to the existing command text, any prefixes in the sub-query are moved to the parent query /// </summary> /// <param name="query">Query</param> public void AppendSubQuery(SparqlQuery query) { PreprocessText(TrimPreamble(_emptyFormatter.Format(new SubQueryPattern(query)))); // NOTE: the namespaces are already updated through during the TrimPreambule call }
/// <summary> /// Tries to create a Rule. /// </summary> /// <param name="t">Triple.</param> private void TryCreateRule(Triple t) { String[] rule = new String[2]; Dictionary <INode, INode> variableMap = new Dictionary <INode, INode>(); int nextVarID = 1; VariableContext vars = null; if (t.Context != null && t.Context is VariableContext) { vars = (VariableContext)t.Context; } StringBuilder output = new StringBuilder(); // Generate the INSERT part of the Command output.AppendLine("INSERT"); output.AppendLine("{"); foreach (Triple x in ((IGraphLiteralNode)t.Object).SubGraph.Triples) { if (vars == null) { output.AppendLine(_formatter.Format(x)); } else { if (vars.IsVariable(x.Subject)) { if (!variableMap.ContainsKey(x.Subject)) { variableMap.Add(x.Subject, new VariableNode(null, "autoRuleVar" + nextVarID)); nextVarID++; } output.Append(_formatter.Format(variableMap[x.Subject])); } else { output.Append(_formatter.Format(x.Subject)); } output.Append(' '); if (vars.IsVariable(x.Predicate)) { if (!variableMap.ContainsKey(x.Predicate)) { variableMap.Add(x.Predicate, new VariableNode(null, "autoRuleVar" + nextVarID)); nextVarID++; } output.Append(_formatter.Format(variableMap[x.Predicate])); } else { output.Append(_formatter.Format(x.Predicate)); } output.Append(' '); if (vars.IsVariable(x.Object)) { if (!variableMap.ContainsKey(x.Object)) { variableMap.Add(x.Object, new VariableNode(null, "autoRuleVar" + nextVarID)); nextVarID++; } output.Append(_formatter.Format(variableMap[x.Object])); } else { output.Append(_formatter.Format(x.Object)); } output.AppendLine(" ."); } } output.AppendLine("}"); rule[0] = output.ToString(); // Generate the WHERE part of the Command output = new StringBuilder(); output.AppendLine("WHERE"); output.AppendLine("{"); foreach (Triple x in ((IGraphLiteralNode)t.Subject).SubGraph.Triples) { if (vars == null) { output.AppendLine(_formatter.Format(x)); } else { if (vars.IsVariable(x.Subject)) { if (!variableMap.ContainsKey(x.Subject)) { variableMap.Add(x.Subject, new VariableNode(null, "autoRuleVar" + nextVarID)); nextVarID++; } output.Append(_formatter.Format(variableMap[x.Subject])); } else { output.Append(_formatter.Format(x.Subject)); } output.Append(' '); if (vars.IsVariable(x.Predicate)) { if (!variableMap.ContainsKey(x.Predicate)) { variableMap.Add(x.Predicate, new VariableNode(null, "autoRuleVar" + nextVarID)); nextVarID++; } output.Append(_formatter.Format(variableMap[x.Predicate])); } else { output.Append(_formatter.Format(x.Predicate)); } output.Append(' '); if (vars.IsVariable(x.Object)) { if (!variableMap.ContainsKey(x.Object)) { variableMap.Add(x.Object, new VariableNode(null, "autoRuleVar" + nextVarID)); nextVarID++; } output.Append(_formatter.Format(variableMap[x.Object])); } else { output.Append(_formatter.Format(x.Object)); } output.AppendLine(" ."); } } output.AppendLine("}"); rule[1] = output.ToString(); ISyntaxValidationResults results = _validator.Validate(rule[0] + rule[1]); if (results.IsValid) { _rules.Add(rule); } }
/// <summary> /// Updates a Graph in the Fuseki store /// </summary> /// <param name="graphUri">URI of the Graph to update</param> /// <param name="additions">Triples to be added</param> /// <param name="removals">Triples to be removed</param> public override void UpdateGraph(string graphUri, IEnumerable <Triple> additions, IEnumerable <Triple> removals) { try { String graph = (graphUri != null && !graphUri.Equals(String.Empty)) ? "GRAPH <" + _formatter.FormatUri(graphUri) + "> {" : String.Empty; StringBuilder update = new StringBuilder(); if (additions != null) { if (additions.Any()) { update.AppendLine("INSERT DATA {"); if (!graph.Equals(String.Empty)) { update.AppendLine(graph); } foreach (Triple t in additions) { update.AppendLine(_formatter.Format(t)); } if (!graph.Equals(String.Empty)) { update.AppendLine("}"); } update.AppendLine("}"); } } if (removals != null) { if (removals.Any()) { if (update.Length > 0) { update.AppendLine(";"); } update.AppendLine("DELETE DATA {"); if (!graph.Equals(String.Empty)) { update.AppendLine(graph); } foreach (Triple t in removals) { update.AppendLine(_formatter.Format(t)); } if (!graph.Equals(String.Empty)) { update.AppendLine("}"); } update.AppendLine("}"); } } if (update.Length > 0) { // Make the SPARQL Update Request HttpWebRequest request = (HttpWebRequest)WebRequest.Create(_updateUri); request.Method = "POST"; request.ContentType = "application/sparql-update"; request = ApplyRequestOptions(request); Tools.HttpDebugRequest(request); StreamWriter writer = new StreamWriter(request.GetRequestStream()); writer.Write(update.ToString()); writer.Close(); using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) { Tools.HttpDebugResponse(response); // If we get here without erroring then the request was OK response.Close(); } } } catch (WebException webEx) { throw StorageHelper.HandleHttpError(webEx, "updating a Graph in"); } }
/// <summary> /// Prints BGP Analysis. /// </summary> /// <param name="bgp">Analysis.</param> private void PrintBgpAnalysis(IBgp bgp) { if (!HasFlag(ExplanationLevel.AnalyseBgps)) { return; } List <ITriplePattern> ps = bgp.TriplePatterns.ToList(); if (ps.Count == 0) { PrintExplanations("Empty BGP"); } else { HashSet <String> vars = new HashSet <string>(); for (int i = 0; i < ps.Count; i++) { StringBuilder output = new StringBuilder(); // Print what will happen if (ps[i].PatternType == TriplePatternType.Filter) { output.Append("Apply "); } else if (ps[i].PatternType == TriplePatternType.BindAssignment || ps[i].PatternType == TriplePatternType.LetAssignment) { output.Append("Extend by Assignment with "); } else if (ps[i].PatternType == TriplePatternType.SubQuery) { output.Append("Sub-query "); } else if (ps[i].PatternType == TriplePatternType.Path) { output.Append("Property Path "); } else if (ps[i].PatternType == TriplePatternType.PropertyFunction) { output.Append("Property Function "); } // Print the type of Join to be performed if (i > 0 && (ps[i].PatternType == TriplePatternType.Match || ps[i].PatternType == TriplePatternType.SubQuery || ps[i].PatternType == TriplePatternType.Path)) { if (vars.IsDisjoint <String>(ps[i].Variables)) { output.Append("Cross Product with "); } else { List <String> joinVars = vars.Intersect <String>(ps[i].Variables).ToList(); output.Append("Join on {"); joinVars.ForEach(v => output.Append(" ?" + v + ",")); output.Remove(output.Length - 1, 1); output.Append(" } with "); } } // Print the actual Triple Pattern output.Append(_formatter.Format(ps[i])); // Update variables seen so far unless a FILTER which cannot introduce new variables if (ps[i].PatternType != TriplePatternType.Filter) { foreach (String var in ps[i].Variables) { vars.Add(var); } } PrintExplanations(output); } } }
private void LogStartQuery(SparqlQuery q) { SparqlFormatter formatter = new SparqlFormatter(q.NamespaceMap); this.Log("QUERY START", formatter.Format(q)); }