def test_do_sparql_explain(self):
     query = "SELECT * WHERE {?s ?p ?o} LIMIT 1"
     request_generator = SPARQLRequestGenerator()
     res = do_sparql_explain(query, self.host, self.port, self.ssl,
                             request_generator)
     self.assertEqual(type(res), str)
     self.assertTrue(res.startswith('<!DOCTYPE html>'))
Esempio n. 2
0
    def test_do_sparql_explain(self):
        query = "SELECT * WHERE {?s ?p ?o} LIMIT 1"
        request_generator = create_request_generator(
            AuthModeEnum.IAM, IAMAuthCredentialsProvider.ENV)

        res = do_sparql_explain(query, self.host, self.port, self.ssl,
                                request_generator)
        self.assertEqual(type(res), str)
        self.assertTrue(res.startswith('<!DOCTYPE html>'))
Esempio n. 3
0
def sparql_explain(query,
                   host,
                   port,
                   use_ssl,
                   request_param_generator=SPARQLRequestGenerator()):
    res = do_sparql_explain(query, host, port, use_ssl,
                            request_param_generator)
    if 'error' in res:
        html = error_template.render(error=json.dumps(res['error'], indent=2))
    else:
        html = sparql_explain_template.render(table=res)

    return html
Esempio n. 4
0
    def sparql(self, line='', cell='', local_ns: dict = None):
        parser = argparse.ArgumentParser()
        parser.add_argument('query_mode',
                            nargs='?',
                            default='query',
                            help='query mode (default=query) [query|explain]')
        parser.add_argument('--expand-all', action='store_true')

        request_generator = create_request_generator(
            self.graph_notebook_config.auth_mode,
            self.graph_notebook_config.iam_credentials_provider_type,
            command='sparql')
        parser.add_argument('--store-to',
                            type=str,
                            default='',
                            help='store query result to this variable')
        args = parser.parse_args(line.split())
        mode = str_to_query_mode(args.query_mode)

        tab = widgets.Tab()
        logger.debug(f'using mode={mode}')
        if mode == QueryMode.EXPLAIN:
            res = do_sparql_explain(cell, self.graph_notebook_config.host,
                                    self.graph_notebook_config.port,
                                    self.graph_notebook_config.ssl,
                                    request_generator)
            store_to_ns(args.store_to, res, local_ns)
            if 'error' in res:
                html = error_template.render(
                    error=json.dumps(res['error'], indent=2))
            else:
                html = sparql_explain_template.render(table=res)
            explain_output = widgets.Output(layout=DEFAULT_LAYOUT)
            with explain_output:
                display(HTML(html))

            tab.children = [explain_output]
            tab.set_title(0, 'Explain')
            display(tab)
        else:
            query_type = get_query_type(cell)
            headers = {} if query_type not in [
                'SELECT', 'CONSTRUCT', 'DESCRIBE'
            ] else {
                'Accept': 'application/sparql-results+json'
            }
            res = do_sparql_query(cell, self.graph_notebook_config.host,
                                  self.graph_notebook_config.port,
                                  self.graph_notebook_config.ssl,
                                  request_generator, headers)
            store_to_ns(args.store_to, res, local_ns)
            titles = []
            children = []

            display(tab)
            table_output = widgets.Output(layout=DEFAULT_LAYOUT)
            # Assign an empty value so we can always display to table output.
            # We will only add it as a tab if the type of query allows it.
            # Because of this, the table_output will only be displayed on the DOM if the query was of type SELECT.
            table_html = ""
            query_type = get_query_type(cell)
            if query_type in ['SELECT', 'CONSTRUCT', 'DESCRIBE']:
                logger.debug('creating sparql network...')

                # some issues with displaying a datatable when not wrapped in an hbox and displayed last
                hbox = widgets.HBox([table_output], layout=DEFAULT_LAYOUT)
                titles.append('Table')
                children.append(hbox)

                expand_all = line == '--expand-all'
                sn = SPARQLNetwork(expand_all=expand_all)
                sn.extract_prefix_declarations_from_query(cell)
                try:
                    sn.add_results(res)
                except ValueError as value_error:
                    logger.debug(value_error)

                logger.debug(f'number of nodes is {len(sn.graph.nodes)}')
                if len(sn.graph.nodes) > 0:
                    f = Force(network=sn,
                              options=self.graph_notebook_vis_options)
                    titles.append('Graph')
                    children.append(f)
                    logger.debug('added sparql network to tabs')

                rows_and_columns = get_rows_and_columns(res)
                if rows_and_columns is not None:
                    table_id = f"table-{str(uuid.uuid4())[:8]}"
                    table_html = sparql_table_template.render(
                        columns=rows_and_columns['columns'],
                        rows=rows_and_columns['rows'],
                        guid=table_id)

                # Handling CONSTRUCT and DESCRIBE on their own because we want to maintain the previous result pattern
                # of showing a tsv with each line being a result binding in addition to new ones.
                if query_type == 'CONSTRUCT' or query_type == 'DESCRIBE':
                    lines = []
                    for b in res['results']['bindings']:
                        lines.append(
                            f'{b["subject"]["value"]}\t{b["predicate"]["value"]}\t{b["object"]["value"]}'
                        )
                    raw_output = widgets.Output(layout=DEFAULT_LAYOUT)
                    with raw_output:
                        html = sparql_construct_template.render(lines=lines)
                        display(HTML(html))
                    children.append(raw_output)
                    titles.append('Raw')

            json_output = widgets.Output(layout=DEFAULT_LAYOUT)
            with json_output:
                print(json.dumps(res, indent=2))
            children.append(json_output)
            titles.append('JSON')

            tab.children = children
            for i in range(len(titles)):
                tab.set_title(i, titles[i])

            with table_output:
                display(HTML(table_html))