Makes the adapter execute EXPLAIN for the tuples of queries and bindings.
 Returns a formatted string ready to be logged.
181997
def exec_explain(queries) # :nodoc:
      str = queries.map do |sql, binds|
        msg = +"EXPLAIN for: #{sql}"
        unless binds.empty?
          msg << " "
          msg << binds.map { |attr| render_bind(attr) }.inspect
        end
        msg << "\n"
        msg << connection.explain(sql, binds)
      end.join("\n")

      # Overriding inspect to be more human readable, especially in the console.
      def str.inspect
        self
      end

      str
    end
990877
def format_explanation(explanation, indent='  ', indent_level=0):
    
    if not explanation:
        return ''

    # Note: This is probably a crap implementation, but it's an
    # interesting starting point for a better formatter.
    line = ('%s%s %2.4f' % ((indent * indent_level),
                            explanation['description'],
                            explanation['value']))

    if 'details' in explanation:
        details = '\n'.join(
            [format_explanation(subtree, indent, indent_level + 1)
             for subtree in explanation['details']])
        return line + '\n' + details

    return line
896097
@Override
    public String getQueryString() {
        try {
            collaborator.preInvoke(componentMetaData);
            return request.getQueryString();
        } finally {
            collaborator.postInvoke();
        }
    }
72762
def describe(self, uri, format="", convert=True):
		
		lines = ["PREFIX %s: <%s>" % (k, r) for k, r in self.prefixes.iteritems()]
		if uri.startswith("http://"):
			lines.extend(["DESCRIBE <%s>" % uri])
		else:  # it's a shortened uri
			lines.extend(["DESCRIBE %s" % uri])
		query = "\n".join(lines)


		if self.verbose:
			print(query, "\n\n")

		return self.__doQuery(query, format, convert)
922564
def _setup_adapter(self, namespace, route_prefix):
        
        self.serializer = JSONAPI(
            self.sqla.Model, prefix='{}://{}{}'.format(
                self.app.config['PREFERRED_URL_SCHEME'],
                self.app.config['SERVER_NAME'], route_prefix))
        for view in views:
            method, endpoint = view
            pattern = route_prefix + endpoint.value
            name = '{}_{}_{}'.format(namespace, method.name, endpoint.name)
            view = self._generate_view(method, endpoint)
            self.app.add_url_rule(pattern + '/',
                                  name + '_slashed',
                                  view,
                                  methods=[method.name],
                                  strict_slashes=False)
            self.app.add_url_rule(pattern, name, view, methods=[method.name])
1173894
def __execute_text(self, query, **replacements):
        

        # We've had persistent and long-term issues where we can't access tables 
        # from another client because they're locked, as well as getting the 
        # "gone away" error quite frequenctly. Per the documentation, apparently 
        # it is common to -not- reuse the same session from request to request,
        # and we believe this to be the problem. Hopefully it's fixed, now.
        #
        # REF: http://docs.sqlalchemy.org/en/rel_0_9/orm/session.html#when-do-i-construct-a-session-when-do-i-commit-it-and-when-do-i-close-it
        session = self.__get_session()
        
        try:
            records = session.execute(query, replacements)
        except:
            _LOGGER.exception("Query failure:\n%s", query)

            raise

        # Verifying that we have a realized list of results before we commit 
        # the transaction.

        try:
            records = list(records)
        finally:
            session.commit()

        for record in records:
            yield dict(record)
813652
private int bindStatement(PreparedStatement stmt, int index, InCriteria crit, ClassDescriptor cld) throws SQLException
    {
        if (crit.getValue() instanceof Collection)
        {
            Collection values = (Collection) crit.getValue();
            Iterator iter = values.iterator();

            while (iter.hasNext())
            {
                index = bindStatementValue(stmt, index, crit.getAttribute(), iter.next(), cld);
            }
        }
        else
        {
            index = bindStatementValue(stmt, index, crit.getAttribute(), crit.getValue(), cld);
        }
        return index;
    }
108097
def _compile_query(self):
        
        # https://wiki.apache.org/solr/SolrQuerySyntax
        # http://lucene.apache.org/core/2_9_4/queryparsersyntax.html
        query = []

        # filtered_query = self._model_class.row_level_access(self._current_context, self)
        # if filtered_query is not None:
        #     self._solr_query += filtered_query._solr_query
        # print(self._solr_query)
        for key, val, is_escaped in self._solr_query:
            # querying on a linked model by model instance
            # it should be a Model, not a Node!
            if key == 'key':
                key = '_yz_rk'
            elif key == '-key':
                    key = '-_yz_rk'
            elif key[:5] == 'key__':  # to handle key__in etc.
                key = '_yz_rk__' + key[5:]
            elif key[:6] == '-key__':  # to handle key__in etc.
                key = '-_yz_rk__' + key[6:]

            key, val, is_escaped = self._process_query_val(key, val, is_escaped)
            # if it's not one of the expected objects, it should be a string
            # if key == "OR_QRY" then join them with "OR" after escaping & parsing
            if key == 'OR_QRY':
                key = 'NOKEY'
                val = ' OR '.join(
                    ['%s:%s' % self._parse_query_key(*self._process_query_val(k, v, is_escaped)) for
                     k, v in val.items()])
                is_escaped = True
            # __in query is same as OR_QRY but key stays same for all values
            elif key.endswith('__in'):
                if not val:
                    raise ValueError("query value list can not be empty for __in query, "
                                     "please check if it is empty or not before execute filter.")
                key = key[:-4]
                val = ' OR '.join(
                    ['%s:%s' % (key, self._escape_query(v, is_escaped)) for v in val])
                if key.startswith('-'):
                    val = '*:* %s' % val
                key = 'NOKEY'
                is_escaped = True
            # parse the query
            key, val = self._parse_query_key(key, val, is_escaped)

            # as long as not explicitly asked for,
            # we filter out records with deleted flag
            if key == 'deleted':
                self.want_deleted = True
            # convert two underscores to dot notation
            key = key.replace('__', '.')
            # NOKEY means we already combined key partition in to "val"
            if key == 'NOKEY':
                query.append("(%s)" % val)
            else:
                query.append("%s:%s" % (key, val))

        # need to add *:* for negative queries, if
        # query has only one criteria, such as:
        # (-name:Jack) AND -deleted:True
        # this wont work properly, it must be altered as
        # (*:* -name:Jack) AND -deleted:True
        if len(query) == 1:
            q = query[0]
            if q.startswith('-'):
                query[0] = '*:* %s' % q
            if q[:2] == '(-':
                query[0] = '( *:* %s' % q[1:]

        # filter out "deleted" fields if not user explicitly asked for

        # join everything with "AND"
        joined_query = self._QUERY_GLUE.join(query)
        if not self.want_deleted:
            if joined_query:
                joined_query = "(%s) AND -deleted:True" % joined_query
            else:
                joined_query = '-deleted:True'
        elif not joined_query:
            joined_query = '*:*'
        self.compiled_query = joined_query
109785
def make_query_string(params)
      clean_params(params).collect do |k, v|
        CGI.escape(k) + '=' + CGI.escape(v)
      end.join('&')
    end
1017885
def _bind(self, args, kwds):
    """"""
    bindings = dict(kwds)
    for i, arg in enumerate(args):
      bindings[i + 1] = arg
    used = {}
    ancestor = self.ancestor
    if isinstance(ancestor, ParameterizedThing):
      ancestor = ancestor.resolve(bindings, used)
    filters = self.filters
    if filters is not None:
      filters = filters.resolve(bindings, used)
    unused = []
    for i in xrange(1, 1 + len(args)):
      if i not in used:
        unused.append(i)
    if unused:
      raise datastore_errors.BadArgumentError(
          'Positional arguments %s were given but not used.' %
          ', '.join(str(i) for i in unused))
    return self.__class__(kind=self.kind, ancestor=ancestor,
                          filters=filters, orders=self.orders,
                          app=self.app, namespace=self.namespace,
                          default_options=self.default_options,
                          projection=self.projection, group_by=self.group_by)
370867
def collecting_queries_for_explain # :nodoc:
      current = Thread.current
      original, current[:available_queries_for_explain] = current[:available_queries_for_explain], []
      return yield, current[:available_queries_for_explain]
    ensure
      # Note that the return value above does not depend on this assigment.
      current[:available_queries_for_explain] = original
    end
55195
def _log_query(query):
        
        query = query.strip()

        if os.linesep in query:
            # Query is a multi line query
            MetadataDataLayer.io.log_very_verbose('Executing query:')
            MetadataDataLayer.io.log_very_verbose('<sql>{0}</sql>'.format(query))
        else:
            # Query is a single line query.
            MetadataDataLayer.io.log_very_verbose('Executing query: <sql>{0}</sql>'.format(query))
149052
def execute(query_str = nil, **kwargs)
      if query_str
        kwargs[:query] = query_str
      end
      # Some of the query context _should_ be passed to the multiplex, too
      multiplex_context = if (ctx = kwargs[:context])
        {
          backtrace: ctx[:backtrace],
          tracers: ctx[:tracers],
        }
      else
        {}
      end
      # Since we're running one query, don't run a multiplex-level complexity analyzer
      all_results = multiplex([kwargs], max_complexity: nil, context: multiplex_context)
      all_results[0]
    end
159653
def do_execute(self):
        
        formatstr = str(self.resolve_option("format"))
        expanded = self.storagehandler.expand(formatstr)
        self._output.append(Token(expanded))
        return None
920424
def get_sql(query):
    
    sql = str(query.statement.compile(dialect=sqlite.dialect(),
                                      compile_kwargs={"literal_binds": True}))
    return sql
106892
def __execute_queries(self):
        """"""

        def func(item):
            or_check = False
            for queries in self._queries:
                and_check = True
                for query in queries:
                    and_check &= self._matcher._match(
                        item.get(query.get('key'), None),
                        query.get('operator'),
                        query.get('value')
                    )
                or_check |= and_check
            return or_check

        self._json_data = list(filter(lambda item: func(item), self._json_data))
835529
def query_string=(query)
      self.query_params.clear

      ::URI::QueryParams.parse(query).each do |name,value|
        self.query_params.new(
          :name  => URLQueryParamName.first_or_new(:name => name),
          :value => value
        )
      end

      return query
    end