Ensures the given query is applied after the appropriate index.
552653
private void indexQuery(
      long index,
      long timestamp,
      RaftSession session,
      PrimitiveOperation operation,
      CompletableFuture<OperationResult> future) {
    // If the query index is greater than the session's last applied index, queue the request for handling once the
    // state machine is caught up.
    if (index > currentIndex) {
      log.trace("Registering query with index " + index + " > " + currentIndex);
      session.registerIndexQuery(index, () -> applyQuery(timestamp, session, operation, future));
    } else {
      applyQuery(timestamp, session, operation, future);
    }
  }
1135858
private void ensureNext() {
        // Check if the current scan result has more keys (i.e. the index did not reach the end of the result list)
        if (resultIndex < scanResult.getResult().size()) {
            return;
        }
        // Since the current scan result was fully iterated,
        // if there is another cursor scan it and ensure next key (recursively)
        if (!FIRST_CURSOR.equals(scanResult.getStringCursor())) {
            scanResult = scan(scanResult.getStringCursor(), scanParams);
            resultIndex = 0;
            ensureNext();
        }
    }
1218352
function indexRetrieve(value, index, hitBehavior) {
        each(index, function (item) {
            if (item.reg.test(value)) {
                hitBehavior(item.v, item.k, item);
                return false;
            }
        });
    }
860007
def after(self, i, sibling, name=None):
        """"""
        self.parent._insert(sibling, idx=self._own_index + 1 + i, name=name)
        return self
492745
def __check_index(self, start_date, end_date):
        """"""
        index_query = """SELECT id
                           FROM facts
                          WHERE (end_time >= ? OR end_time IS NULL)
                            AND start_time <= ?
                            AND id not in(select id from fact_index)"""

        rebuild_ids = ",".join([str(res[0]) for res in self.fetchall(index_query, (start_date, end_date))])

        if rebuild_ids:
            query = """
                       SELECT a.id AS id,
                              a.start_time AS start_time,
                              a.end_time AS end_time,
                              a.description as description,
                              b.name AS name, b.id as activity_id,
                              coalesce(c.name, ?) as category,
                              e.name as tag
                         FROM facts a
                    LEFT JOIN activities b ON a.activity_id = b.id
                    LEFT JOIN categories c ON b.category_id = c.id
                    LEFT JOIN fact_tags d ON d.fact_id = a.id
                    LEFT JOIN tags e ON e.id = d.tag_id
                        WHERE a.id in (%s)
                     ORDER BY a.id
            """ % rebuild_ids

            facts = self.__group_tags(self.fetchall(query, (self._unsorted_localized, )))

            insert = """INSERT INTO fact_index (id, name, category, description, tag)
                             VALUES (?, ?, ?, ?, ?)"""
            params = [(fact['id'], fact['name'], fact['category'], fact['description'], " ".join(fact['tags'])) for fact in facts]

            self.executemany(insert, params)
903495
def after(self, idx):
        """"""
        if not isinstance(idx, datetime):
            raise TypeError("'%s' is not %s" % (idx, datetime))
        day = max(idx.date(), self._lo_limit)
        while day < self._hi_limit:
            if day < self._rd_cache.lo or day >= self._rd_cache.hi:
                self._load(self._rd_cache, day)
            self._rd_cache.set_ptr(idx)
            if self._rd_cache.ptr < len(self._rd_cache.data):
                return self._rd_cache.data[self._rd_cache.ptr]['idx']
            day = self._rd_cache.hi
        return None
881921
function(index) {
    var rule = this.resolvers[index];
    if (rule.passes === true) {
      this.passed.push(rule);
    } else if (rule.passes === false) {
      this.failed.push(rule);
      this.onFailedOne(rule);
    }

    this.fire();
  }
1293503
def recurse(query, index):
    
    for node in app.store.find(query):
        if node.is_leaf:
            index.add(node.path)
        else:
            recurse('{0}.*'.format(node.path), index)
1240086
private void enforceCpuLimits()
    {
        for (QueryExecution query : queryTracker.getAllQueries()) {
            Duration cpuTime = query.getTotalCpuTime();
            Duration sessionLimit = getQueryMaxCpuTime(query.getSession());
            Duration limit = Ordering.natural().min(maxQueryCpuTime, sessionLimit);
            if (cpuTime.compareTo(limit) > 0) {
                query.fail(new ExceededCpuLimitException(limit));
            }
        }
    }
981050
def run(self):
        """"""
        query = self.query

        # count before filtering
        self.cardinality = query.add_columns(self.columns[0].sqla_expr).count()

        self._set_column_filter_expressions()
        self._set_global_filter_expression()
        self._set_sort_expressions()
        self._set_yadcf_data(query)

        # apply filters
        query = query.filter(
            *[e for e in self.filter_expressions if e is not None])

        self.cardinality_filtered = query.add_columns(
            self.columns[0].sqla_expr).count()

        # apply sorts
        query = query.order_by(
            *[e for e in self.sort_expressions if e is not None])

        # add paging options
        length = int(self.params.get('length'))
        if length >= 0:
            query = query.limit(length)
        elif length == -1:
            pass
        else:
            raise (ValueError(
                'Length should be a positive integer or -1 to disable'))
        query = query.offset(int(self.params.get('start')))

        # add columns to query
        query = query.add_columns(*[c.sqla_expr for c in self.columns])

        # fetch the result of the queries
        column_names = [
            col.mData if col.mData else str(i)
            for i, col in enumerate(self.columns)
        ]
        self.results = [{k: v
                         for k, v in zip(column_names, row)}
                        for row in query.all()]
128188
private function ensureIndexes()
    {
        if ($this->checkedIndexes) {
            return;
        }

        $this->checkedIndexes = true;

        if ( ! $this->isFilesCollectionEmpty()) {
            return;
        }

        $this->ensureFilesIndex();
        $this->ensureChunksIndex();
    }
668042
protected CompletableFuture<QueryResponse> applyQuery(Indexed<QueryEntry> entry) {
    // In the case of the leader, the state machine is always up to date, so no queries will be queued and all query
    // indexes will be the last applied index.
    CompletableFuture<QueryResponse> future = new CompletableFuture<>();
    raft.getServiceManager().<OperationResult>apply(entry).whenComplete((result, error) -> {
      completeOperation(result, QueryResponse.builder(), error, future);
    });
    return future;
  }
1094464
protected final void rangeCheck (int index, boolean insert)
    {
        if ((index < 0) || (insert ? (index > _size) : (index >= _size))) {
            throw new IndexOutOfBoundsException(
                "Index: " + index + ", Size: " + _size);
        }
    }
622969
@Managed
   @ManagedDescription("Index optimization ")
   public void optimize()
   {
      if (handler instanceof SearchIndex)
      {
         try
         {
            if (isSuspended.get())
            {
               resume();

               try
               {
                  ((SearchIndex)handler).getIndex().optimize();
               }
               finally
               {
                  suspend();
               }
            }
            else
            {
               ((SearchIndex)handler).getIndex().optimize();
            }
         }
         catch (IOException e)
         {
            LOG.error(e.getMessage(), e);
         }
         catch (ResumeException e)
         {
            LOG.error(e.getMessage(), e);
         }
         catch (SuspendException e)
         {
            LOG.error(e.getMessage(), e);
         }
      }
      else
      {
         LOG.error("This kind of QuerHandler class doesn't support index optimization.");
      }
   }
217057
function processLookupResults(intInds, key, opts, resultArr) {
  if (intInds === null) {
    if (opts.resolveMode === RESOLVE_MODE.COL) {
      throw new Error('could not find column named "' + key + '"');
    } else {
      throw new Error('could find entry for key: ' + key);
    }
  } else if (typeof intInds === 'number') {
    resultArr.push(intInds);
  } else {
    for (var j = 0; j < intInds.length; j++) {
      resultArr.push(intInds[j]);
    }
  }
}
302338
def need_completion_refresh(queries):
    """"""
    tokens = {
        'use', '\\u',
        'create',
        'drop'
    }

    for query in sqlparse.split(queries):
        try:
            first_token = query.split()[0]
            if first_token.lower() in tokens:
                return True
        except Exception:
            return False
1361332
def apply_offset(self):
    ''''''
    self._ensure_modification_is_safe()

    if self.query.offset != 0:
      self._iterable = \
        offset_gen(self.query.offset, self._iterable, self._skipped_inc)