note: requires SPARQL 1.1
        2015-06-04: currenlty not used, inferred from above
169331
def getClassAllSubs(self, aURI):
        
        aURI = aURI
        try:
            qres = self.rdfgraph.query(
                  """SELECT DISTINCT ?x
                     WHERE {
                         { ?x rdfs:subClassOf+ <%s> }
                         FILTER (!isBlank(?x))
                     }
                     """ % (aURI))
        except:
            printDebug("... warning: the 'getClassAllSubs' query failed (maybe missing SPARQL 1.1 support?)")
            qres = []
        return list(qres)
533248
def _search(self, searchterm, pred, **args):
        
        # TODO: DRY with sparql_ontol_utils
        searchterm = searchterm.replace('%','.*')
        namedGraph = get_named_graph(self.handle)
        query = """
        prefix oboInOwl: <http://www.geneontology.org/formats/oboInOwl#>
        SELECT ?c WHERE {{
        GRAPH <{g}>  {{
        ?c {pred} ?l
        FILTER regex(?l,'{s}','i')
        }}
        }}
        """.format(pred=pred, s=searchterm, g=namedGraph)
        bindings = run_sparql(query)
        return [r['c']['value'] for r in bindings]
1232411
private static String initFindEntitiesQuery(EntityKeyMetadata entityKeyMetadata, boolean includeEmbedded) {
		StringBuilder queryBuilder = new StringBuilder( "MATCH " );
		queryBuilder.append( "(" );
		queryBuilder.append( ENTITY_ALIAS );
		queryBuilder.append( ":" );
		queryBuilder.append( ENTITY );
		queryBuilder.append( ":" );
		appendLabel( entityKeyMetadata, queryBuilder );
		queryBuilder.append( ")" );
		appendOptionalMatchOwnerEmbeddedNodes( queryBuilder );
		appendGetEmbeddedNodesIfNeeded( includeEmbedded, queryBuilder );
		return queryBuilder.toString();
	}
761141
def _rdf2dot_simple(g, stream):
    """"""
    from itertools import chain

    import re

    path_re = re.compile(
        r'file:///(?P<type>[a-zA-Z]+)/'
        r'(?P<commit>\w+)'
        r'(?P<path>.+)?'
    )

    inputs = g.query(
        """
        SELECT ?input ?role ?activity ?comment
        WHERE {
            ?activity (prov:qualifiedUsage/prov:entity) ?input .
            ?activity prov:qualifiedUsage ?qual .
            ?qual prov:hadRole ?role .
            ?qual prov:entity ?input .
            ?qual rdf:type ?type .
            ?activity rdf:type wfprov:ProcessRun .
            ?activity rdfs:comment ?comment .
            FILTER NOT EXISTS {?activity rdf:type wfprov:WorkflowRun}
        }
        """
    )
    outputs = g.query(
        """
        SELECT ?activity ?role ?output ?comment
        WHERE {
            ?output (prov:qualifiedGeneration/prov:activity) ?activity .
            ?output prov:qualifiedGeneration ?qual .
            ?qual prov:hadRole ?role .
            ?qual prov:activity ?activity .
            ?qual rdf:type ?type .
            ?activity rdf:type wfprov:ProcessRun ;
                      rdfs:comment ?comment .
            FILTER NOT EXISTS {?activity rdf:type wfprov:WorkflowRun}
        }
        """
    )

    activity_nodes = {}
    artifact_nodes = {}
    for source, role, target, comment, in chain(inputs, outputs):
        # extract the pieces of the process URI
        src_path = path_re.match(source).groupdict()
        tgt_path = path_re.match(target).groupdict()

        # write the edge
        stream.write(
            '\t"{src_commit}:{src_path}" -> '
            '"{tgt_commit}:{tgt_path}" '
            '[label={role}] \n'.format(
                src_commit=src_path['commit'][:5],
                src_path=src_path.get('path') or '',
                tgt_commit=tgt_path['commit'][:5],
                tgt_path=tgt_path.get('path') or '',
                role=role
            )
        )
        if src_path.get('type') == 'commit':
            activity_nodes.setdefault(source, {'comment': comment})
            artifact_nodes.setdefault(target, {})
        if tgt_path.get('type') == 'commit':
            activity_nodes.setdefault(target, {'comment': comment})
            artifact_nodes.setdefault(source, {})

    # customize the nodes
    for node, content in activity_nodes.items():
        node_path = path_re.match(node).groupdict()
        stream.write(
            '\t"{commit}:{path}" '
            '[shape=box label="#{commit}:{path}:{comment}"] \n'.format(
                comment=content['comment'],
                commit=node_path['commit'][:5],
                path=node_path.get('path') or ''
            )
        )
    for node, content in artifact_nodes.items():
        node_path = path_re.match(node).groupdict()
        stream.write(
            '\t"{commit}:{path}" '
            '[label="#{commit}:{path}"] \n'.format(
                commit=node_path['commit'][:5],
                path=node_path.get('path') or ''
            )
        )
    stream.write('}\n')
938416
def sparql_count(self, query, flush=None):
        
        return self.count_statements(query, language='sparql', type='tuples',
            flush=flush)
1163942
private static void getPrimaryKey(DatabaseMetaData md, DatabaseRelationDefinition relation, QuotedIDFactory idfac) throws SQLException {
		RelationID id = relation.getID();
		// Retrieves a description of the given table's primary key columns. They are ordered by COLUMN_NAME (sic!)
		try (ResultSet rs = md.getPrimaryKeys(null, id.getSchemaName(), id.getTableName())) {
			extractPrimaryKey(relation, idfac, id, rs);
		} catch (SQLSyntaxErrorException e) {
		    // WORKAROUND for MySQL connector >= 8.0:
            // <https://github.com/ontop/ontop/issues/270>
            try (ResultSet rs = md.getPrimaryKeys(id.getSchemaName(), null, id.getTableName())) {
                extractPrimaryKey(relation, idfac, id, rs);
            }
		}
	}
113299
def query(self, constraint, sortby=None, typenames=None, maxrecords=10, startposition=0):
        

        # run the raw query and get total
        # we want to exclude layers which are not valid, as it is done in the search engine
        if 'where' in constraint:  # GetRecords with constraint
            query = self._get_repo_filter(Layer.objects).filter(
                is_valid=True).extra(where=[constraint['where']], params=constraint['values'])
        else:  # GetRecords sans constraint
            query = self._get_repo_filter(Layer.objects).filter(is_valid=True)

        total = query.count()

        # apply sorting, limit and offset
        if sortby is not None:
            if 'spatial' in sortby and sortby['spatial']:  # spatial sort
                desc = False
                if sortby['order'] == 'DESC':
                    desc = True
                query = query.all()
                return [str(total),
                        sorted(query,
                               key=lambda x: float(util.get_geometry_area(getattr(x, sortby['propertyname']))),
                               reverse=desc,
                               )[startposition:startposition+int(maxrecords)]]
            else:
                if sortby['order'] == 'DESC':
                    pname = '-%s' % sortby['propertyname']
                else:
                    pname = sortby['propertyname']
                return [str(total),
                        query.order_by(pname)[startposition:startposition+int(maxrecords)]]
        else:  # no sort
            return [str(total), query.all()[startposition:startposition+int(maxrecords)]]
149767
def getPropAllSubs(self, aURI):
        
        aURI = aURI
        try:
            qres = self.rdflib_graph.query("""SELECT DISTINCT ?x
                     WHERE {
                         { ?x rdfs:subPropertyOf+ <%s> }
                         FILTER (!isBlank(?x))
                     }
                     """ % (aURI))
        except:
            printDebug(
                "... warning: the 'getPropAllSubs' query failed (maybe missing SPARQL 1.1 support?)"
            )
            qres = []
        return list(qres)
950861
def transform_sparql_construct(rdf, construct_query):
    """"""

    logging.debug("performing SPARQL CONSTRUCT transformation")

    if construct_query[0] == '@':  # actual query should be read from file
        construct_query = file(construct_query[1:]).read()

    logging.debug("CONSTRUCT query: %s", construct_query)

    newgraph = Graph()
    for triple in rdf.query(construct_query):
        newgraph.add(triple)

    return newgraph
304421
private boolean querySupported(Query<Entity> q) {
    return !containsAnyOperator(q, unsupportedOperators)
        && !containsComputedAttribute(q, getEntityType())
        && !containsNestedQueryRuleField(q);
  }
1199601
private void checkRelationAndExecuteQuery(String embeddableKey,
            Map<String, List<String>> embeddableToDependentEmbeddables, Map<String, String> queries)
    {
        List<String> dependentEmbeddables = embeddableToDependentEmbeddables.get(embeddableKey);

        if (!dependentEmbeddables.isEmpty())
        {
            for (String dependentEmbeddable : dependentEmbeddables)
            {
                checkRelationAndExecuteQuery(dependentEmbeddable, embeddableToDependentEmbeddables, queries);
            }
        }
        KunderaCoreUtils.printQuery(queries.get(embeddableKey), showQuery);

        try
        {
            cassandra_client.execute_cql3_query(
                    ByteBuffer.wrap(queries.get(embeddableKey).getBytes(Constants.CHARSET_UTF8)), Compression.NONE,
                    ConsistencyLevel.ONE);
        }
        catch (Exception e)
        {
            throw new KunderaException("Error while creating type: " + queries.get(embeddableKey), e);
        }

    }
514984
def getClassAllSubs(self, aURI):
        
        aURI = aURI
        try:
            qres = self.rdflib_graph.query("""SELECT DISTINCT ?x
                     WHERE {
                         { ?x rdfs:subClassOf+ <%s> }
                         FILTER (!isBlank(?x))
                     }
                     """ % (aURI))
        except:
            printDebug(
                "... warning: the 'getClassAllSubs' query failed (maybe missing SPARQL 1.1 support?)"
            )
            qres = []
        return list(qres)
1287181
def GetKnowledgeBase(rdf_client_obj, allow_uninitialized=False):
  """"""
  if not allow_uninitialized:
    if rdf_client_obj is None:
      raise artifact_utils.KnowledgeBaseUninitializedError(
          "No client snapshot given.")
    if rdf_client_obj.knowledge_base is None:
      raise artifact_utils.KnowledgeBaseUninitializedError(
          "KnowledgeBase empty for %s." % rdf_client_obj.client_id)
    kb = rdf_client_obj.knowledge_base
    if not kb.os:
      raise artifact_utils.KnowledgeBaseAttributesMissingError(
          "KnowledgeBase missing OS for %s. Knowledgebase content: %s" %
          (rdf_client_obj.client_id, kb))
  if rdf_client_obj is None or rdf_client_obj.knowledge_base is None:
    return rdf_client.KnowledgeBase()

  version = rdf_client_obj.os_version.split(".")
  kb = rdf_client_obj.knowledge_base
  try:
    kb.os_major_version = int(version[0])
    if len(version) >= 1:
      kb.os_minor_version = int(version[1])
  except ValueError:
    pass

  return kb
425608
def _GetSqliteSchema(self, proto_struct_class, prefix=""):
    """"""
    schema = collections.OrderedDict()
    for type_info in proto_struct_class.type_infos:
      if type_info.__class__ is rdf_structs.ProtoEmbedded:
        schema.update(
            self._GetSqliteSchema(
                type_info.type, prefix="%s%s." % (prefix, type_info.name)))
      else:
        field_name = utils.SmartStr(prefix + type_info.name)
        schema[field_name] = Rdf2SqliteAdapter.GetConverter(type_info)
    return schema
1046244
function resolvePrimaryKey(attrNode, context) {
    const errorContext = context.errorContext;
    context.errorContext = ' in primaryKey' + errorContext;

    const neededDataSources = [];

    Object.keys(attrNode.dataSources).forEach(dataSourceName => {
        if (attrNode.dataSources[dataSourceName].joinParentKey) return;
        neededDataSources.push(dataSourceName);
    });

    attrNode.resolvedPrimaryKey = resolveKey(
        attrNode.primaryKey,
        attrNode,
        {
            neededDataSources,
            allowMultiValued: false
        },
        context
    );

    // enable "equal" filter:
    attrNode.primaryKey.forEach(primaryKeyAttrPath => {
        const primaryKeyAttrNode = getLocalAttribute(primaryKeyAttrPath, attrNode, context);

        if (!primaryKeyAttrNode.filter && attrNode.primaryKey.length === 1) {
            if (!primaryKeyAttrNode.hidden) {
                primaryKeyAttrNode.filter = ['equal'];
            }
        }
    });

    context.errorContext = errorContext;
}
1039146
private DataFrame getDataFrameToPersist(String query, String subQuery)
    {
        EntityMetadata entityMetadata = getEntityMetadata();

        Client client = entityMetadata != null ? persistenceDelegeator.getClient(entityMetadata)
                : persistenceDelegeator.getClient(kunderaQuery.getPersistenceUnit());

        return ((SparkClient) client).getDataFrame(subQuery, entityMetadata, getKunderaQuery());
    }
424176
def where(filter)
      if filter.is_a?(String) # we got a Sparql snippet
        where_clauses << filter
      elsif filter.is_a?(Hash)
        filter.each_pair do |key, value|
          field = resource_class.get_field(key)
          value = RDF::Literal.new(value) unless value.respond_to?(:to_base)
          where_clauses << "?uri <#{ field.predicate }> #{ value.to_base }"
        end
      end
      self
    end