internal static void Apply(this ISparqlResultsHandler handler, SparqlEvaluationContext context) { try { handler.StartResults(); SparqlQuery q = context.Query; SparqlQueryType type; if (q == null) { type = (context.OutputMultiset.Variables.Any() || context.OutputMultiset.Sets.Any() ? SparqlQueryType.Select : SparqlQueryType.Ask); } else { type = q.QueryType; } if (type == SparqlQueryType.Ask) { //ASK Query so get the handler to handle an appropriate boolean result if (context.OutputMultiset is IdentityMultiset) { handler.HandleBooleanResult(true); } else if (context.OutputMultiset is NullMultiset) { handler.HandleBooleanResult(false); } else { handler.HandleBooleanResult(!context.OutputMultiset.IsEmpty); } } else { //SELECT Query so get the handler to handle variables and then handle results foreach (String var in context.OutputMultiset.Variables) { if (!handler.HandleVariable(var)) ParserHelper.Stop(); } foreach (ISet s in context.OutputMultiset.Sets) { if (!handler.HandleResult(new SparqlResult(s))) ParserHelper.Stop(); } } handler.EndResults(true); } catch (RdfParsingTerminatedException) { handler.EndResults(true); } catch { handler.EndResults(false); throw; } }
public override IValuedNode Evaluate(SparqlEvaluationContext context, int bindingId) { IValuedNode a = _leftExpr.Evaluate(context, bindingId); IValuedNode b = _rightExpr.Evaluate(context, bindingId); var type = (SparqlNumericType)Math.Max((int)a.NumericType, (int)b.NumericType); if (type == SparqlNumericType.Integer) { return new LongNode(null, a.AsInteger() | b.AsInteger()); } throw new RdfQueryException("Cannot evaluate bitwise OR expression as the arguments are not integer values."); }
public void LocalSparqlQuery1() { CreateIInMemoryQueryableStore(); var x = new {Title="foo", FileLocation="bar"}; ObjectDeserialiserQuerySink sink = new ObjectDeserialiserQuerySink(typeof(Track), x.GetType(), null, false, null, null); string qry = CreateQueryForArtist("Rory Blythe"); SparqlQuery query = this._parser.ParseFromString(qry); SparqlEvaluationContext evalContext = new SparqlEvaluationContext(query, new InMemoryDataset(store)); ISparqlAlgebra algebra = query.ToAlgebra(); BaseMultiset localResults = algebra.Evaluate(evalContext); sink.Fill(localResults); foreach (object track in sink.IncomingResults) { Console.WriteLine(track.ToString()); } }
public void SparqlPropertyPathEvaluationSequencedAlternatives() { EnsureTestData(); INode a = this._factory.CreateUriNode(new Uri(RdfSpecsHelper.RdfType)); INode b = this._factory.CreateUriNode(new Uri(NamespaceMapper.RDFS + "range")); SequencePath path = new SequencePath(new AlternativePath(new Property(a), new Property(b)), new AlternativePath(new Property(a), new Property(a))); ISparqlAlgebra algebra = this.GetAlgebraUntransformed(path); SparqlEvaluationContext context = new SparqlEvaluationContext(null, this._data); BaseMultiset results = algebra.Evaluate(context); TestTools.ShowMultiset(results); Assert.IsFalse(results.IsEmpty, "Results should not be empty"); }
/// <summary> /// Processes a Having /// </summary> /// <param name="having">Having</param> /// <param name="context">SPARQL Evaluation Context</param> public override BaseMultiset ProcessHaving(Having having, SparqlEvaluationContext context) { return(this.ExplainAndEvaluate <Having>(having, context, base.ProcessHaving)); }
public void SparqlPropertyPathEvaluationZeroLengthWithBothTerms() { EnsureTestData(); FixedCardinality path = new FixedCardinality(new Property(this._factory.CreateUriNode(new Uri(RdfSpecsHelper.RdfType))), 0); ISparqlAlgebra algebra = this.GetAlgebra(path, ConfigurationLoader.CreateConfigurationNode(new Graph(), ConfigurationLoader.ClassHttpHandler), this._factory.CreateUriNode(new Uri(NamespaceMapper.RDFS + "Class"))); SparqlEvaluationContext context = new SparqlEvaluationContext(null, this._data); BaseMultiset results = algebra.Evaluate(context); TestTools.ShowMultiset(results); Assert.IsTrue(results.IsEmpty, "Results should be empty"); Assert.IsTrue(results is NullMultiset, "Results should be Null"); }
/// <summary> /// Processes an Extend /// </summary> /// <param name="extend">Extend</param> /// <param name="context">SPARQL Evaluation Context</param> public override BaseMultiset ProcessExtend(Extend extend, SparqlEvaluationContext context) { return(this.ExplainAndEvaluate <Extend>(extend, context, base.ProcessExtend)); }
/// <summary> /// Processes a Graph /// </summary> /// <param name="graph">Graph</param> /// <param name="context">SPARQL Evaluation Context</param> public override BaseMultiset ProcessGraph(Algebra.Graph graph, SparqlEvaluationContext context) { return(this.ExplainAndEvaluate <Algebra.Graph>(graph, context, base.ProcessGraph)); }
/// <summary> /// Evaluates the Command in the given Context /// </summary> /// <param name="context">Evaluation Context</param> public override void Evaluate(SparqlUpdateEvaluationContext context) { bool defGraphOk = false; bool datasetOk = false; try { //First evaluate the WHERE pattern to get the affected bindings ISparqlAlgebra where = this._wherePattern.ToAlgebra(); if (context.Commands != null) { where = context.Commands.ApplyAlgebraOptimisers(where); } //Set Active Graph for the WHERE based upon the WITH clause //Don't bother if there are USING URIs as these would override any Active Graph we set here //so we can save ourselves the effort of doing this if (!this.UsingUris.Any()) { if (this._graphUri != null) { context.Data.SetActiveGraph(this._graphUri); defGraphOk = true; } else { context.Data.SetActiveGraph((Uri)null); defGraphOk = true; } } //We need to make a dummy SparqlQuery object since if the Command has used any //USING/USING NAMEDs along with GRAPH clauses then the algebra needs to have the //URIs available to it which it gets from the Query property of the Context //object SparqlQuery query = new SparqlQuery(); foreach (Uri u in this.UsingUris) { query.AddDefaultGraph(u); } foreach (Uri u in this.UsingNamedUris) { query.AddNamedGraph(u); } SparqlEvaluationContext queryContext = new SparqlEvaluationContext(query, context.Data, context.QueryProcessor); if (this.UsingUris.Any()) { //If there are USING URIs set the Active Graph to be formed of the Graphs with those URIs context.Data.SetActiveGraph(this._usingUris); datasetOk = true; } BaseMultiset results = queryContext.Evaluate(where); if (this.UsingUris.Any()) { //If there are USING URIs reset the Active Graph afterwards //Also flag the dataset as no longer being OK as this flag is used in the finally //block to determine whether the Active Graph needs resetting which it may do if the //evaluation of the context.Data.ResetActiveGraph(); datasetOk = false; } //Reset Active Graph for the WHERE if (defGraphOk) { context.Data.ResetActiveGraph(); defGraphOk = false; } //Get the Graph from which we are deleting IGraph g = context.Data.GetModifiableGraph(this._graphUri); //Delete the Triples for each Solution foreach (ISet s in queryContext.OutputMultiset.Sets) { List<Triple> deletedTriples = new List<Triple>(); //Triples from raw Triple Patterns try { ConstructContext constructContext = new ConstructContext(g, s, true); foreach (IConstructTriplePattern p in this._deletePattern.TriplePatterns.OfType<IConstructTriplePattern>()) { try { deletedTriples.Add(p.Construct(constructContext)); } catch (RdfQueryException) { //If we get an error here then we couldn't construct a specific Triple //so we continue anyway } } g.Retract(deletedTriples); } catch (RdfQueryException) { //If we throw an error this means we couldn't construct for this solution so the //solution is ignored this graph } //Triples from GRAPH clauses foreach (GraphPattern gp in this._deletePattern.ChildGraphPatterns) { deletedTriples.Clear(); try { String graphUri; switch (gp.GraphSpecifier.TokenType) { case Token.URI: graphUri = gp.GraphSpecifier.Value; break; case Token.VARIABLE: if (s.ContainsVariable(gp.GraphSpecifier.Value)) { INode temp = s[gp.GraphSpecifier.Value.Substring(1)]; if (temp == null) { //If the Variable is not bound then skip continue; } else if (temp.NodeType == NodeType.Uri) { graphUri = temp.ToSafeString(); } else { //If the Variable is not bound to a URI then skip continue; } } else { //If the Variable is not bound for this solution then skip continue; } break; default: //Any other Graph Specifier we have to ignore this solution continue; } //If the Dataset doesn't contain the Graph then no need to do the Deletions if (!context.Data.HasGraph(UriFactory.Create(graphUri))) continue; //Do the actual Deletions IGraph h = context.Data.GetModifiableGraph(UriFactory.Create(graphUri)); ConstructContext constructContext = new ConstructContext(h, s, true); foreach (IConstructTriplePattern p in gp.TriplePatterns.OfType<IConstructTriplePattern>()) { try { deletedTriples.Add(p.Construct(constructContext)); } catch (RdfQueryException) { //If we get an error here then we couldn't construct a specific //triple so we continue anyway } } h.Retract(deletedTriples); } catch (RdfQueryException) { //If we get an error here this means we couldn't construct for this solution so the //solution is ignored for this graph } } } } finally { //If the Dataset was set and an error occurred in doing the WHERE clause then //we'll need to Reset the Active Graph if (datasetOk) context.Data.ResetActiveGraph(); if (defGraphOk) context.Data.ResetActiveGraph(); } }
/// <summary> /// Processes a Distinct modifier /// </summary> /// <param name="distinct">Distinct modifier</param> /// <param name="context">SPARQL Evaluation Context</param> public override BaseMultiset ProcessDistinct(Distinct distinct, SparqlEvaluationContext context) { return(this.ExplainAndEvaluate <Distinct>(distinct, context, base.ProcessDistinct)); }
/// <summary> /// Processes a Property Path /// </summary> /// <param name="path">Path</param> /// <param name="context">SPARQL Evaluation Context</param> /// <returns></returns> public override BaseMultiset ProcessPropertyPath(PropertyPath path, SparqlEvaluationContext context) { return(this.ExplainAndEvaluate <PropertyPath>(path, context, base.ProcessPropertyPath)); }
/// <summary> /// Processes a Reduced modifier /// </summary> /// <param name="reduced">Reduced modifier</param> /// <param name="context">SPARQL Evaluation Context</param> public override BaseMultiset ProcessReduced(Reduced reduced, SparqlEvaluationContext context) { return(this.ExplainAndEvaluate <Reduced>(reduced, context, base.ProcessReduced)); }
/// <summary> /// Processes a Null Operator /// </summary> /// <param name="nullOp">Null Operator</param> /// <param name="context">SPARQL Evaluation Context</param> /// <returns></returns> public override BaseMultiset ProcessNullOperator(NullOperator nullOp, SparqlEvaluationContext context) { return(this.ExplainAndEvaluate <NullOperator>(nullOp, context, base.ProcessNullOperator)); }
/// <summary> /// Processes an Order By /// </summary> /// <param name="orderBy"></param> /// <param name="context">SPARQL Evaluation Context</param> public override BaseMultiset ProcessOrderBy(OrderBy orderBy, SparqlEvaluationContext context) { return(this.ExplainAndEvaluate <OrderBy>(orderBy, context, base.ProcessOrderBy)); }
/// <summary> /// Processes a Negated Property Set /// </summary> /// <param name="negPropSet">Negated Property Set</param> /// <param name="context">SPARQL Evaluation Context</param> /// <returns></returns> public override BaseMultiset ProcessNegatedPropertySet(NegatedPropertySet negPropSet, SparqlEvaluationContext context) { return(this.ExplainAndEvaluate <NegatedPropertySet>(negPropSet, context, base.ProcessNegatedPropertySet)); }
/// <summary> /// Processes a Minus /// </summary> /// <param name="minus">Minus</param> /// <param name="context">SPARQL Evaluation Context</param> public override BaseMultiset ProcessMinus(IMinus minus, SparqlEvaluationContext context) { return(this.ExplainAndEvaluate <IMinus>(minus, context, base.ProcessMinus)); }
/// <summary> /// Processes a LeftJoin /// </summary> /// <param name="leftJoin">Left Join</param> /// <param name="context">SPARQL Evaluation Context</param> public override BaseMultiset ProcessLeftJoin(ILeftJoin leftJoin, SparqlEvaluationContext context) { return(this.ExplainAndEvaluate <ILeftJoin>(leftJoin, context, base.ProcessLeftJoin)); }
/// <summary> /// Evaluates the Command in the given Context /// </summary> /// <param name="context">Evaluation Context</param> public override void Evaluate(SparqlUpdateEvaluationContext context) { bool datasetOk = false; bool defGraphOk = false; try { //First evaluate the WHERE pattern to get the affected bindings ISparqlAlgebra where = this._wherePattern.ToAlgebra(); //Set Active Graph for the WHERE //Don't bother if there are USING URIs as these would override any Active Graph we set here //so we can save ourselves the effort of doing this if (!this.UsingUris.Any()) { if (this._graphUri != null) { context.Data.SetActiveGraph(this._graphUri); defGraphOk = true; } else { context.Data.SetActiveGraph((Uri)null); defGraphOk = true; } } //We need to make a dummy SparqlQuery object since if the Command has used any //USING NAMEDs along with GRAPH clauses then the algebra needs to have the //URIs available to it which it gets from the Query property of the Context //object SparqlQuery query = new SparqlQuery(); foreach (Uri u in this.UsingNamedUris) { query.AddNamedGraph(u); } SparqlEvaluationContext queryContext = new SparqlEvaluationContext(query, context.Data); if (this.UsingUris.Any()) { //If there are USING URIs set the Active Graph to be formed of the Graphs with those URIs context.Data.SetActiveGraph(this._usingUris); datasetOk = true; } BaseMultiset results = where.Evaluate(queryContext); if (this.UsingUris.Any()) { //If there are USING URIs reset the Active Graph afterwards //Also flag the dataset as no longer being OK as this flag is used in the finally //block to determine whether the Active Graph needs resetting which it may do if the //evaluation of the context.Data.ResetActiveGraph(); datasetOk = false; } //Reset Active Graph for the WHERE if (defGraphOk) { context.Data.ResetActiveGraph(); defGraphOk = false; } //TODO: Need to detect when we create a Graph for Insertion but then fail to insert anything since in this case the Inserted Graph should be removed //Get the Graph to which we are inserting //HashSet<Uri> insertedGraphs = new HashSet<Uri>(); IGraph g; if (context.Data.HasGraph(this._graphUri)) { g = context.Data.GetModifiableGraph(this._graphUri); } else { //insertedGraphs.Add(this._graphUri); g = new Graph(); g.BaseUri = this._graphUri; context.Data.AddGraph(g); g = context.Data.GetModifiableGraph(this._graphUri); } //Insert the Triples for each Solution foreach (Set s in queryContext.OutputMultiset.Sets) { List<Triple> insertedTriples = new List<Triple>(); //Triples from raw Triple Patterns try { ConstructContext constructContext = new ConstructContext(g, s, true); foreach (IConstructTriplePattern p in this._insertPattern.TriplePatterns.OfType<IConstructTriplePattern>()) { try { insertedTriples.Add(p.Construct(constructContext)); } catch (RdfQueryException) { //If we throw an error this means we couldn't construct a specific Triple //so we continue anyway } } g.Assert(insertedTriples); } catch (RdfQueryException) { //If we throw an error this means we couldn't construct for this solution so the //solution is ignored for this graph } //Triples from GRAPH clauses foreach (GraphPattern gp in this._insertPattern.ChildGraphPatterns) { insertedTriples.Clear(); try { String graphUri; switch (gp.GraphSpecifier.TokenType) { case Token.URI: graphUri = gp.GraphSpecifier.Value; break; case Token.VARIABLE: if (s.ContainsVariable(gp.GraphSpecifier.Value)) { INode temp = s[gp.GraphSpecifier.Value.Substring(1)]; if (temp == null) { //If the Variable is not bound then skip continue; } else if (temp.NodeType == NodeType.Uri) { graphUri = temp.ToSafeString(); } else { //If the Variable is not bound to a URI then skip continue; } } else { //If the Variable is not bound for this solution then skip continue; } break; default: //Any other Graph Specifier we have to ignore this solution continue; } //Ensure the Graph we're inserting to exists in the dataset creating it if necessary IGraph h; Uri destUri = new Uri(graphUri); if (context.Data.HasGraph(destUri)) { h = context.Data.GetModifiableGraph(destUri); } else { //insertedGraphs.Add(destUri); h = new Graph(); h.BaseUri = destUri; context.Data.AddGraph(h); h = context.Data.GetModifiableGraph(destUri); } //Do the actual Insertions ConstructContext constructContext = new ConstructContext(h, s, true); foreach (IConstructTriplePattern p in gp.TriplePatterns.OfType<IConstructTriplePattern>()) { try { insertedTriples.Add(p.Construct(constructContext)); } catch (RdfQueryException) { //If we throw an error this means we couldn't construct a specific Triple //so we continue anyway } } h.Assert(insertedTriples); } catch (RdfQueryException) { //If we throw an error this means we couldn't construct for this solution so the //solution is ignored for this Graph } } } } finally { //If the Dataset was set and an error occurred in doing the WHERE clause then //we'll need to Reset the Active Graph if (datasetOk) context.Data.ResetActiveGraph(); if (defGraphOk) context.Data.ResetActiveGraph(); } }
/// <summary> /// Processes a Select /// </summary> /// <param name="select">Select</param> /// <param name="context">SPARQL Evaluation Context</param> public override BaseMultiset ProcessSelect(Select select, SparqlEvaluationContext context) { return(this.ExplainAndEvaluate <Select>(select, context, base.ProcessSelect)); }
/// <summary> /// Creates a new Leviathan Results Binder /// </summary> /// <param name="context">Evaluation Context</param> public LeviathanResultBinder(SparqlEvaluationContext context) : base() { this._context = context; }
/// <summary> /// Processes a Select Distinct Graphs /// </summary> /// <param name="selDistGraphs">Select Distinct Graphs</param> /// <param name="context">SPARQL Evaluation Context</param> public override BaseMultiset ProcessSelectDistinctGraphs(SelectDistinctGraphs selDistGraphs, SparqlEvaluationContext context) { return(this.ExplainAndEvaluate <SelectDistinctGraphs>(selDistGraphs, context, base.ProcessSelectDistinctGraphs)); }
private void TestProductTimeout(IGraph data, String query, bool useGlobal, int expectedResults) { Console.WriteLine("Maximum Expected Results: " + expectedResults); Console.WriteLine("Initial Global Timeout: " + Options.QueryExecutionTimeout); Console.WriteLine(); long globalOrig = Options.QueryExecutionTimeout; try { if (useGlobal) { Console.WriteLine("Global Timeout setting in use"); } else { Console.WriteLine("Per Query Timeout setting in use"); } Console.WriteLine(); TripleStore store = new TripleStore(); store.Add(data); SparqlQuery q = this._parser.ParseFromString(query); LeviathanQueryProcessor processor = new LeviathanQueryProcessor(AsDataset(store)); SparqlFormatter formatter = new SparqlFormatter(); Console.WriteLine("Query:"); Console.WriteLine(formatter.Format(q)); //Evaluate for each Timeout foreach (long t in this._timeouts) { //Set the Timeout and ask for Partial Results if (useGlobal) { Options.QueryExecutionTimeout = t; } else { q.Timeout = t; } q.PartialResultsOnTimeout = true; //Check that the reported Timeout matches the expected SparqlEvaluationContext context = new SparqlEvaluationContext(q, null); long expected; if (useGlobal) { expected = t; } else { if (Options.QueryExecutionTimeout > 0 && t <= Options.QueryExecutionTimeout) { expected = t; } else if (Options.QueryExecutionTimeout == 0) { expected = t; } else { expected = Options.QueryExecutionTimeout; } } Assert.AreEqual(expected, context.QueryTimeout, "Reported Timeout not as expected"); //Run the Query Object results = processor.ProcessQuery(q); if (results is SparqlResultSet) { SparqlResultSet rset = (SparqlResultSet)results; Console.WriteLine("Requested Timeout: " + t + " - Actual Timeout: " + expected + "ms - Results: " + rset.Count + " - Query Time: " + q.QueryExecutionTime); Assert.IsTrue(rset.Count <= expectedResults, "Results should be <= expected"); } else { Assert.Fail("Did not get a Result Set as expected"); } } } finally { Options.QueryExecutionTimeout = globalOrig; } }
/// <summary> /// Processes a Slice modifier /// </summary> /// <param name="slice">Slice modifier</param> /// <param name="context">SPARQL Evaluation Context</param> public override BaseMultiset ProcessSlice(Slice slice, SparqlEvaluationContext context) { return(this.ExplainAndEvaluate <Slice>(slice, context, base.ProcessSlice)); }
/// <summary> /// Processes an Exists Join /// </summary> /// <param name="existsJoin">Exists Join</param> /// <param name="context">SPARQL Evaluation Context</param> public override BaseMultiset ProcessExistsJoin(IExistsJoin existsJoin, SparqlEvaluationContext context) { return(this.ExplainAndEvaluate <IExistsJoin>(existsJoin, context, base.ProcessExistsJoin)); }
/// <summary> /// Processes a Subquery /// </summary> /// <param name="subquery">Subquery</param> /// <param name="context">SPARQL Evaluation Context</param> /// <returns></returns> public override BaseMultiset ProcessSubQuery(SubQuery subquery, SparqlEvaluationContext context) { return(this.ExplainAndEvaluate <SubQuery>(subquery, context, base.ProcessSubQuery)); }
/// <summary> /// Processes a Filter /// </summary> /// <param name="filter">Filter</param> /// <param name="context">SPARQL Evaluation Context</param> public override BaseMultiset ProcessFilter(IFilter filter, SparqlEvaluationContext context) { return(this.ExplainAndEvaluate <IFilter>(filter, context, base.ProcessFilter)); }
/// <summary> /// Processes a Union /// </summary> /// <param name="union">Union</param> /// <param name="context">SPARQL Evaluation Context</param> public override BaseMultiset ProcessUnion(IUnion union, SparqlEvaluationContext context) { return(this.ExplainAndEvaluate <IUnion>(union, context, base.ProcessUnion)); }
/// <summary> /// Processes a Group By /// </summary> /// <param name="groupBy">Group By</param> /// <param name="context">SPARQL Evaluation Context</param> public override BaseMultiset ProcessGroupBy(GroupBy groupBy, SparqlEvaluationContext context) { return(this.ExplainAndEvaluate <GroupBy>(groupBy, context, base.ProcessGroupBy)); }
/// <summary> /// Processes a Unknown Operator /// </summary> /// <param name="algebra">Unknown Operator</param> /// <param name="context">SPARQL Evaluation Context</param> public override BaseMultiset ProcessUnknownOperator(ISparqlAlgebra algebra, SparqlEvaluationContext context) { return(this.ExplainAndEvaluate <ISparqlAlgebra>(algebra, context, base.ProcessUnknownOperator)); }
public void SparqlPropertyPathEvaluationZeroLengthWithTermEnd() { EnsureTestData(); FixedCardinality path = new FixedCardinality(new Property(this._factory.CreateUriNode(new Uri(RdfSpecsHelper.RdfType))), 0); INode rdfsClass = this._factory.CreateUriNode(new Uri(NamespaceMapper.RDFS + "Class")); ISparqlAlgebra algebra = this.GetAlgebra(path, null, rdfsClass); SparqlEvaluationContext context = new SparqlEvaluationContext(null, this._data); BaseMultiset results = algebra.Evaluate(context); TestTools.ShowMultiset(results); Assert.IsFalse(results.IsEmpty, "Results should not be empty"); Assert.AreEqual(1, results.Count, "Expected 1 Result"); Assert.AreEqual(rdfsClass, results[1]["x"], "Expected 1 Result set to rdfs:Class"); }
/// <summary> /// Processes a Zero or More Path /// </summary> /// <param name="path">Path</param> /// <param name="context">SPARQL Evaluation Context</param> /// <returns></returns> public override BaseMultiset ProcessZeroOrMorePath(ZeroOrMorePath path, SparqlEvaluationContext context) { return(this.ExplainAndEvaluate <ZeroOrMorePath>(path, context, base.ProcessZeroOrMorePath)); }
public void SparqlPropertyPathEvaluationInverseNegatedPropertySet() { EnsureTestData(); NegatedSet path = new NegatedSet(Enumerable.Empty<Property>(), new Property[] { new Property(this._factory.CreateUriNode(new Uri(RdfSpecsHelper.RdfType))) }); ISparqlAlgebra algebra = this.GetAlgebra(path); SparqlEvaluationContext context = new SparqlEvaluationContext(null, this._data); BaseMultiset results = algebra.Evaluate(context); TestTools.ShowMultiset(results); Assert.IsFalse(results.IsEmpty, "Results should not be empty"); }
/// <summary> /// Explains and evaluates some algebra operator /// </summary> /// <typeparam name="T">Algebra Operator Type</typeparam> /// <param name="algebra">Algebra</param> /// <param name="context">Context</param> /// <param name="evaluator">Evaluator Function</param> /// <returns></returns> private BaseMultiset ExplainAndEvaluate <T>(T algebra, SparqlEvaluationContext context, Func <T, SparqlEvaluationContext, BaseMultiset> evaluator) where T : ISparqlAlgebra { //If explanation is disabled just evaluate and return if (this._level == ExplanationLevel.None) { return(evaluator(algebra, context)); } //Print the basic evaluation start information this.ExplainEvaluationStart(algebra, context); //Print analysis (if enabled) this.PrintAnalysis(algebra); //Start Timing (if enabled) if (this.HasFlag(ExplanationLevel.ShowTimings)) { this._startTimes.Value.Push(DateTime.Now); } //Do the actual Evaluation BaseMultiset results;// = evaluator(algebra, context); if (this.HasFlag(ExplanationLevel.Simulate)) { results = (algebra is ITerminalOperator) ? new SingletonMultiset(algebra.Variables) : evaluator(algebra, context); } else { results = evaluator(algebra, context); } //End Timing and Print (if enabled) if (this.HasFlag(ExplanationLevel.ShowTimings)) { DateTime start = this._startTimes.Value.Pop(); TimeSpan elapsed = DateTime.Now - start; //this.PrintExplanations("Took " + elapsed.ToString()); this.ExplainEvaluationAction(algebra, context, "Took " + elapsed.ToString()); } //Show Intermediate Result Count (if enabled) if (this.HasFlag(ExplanationLevel.ShowIntermediateResultCount)) { String result; if (results is NullMultiset) { result = "Result is Null"; } else if (results is IdentityMultiset) { result = "Result is Identity"; } else { result = results.Count + " Results(s)"; } this.ExplainEvaluationAction(algebra, context, result); } //Print the basic evaluation end information this.ExplainEvaluationEnd(algebra, context); //Result the results return(results); }
public void SparqlPropertyPathEvaluationZeroLength() { EnsureTestData(); FixedCardinality path = new FixedCardinality(new Property(this._factory.CreateUriNode(new Uri(RdfSpecsHelper.RdfType))), 0); ISparqlAlgebra algebra = this.GetAlgebra(path); SparqlEvaluationContext context = new SparqlEvaluationContext(null, this._data); BaseMultiset results = algebra.Evaluate(context); TestTools.ShowMultiset(results); Assert.IsFalse(results.IsEmpty, "Results should not be empty"); }
/// <summary> /// Executes a Graph Pattern style query against the Source /// </summary> /// <param name="graph">Graph Pattern</param> /// <param name="options">Query Options</param> /// <param name="sink">Results Sink</param> /// <remarks> /// <para> /// This is implemented by transforming the Graph Pattern which is a set of SemWeb Statement templates into a SPARQL Algebra BGP. The resulting algebra is then executed using the Leviathan engine and the results converted into VariableBindings for SemWeb /// </para> /// <para> /// The only Query Option that is supported is the Limit option /// </para> /// </remarks> public void Query(Statement[] graph, SW.Query.QueryOptions options, SW.Query.QueryResultSink sink) { ISparqlAlgebra algebra = this.ToAlgebra(graph); SparqlEvaluationContext context = new SparqlEvaluationContext(null, new InMemoryDataset(this._store)); BaseMultiset results = context.Evaluate(algebra);//algebra.Evaluate(context); sink.Init(results.Variables.Select(v => new Variable(v)).ToArray()); if (results.Count > 0) { int c = 0; foreach (Set s in results.Sets) { //Apply Limit if applicable if (options.Limit > 0 && c >= options.Limit) { sink.Finished(); return; } //Convert the Set to VariableBindings for SemWeb Variable[] vars = s.Variables.Select(v => new Variable(v)).ToArray(); Resource[] resources = s.Variables.Select(v => SemWebConverter.ToSemWeb(s[v], this.GetMapping(s[v].Graph))).ToArray(); SW.Query.VariableBindings bindings = new SW.Query.VariableBindings(vars, resources); //Keep adding results until the sink tells us to stop if (!sink.Add(bindings)) { sink.Finished(); return; } c++; } sink.Finished(); } else { sink.Finished(); } }
private void TestProductTimeout(IGraph data, String query, bool useGlobal, int expectedResults) { Console.WriteLine("Maximum Expected Results: " + expectedResults); Console.WriteLine("Initial Global Timeout: " + Options.QueryExecutionTimeout); Console.WriteLine(); long globalOrig = Options.QueryExecutionTimeout; try { if (useGlobal) { Console.WriteLine("Global Timeout setting in use"); } else { Console.WriteLine("Per Query Timeout setting in use"); } Console.WriteLine(); TripleStore store = new TripleStore(); store.Add(data); SparqlQuery q = this._parser.ParseFromString(query); LeviathanQueryProcessor processor = new LeviathanQueryProcessor(store); SparqlFormatter formatter = new SparqlFormatter(); Console.WriteLine("Query:"); Console.WriteLine(formatter.Format(q)); //Evaluate for each Timeout foreach (long t in this._timeouts) { //Set the Timeout and ask for Partial Results if (useGlobal) { Options.QueryExecutionTimeout = t; } else { q.Timeout = t; } q.PartialResultsOnTimeout = true; //Check that the reported Timeout matches the expected SparqlEvaluationContext context = new SparqlEvaluationContext(q, null); long expected; if (useGlobal) { expected = t; } else { if (Options.QueryExecutionTimeout > 0 && t <= Options.QueryExecutionTimeout) { expected = t; } else if (Options.QueryExecutionTimeout == 0) { expected = t; } else { expected = Options.QueryExecutionTimeout; } } Assert.AreEqual(expected, context.QueryTimeout, "Reported Timeout not as expected"); //Run the Query Object results = processor.ProcessQuery(q); if (results is SparqlResultSet) { SparqlResultSet rset = (SparqlResultSet)results; Console.WriteLine("Requested Timeout: " + t + " - Actual Timeout: " + expected + "ms - Results: " + rset.Count + " - Query Time: " + q.QueryTime + "ms"); Assert.IsTrue(rset.Count <= expectedResults, "Results should be <= expected"); } else { Assert.Fail("Did not get a Result Set as expected"); } } } finally { Options.QueryExecutionTimeout = globalOrig; } }
/// <summary> /// Processes a Join. /// </summary> /// <param name="join">Join.</param> /// <param name="context">SPARQL Evaluation Context.</param> public override BaseMultiset ProcessJoin(IJoin join, SparqlEvaluationContext context) { return(ExplainAndEvaluate <IJoin>(join, context, base.ProcessJoin)); }
/// <summary> /// Processes a One or More Path. /// </summary> /// <param name="path">Path.</param> /// <param name="context">SPARQL Evaluation Context.</param> /// <returns></returns> public override BaseMultiset ProcessOneOrMorePath(OneOrMorePath path, SparqlEvaluationContext context) { return(ExplainAndEvaluate <OneOrMorePath>(path, context, base.ProcessOneOrMorePath)); }
/// <summary> /// Processes a Bindings modifier /// </summary> /// <param name="b">Bindings</param> /// <param name="context">SPARQL Evaluation Context</param> public override BaseMultiset ProcessBindings(Bindings b, SparqlEvaluationContext context) { return(this.ExplainAndEvaluate <Bindings>(b, context, base.ProcessBindings)); }
/// <summary> /// Processes an Ask /// </summary> /// <param name="ask">Ask</param> /// <param name="context">SPARQL Evaluation Context</param> public override BaseMultiset ProcessAsk(Ask ask, SparqlEvaluationContext context) { return(this.ExplainAndEvaluate <Ask>(ask, context, base.ProcessAsk)); }
/// <summary> /// Processes a Service. /// </summary> /// <param name="service">Service.</param> /// <param name="context">SPARQL Evaluation Context.</param> public override BaseMultiset ProcessService(Service service, SparqlEvaluationContext context) { return(ExplainAndEvaluate <Service>(service, context, base.ProcessService)); }
/// <summary> /// Processes a BGP /// </summary> /// <param name="bgp">BGP</param> /// <param name="context">SPARQL Evaluation Context</param> public override BaseMultiset ProcessBgp(IBgp bgp, SparqlEvaluationContext context) { return(this.ExplainAndEvaluate <IBgp>(bgp, context, base.ProcessBgp)); }
private void PrintGraphAnalysis(Algebra.Graph graph, SparqlEvaluationContext context) { if (!HasFlag(ExplanationLevel.AnalyseNamedGraphs)) { return; } switch (graph.GraphSpecifier.TokenType) { case Token.QNAME: case Token.URI: // Only a single active graph Uri activeGraphUri = UriFactory.Create(Tools.ResolveUriOrQName(graph.GraphSpecifier, context.Query.NamespaceMap, context.Query.BaseUri)); PrintExplanations("Graph clause accesses single named graph " + activeGraphUri.AbsoluteUri); break; case Token.VARIABLE: // Potentially many active graphs List <String> activeGraphs = new List <string>(); String gvar = graph.GraphSpecifier.Value.Substring(1); // Watch out for the case in which the Graph Variable is not bound for all Sets in which case // we still need to operate over all Graphs if (context.InputMultiset.ContainsVariable(gvar) && context.InputMultiset.Sets.All(s => s[gvar] != null)) { // If there are already values bound to the Graph variable for all Input Solutions then we limit the Query to those Graphs List <Uri> graphUris = new List <Uri>(); foreach (ISet s in context.InputMultiset.Sets) { INode temp = s[gvar]; if (temp == null) { continue; } if (temp.NodeType != NodeType.Uri) { continue; } activeGraphs.Add(temp.ToString()); graphUris.Add(((IUriNode)temp).Uri); } } else { // Worth explaining that the graph variable is partially bound if (context.InputMultiset.ContainsVariable(gvar)) { PrintExplanations("Graph clause uses variable ?" + gvar + " to specify named graphs, this variable is only partially bound at this point in the query so can't be use to restrict list of named graphs to access"); } // Nothing yet bound to the Graph Variable so the Query is over all the named Graphs if (context.Query != null && context.Query.NamedGraphs.Any()) { // Query specifies one/more named Graphs PrintExplanations("Graph clause uses variable ?" + gvar + " which is restricted to graphs specified by the queries FROM NAMED clause(s)"); activeGraphs.AddRange(context.Query.NamedGraphs.Select(u => u.AbsoluteUri)); } else if (context.Query != null && context.Query.DefaultGraphs.Any() && !context.Query.NamedGraphs.Any()) { // Gives null since the query dataset does not include any named graphs PrintExplanations("Graph clause uses variable ?" + gvar + " which will match no graphs because the queries dataset description does not include any named graphs i.e. there where FROM clauses but no FROM NAMED clauses"); return; } else { // Query is over entire dataset/default Graph since no named Graphs are explicitly specified PrintExplanations("Graph clause uses variable ?" + gvar + " which accesses all named graphs provided by the dataset"); activeGraphs.AddRange(context.Data.GraphUris.Select(u => u.ToSafeString())); } } // Remove all duplicates from Active Graphs to avoid duplicate results activeGraphs = activeGraphs.Distinct().ToList(); activeGraphs.RemoveAll(x => x == null); PrintExplanations("Graph clause will access the following " + activeGraphs.Count + " graphs:"); foreach (String uri in activeGraphs) { PrintExplanations(uri); } break; default: throw new RdfQueryException("Cannot use a '" + graph.GraphSpecifier.GetType() + "' Token to specify the Graph for a GRAPH clause"); } }