Esempio n. 1
0
        private SparqlResultSet ParseSparqlResultSetXmlResultFile(XDocument expected)
        {
            XNamespace ns = "http://www.w3.org/2005/sparql-results#";

            var variableNodes = expected
                                .Descendants()
                                .Where(x => x.Name.Namespace == ns && x.Name.LocalName == "head")
                                .Descendants()
                                .Where(x => x.Name.Namespace == ns && x.Name.LocalName == "variable")
                                .Select(x => x.Attribute("name"))
                                .Where(x => x != null)
                                .Select(x => x.Value);

            var resultSet = new SparqlResultSet();
            var handler   = new ResultSetHandler(resultSet);

            handler.StartResults();

            foreach (var variable in variableNodes)
            {
                handler.HandleVariable(variable);
            }

            var resultNodes = expected
                              .Descendants()
                              .Where(x => x.Name.Namespace == ns && x.Name.LocalName == "results")
                              .Descendants()
                              .Where(x => x.Name.Namespace == ns && x.Name.LocalName == "result");

            foreach (var resultNode in resultNodes)
            {
                var bindings = resultNode
                               .Descendants()
                               .Where(x => x.Name.Namespace == ns && x.Name.LocalName == "binding")
                               .Where(x => x.Attribute("name") != null);


                var set = new Set();

                foreach (var binding in bindings)
                {
                    var varNane = binding.Attribute("name").Value;
                    var value   = GetSparqlValue(binding, handler);

                    if (value != null)
                    {
                        set.Add(varNane, value);
                    }
                }

                handler.HandleResult(new SparqlResult(set));
            }

            handler.EndResults(true);

            return(resultSet);
        }
Esempio n. 2
0
        private static SparqlResultSet executeSparqlResultQuery(string sparql, string infer)
        {
            SparqlResultSet result = new SparqlResultSet();

            using (GraphDBConnector connector = new GraphDBConnector($"infer={infer}"))
            {
                connector.Timeout = 180 * 1000;
                ResultSetHandler sparqlHandler = new ResultSetHandler(result);
                connector.Query(null, sparqlHandler, sparql);
            }
            return(result);
        }
        private void TestResultSetHandler(ISparqlQueryProcessor processor, String query)
        {
            SparqlQuery q = this._parser.ParseFromString(query);

            SparqlResultSet expected = processor.ProcessQuery(q) as SparqlResultSet;

            Assert.NotNull(expected);

            SparqlResultSet  actual  = new SparqlResultSet();
            ResultSetHandler handler = new ResultSetHandler(actual);

            processor.ProcessQuery(null, handler, q);

            Assert.Equal(expected, actual);
        }
        private void TestResultSetHandler(ISparqlQueryProcessor processor, String query)
        {
            SparqlQuery q = this._parser.ParseFromString(query);

            SparqlResultSet expected = processor.ProcessQuery(q) as SparqlResultSet;

            if (expected == null)
            {
                Assert.Fail("Query failed to return a Result Set as expected");
            }

            SparqlResultSet  actual  = new SparqlResultSet();
            ResultSetHandler handler = new ResultSetHandler(actual);

            processor.ProcessQuery(null, handler, q);

            Assert.AreEqual(expected, actual, "Result Sets should be equal");
        }
Esempio n. 5
0
        public void TestAsyncQueryWithQueryCallback()
        {
            var store = new TripleStore();
            var g     = new Graph();

            g.LoadFromEmbeddedResource("VDS.RDF.Configuration.configuration.ttl");
            store.Add(g);
            var dataset = new InMemoryDataset(store, g.BaseUri);

            var processor = new LeviathanQueryProcessor(dataset);

            var wait   = new AutoResetEvent(false);
            var parser = new SparqlQueryParser();
            var query  = parser.ParseFromString(
                "SELECT * WHERE { ?instance a ?class }");
            var callbackInvoked = false;
            var syncResultSet   = processor.ProcessQuery(query) as SparqlResultSet;

            Assert.NotNull(syncResultSet);
            var syncResultCount = syncResultSet.Count;
            var resultSet       = new SparqlResultSet();
            var resultHandler   = new ResultSetHandler(resultSet);

            processor.ProcessQuery(null, resultHandler, query, (rdfHandler, rsetHandler, state) =>
            {
                try
                {
                    Assert.IsNotType <AsyncError>(state);
                    Assert.Equal("some state", state);
                }
                finally
                {
                    callbackInvoked = true;
                    wait.Set();
                }
            }, "some state");
            wait.WaitOne();
            var resultCount = resultSet.Count;

            Assert.True(callbackInvoked);
            Assert.True(resultCount > 0);
            Assert.Equal(syncResultCount, resultCount);
        }
Esempio n. 6
0
        /// <inheritdoc />
        public object Query(string sparqlQuery)
        {
            var graph        = new Graph();
            var graphHandler = new GraphHandler(graph);

            var resultSet        = new SparqlResultSet();
            var resultSetHandler = new ResultSetHandler(resultSet);

            Query(graphHandler, resultSetHandler, sparqlQuery);

            if (resultSet.ResultsType != SparqlResultsType.Unknown)
            {
                return(resultSet);
            }
            else
            {
                return(graph);
            }
        }
Esempio n. 7
0
        /// <summary>
        /// Executes the specified SQL statement using the specified connection.
        /// </summary>
        /// <typeparam name="T">The type of object that the handler returns</typeparam>
        /// <param name="conn">The connection to use for the query call.</param>
        /// <param name="query">The SQL statement to execute.</param>
        /// <param name="rsh">The handler used to create the result object from the ResultSet.</param>
        /// <returns>An object generated by the handler.</returns>
        public T Query <T>(DbConnection conn, StringBuilder query, ResultSetHandler <T> rsh)
        {
            CheckNulls(conn, query);
            T result = default(T);

            DbCommand    cmd = null;
            DbDataReader rd  = null;

            try
            {
                cmd             = conn.CreateCommand();
                cmd.CommandText = query.ToString();
                rd     = cmd.ExecuteReader();
                result = rsh.Handle(rd);
            }
            finally
            {
                Close(conn, cmd, rd);
            }

            return(result);
        }
Esempio n. 8
0
        /// <summary>
        /// Executes the specified statement using the specified connection.
        /// </summary>
        /// <typeparam name="T">The type of object that the handler returns</typeparam>
        /// <param name="conn">The connection to use for the query call.</param>
        /// <param name="stmtWrapper">The statement wrapper containing the query to execute and the statement params.</param>
        /// <param name="rsh">The handler used to create the result object from the ResultSet.</param>
        /// <returns>An object generated by the handler.</returns>
        public T Query <T>(DbConnection conn, StatementWrapper stmtWrapper, ResultSetHandler <T> rsh)
        {
            CheckNulls(conn, stmtWrapper.Query);
            T result = default(T);

            DbCommand    cmd = null;
            DbDataReader rd  = null;

            try
            {
                cmd             = conn.CreateCommand();
                cmd.CommandText = stmtWrapper.Query.ToString();
                SetParameters(cmd, stmtWrapper.DBParams);
                rd     = cmd.ExecuteReader();
                result = rsh.Handle(rd);
            }
            finally
            {
                Close(conn, cmd, rd);
            }

            return(result);
        }
        /// <summary>
        /// Runs the task
        /// </summary>
        /// <returns></returns>
        protected override object RunTaskInternal()
        {
            try
            {
                //Firstly try and parse the Query
                this.Query = this._parser.ParseFromString(this.QueryString);
            }
            catch
            {
                this.Information = "Query is not valid SPARQL 1.0/1.1 - will attempt to evaluate it but underlying store may reject the originalQuery...";
            }

            // Successfuly parsed originalQuery
            if (this.Query != null)
            {
                //Then apply it to the Manager using the GenericQueryProcessor
                try
                {
                    //Check that paging can be used if it was enabled
                    if (this._usePaging)
                    {
                        if (this.Query.Limit >= 0 || this.Query.Offset > 0)
                        {
                            throw new RdfQueryException("Cannot apply originalQuery paging when the SPARQL Query already contains an explicit LIMIT and/or OFFSET clause");
                        }
                        else if (this.Query.QueryType == SparqlQueryType.Ask)
                        {
                            throw new RdfQueryException("Cannot apply originalQuery paging to an ASK Query");
                        }
                    }

                    int      offset    = 0;
                    TimeSpan totalTime = TimeSpan.Zero;

                    switch (this.Query.QueryType)
                    {
                    case SparqlQueryType.Ask:
                        SparqlResultSet blnResult = this._processor.ProcessQuery(this.Query) as SparqlResultSet;
                        if (blnResult == null)
                        {
                            throw new RdfQueryException("Store did not return a SPARQL Result Set for the ASK originalQuery as was expected");
                        }
                        return(blnResult);

                    case SparqlQueryType.Construct:
                    case SparqlQueryType.Describe:
                    case SparqlQueryType.DescribeAll:
                        Graph g = new Graph();
                        g.NamespaceMap.Import(this.Query.NamespaceMap);

                        do
                        {
                            if (this._usePaging)
                            {
                                this.Query.Limit  = this._pageSize;
                                this.Query.Offset = offset;
                            }
                            Object result = this._processor.ProcessQuery(this.Query);
                            totalTime += this.Query.QueryExecutionTime.HasValue ? this.Query.QueryExecutionTime.Value : TimeSpan.Zero;

                            if (!(result is IGraph))
                            {
                                throw new RdfQueryException("SPARQL Query did not return a RDF Graph as expected");
                            }
                            IGraph temp = (IGraph)result;

                            //If no further results can halt
                            if (temp.Triples.Count == 0)
                            {
                                break;
                            }
                            offset += this._pageSize;

                            //Merge the partial result into the final result
                            g.Merge(temp);
                        } while (this._usePaging);

                        this.Information = "Query Completed OK (Took " + totalTime.ToString() + ")";
                        return(g);

                    case SparqlQueryType.Select:
                    case SparqlQueryType.SelectAll:
                    case SparqlQueryType.SelectAllDistinct:
                    case SparqlQueryType.SelectAllReduced:
                    case SparqlQueryType.SelectDistinct:
                    case SparqlQueryType.SelectReduced:
                        SparqlResultSet  results = new SparqlResultSet();
                        ResultSetHandler handler = new ResultSetHandler(results);
                        try
                        {
                            handler.StartResults();

                            do
                            {
                                if (this._usePaging)
                                {
                                    this.Query.Limit  = this._pageSize;
                                    this.Query.Offset = offset;
                                }
                                Object result = this._processor.ProcessQuery(this.Query);
                                totalTime += this.Query.QueryExecutionTime.HasValue ? this.Query.QueryExecutionTime.Value : TimeSpan.Zero;

                                if (!(result is SparqlResultSet))
                                {
                                    throw new RdfQueryException("SPARQL Query did not return a SPARQL Result Set as expected");
                                }
                                SparqlResultSet rset = (SparqlResultSet)result;
                                foreach (String var in rset.Variables)
                                {
                                    handler.HandleVariable(var);
                                }

                                //If no further results can halt
                                if (rset.Count == 0)
                                {
                                    break;
                                }
                                offset += this._pageSize;

                                //Merge the partial result into the final result
                                foreach (SparqlResult r in rset)
                                {
                                    handler.HandleResult(r);
                                }
                            } while (this._usePaging);

                            handler.EndResults(true);
                        }
                        catch
                        {
                            handler.EndResults(false);
                            throw;
                        }
                        this.Information = "Query Completed OK (Took " + totalTime.ToString() + ")";
                        return(results);

                    default:
                        throw new RdfQueryException("Cannot evaluate an unknown originalQuery type");
                    }
                }
                catch
                {
                    //Try and show the execution time if possible
                    if (this.Query.QueryExecutionTime.HasValue)
                    {
                        this.Information = "Query Failed (Took " + this.Query.QueryExecutionTime.Value + ")";
                    }
                    else
                    {
                        this.Information = "Query Failed";
                    }
                    throw;
                }
            }

            // Unsuccessfully parsed originalQuery - may be using syntax extensions specific to the target store
            DateTime start = DateTime.Now;

            try
            {
                if (this._usePaging)
                {
                    throw new RdfQueryException("Cannot apply paging to a Query that we cannot parse as a valid SPARQL 1.0/1.1 originalQuery");
                }
                Object results = this._storage.Query(this.QueryString);
                this.Information = "Query Completed OK (Took " + (DateTime.Now - start) + ")";
                return(results);
            }
            catch
            {
                //Try and show the execution time if possible
                try
                {
                    this.Information = "Query Failed (Took " + (DateTime.Now - start) + ")";
                }
                catch
                {
                    this.Information = "Query Failed";
                }
                throw;
            }
        }