Find a given record
@param domain
@param query
@return {Promise}
342885
function find(domain, query) {
    if (query.name && !query.name.includes(domain)) {
      query.name = query.name + '.' + domain;
    }
    if (query.query) {
      query = _.extend(query, query.query);
      delete query.query;
    }
    return getZone(domain).then(function (zone) {
      return self.cloudflareClient.findRecord(zone.id, query);
    });
  }
945267
function queryChecker(checkQuery) {
  if (!checkQuery) {
    throw new Error('check query can not be null');
  }
  debug('query checker conditions:%s', checkQuery);
  const arr = checkQuery.split('&');
  const checkParams = {};
  const checkKeys = [];
  arr.forEach((str) => {
    const tmpArr = str.split('=');
    const key = tmpArr[0];
    checkKeys.push(key);
    checkParams[key] = tmpArr[1];
  });

  return (ctx, next) => {
    const query = ctx.query;
    debug('query:%j', query);
    let valid = true;
    checkKeys.forEach((key) => {
      if (valid && query[key] !== checkParams[key]) {
        valid = false;
      }
    });

    if (valid) {
      return next();
    }
    const originalUrl = ctx.originalUrl;
    const urlInfo = url.parse(originalUrl);
    checkKeys.forEach((key) => {
      query[key] = checkParams[key];
    });
    /* eslint no-param-reassign:0 */
    ctx.status = 302;
    ctx.set('Cache-Control', 'no-cache, no-store, max-age=0');
    ctx.redirect(`${urlInfo.pathname}?${qs.stringify(query)}`);
    return null;
  };
}
574127
function findById(schemaName, id) {
	return new Promise(function(resolve, reject) {
		var Model = db.mongoose.model(schemaName);

		Model
		.findById(id)
		.exec(function(error, result) {
			if (error) {
				reqlog.error('internal server error', error);
				reject(error);
			} else {
				resolve(result || 'notFound');
			}
		});
	});
}
1089894
def query_domain(self, domain, typenames, domainquerytype='list', count=False):
        

        objects = self._get_repo_filter(Layer.objects)

        if domainquerytype == 'range':
            return [tuple(objects.aggregate(Min(domain), Max(domain)).values())]
        else:
            if count:
                return [(d[domain], d['%s__count' % domain])
                        for d in objects.values(domain).annotate(Count(domain))]
            else:
                return objects.values_list(domain).distinct()
22300
def get_record(self, domain, record):
        
        rec_id = utils.get_id(record)
        domain_id = utils.get_id(domain)
        uri = "/domains/%s/records/%s" % (domain_id, rec_id)
        resp, resp_body = self._retry_get(uri)
        resp_body["domain_id"] = domain_id
        return CloudDNSRecord(self, resp_body, loaded=False)
1155455
function ServerQueryList(qry, limit, Resource) {
      // Allow qry to be a promise
      qry = $q
        .when(qry)
        .then(normalizeQuery)
        .then(function(_qry) {
          if (limit) {
            _qry.limit = limit;
          }
          return _qry;
        });

      var emitPromise = null;
      var results = new ArrayEmitter();
      var currentLimit = 0;
      var currentSkip = 0;
      var lastBatchSize = 0;
      var _pagingOpts = {};

      results.loading = true;

      function query(data) {
        // We only want to do one emit at a time (otherwise we could get into a bad state)
        if (angular.isFunction(data)) {
          data = data();
        }

        // Store off the query - make sure its a promise
        qry = $q.when(data);

        return qry.then(function(data) {
          // If we have an existing emitPromise then wait for it to resolve before we run
          var promise;
          if (emitPromise) {
            promise = emitPromise.then(function() {
              return sock.query(data);
            });
          } else {
            emitPromise = promise = sock.query(data);
          }

          return promise;
        });
      }

      function newData(_qryId, response, force) {
        if (!response) {
          return;
        }

        var deferred = $q.defer();
        var ids = response.ids;
        var pagingOpts = response.pagingOpts;

        // So far we've only got the ids of the qry result - go and fetch the actual objects.
        // This mechanism saves bandwidth by only getting the object data once then listening
        // for changes to it
        //
        // If we are forcing we want to get both the old and new ids to check for any changes
        // deletions etc..
        var getIds = ids;
        if (force) {
          var oldIds = pluck(results, '_id');
          getIds = union(ids, oldIds);
        }

        Resource.get(getIds, force).$promise.then(function(ress) {
          var ressmap = {};
          ress.forEach(function(res) {
            ressmap[res._id] = res;
          });

          // We don't allow repeated ids so just iterate over the results
          var tmpResults = [];
          ids.forEach(function(id) {
            tmpResults.push(ressmap[id]);
          });

          // Do we need to do a transform?
          var rprom;
          if (angular.isFunction(results.transform)) {
            rprom = $q.when(results.transform(tmpResults));
          } else {
            rprom = $q.when(tmpResults);
          }

          return rprom.then(function(transformed) {
            results.length = 0;
            transformed.forEach(function(res) {
              results.push(res);
            });

            // Since we now have data in our array store off limit data
            currentLimit = tmpResults.length;
            results.$skip = currentSkip = qry && qry.skip ? qry.skip : 0;
            lastBatchSize = lastBatchSize || tmpResults.length;
            _pagingOpts = pagingOpts;
            results.hasNext = pagingOpts.next != null;
            results.hasPrev = pagingOpts.prev != null;

            // Data has come back
            results.loading = false;

            results.$emitter.emit('update', results);

            deferred.resolve(results);
          });
        });

        return deferred.promise;
      }

      function refreshQuery(force) {
        var req = query(qry);
        var promise = req.then(function(res) {
          // If we get no response (the app could be offline) then just resolve with
          // the existing results
          if (angular.isUndefined(res)) {
            results.loading = false;
            return results;
          }

          var _qryId = res.qryId;
          var response = res.data;

          return newData(_qryId, response, force);
        });
        return promise;
      }

      function replace(_qry) {
        // Do the query but replace the existing query
        return $q
          .when(_qry)
          .then(normalizeQuery)
          .then(function(normQry) {
            // We allow a query to resolve to something falsy - in which case we just
            // drop it
            if (!normQry) {
              return;
            }

            return qry.then(function(oldqry) {
              if (JSON.stringify(oldqry) !== JSON.stringify(normQry)) {
                // query is different - continue
                var req = query(normQry);

                var promise = req.then(function(res) {
                  // If we get no response (the app could be offline) then just resolve with
                  // the existing results
                  if (angular.isUndefined(res)) {
                    results.loading = false;
                    return results;
                  }

                  // We do have a response. Continue
                  var _qryId = res.qryId;
                  var data = res.data;

                  return newData(_qryId, data);
                });

                return promise;
              }
            });
          });
      }

      function extendResults(obj, noSanitize) {
        // Sanitize the object
        if (!noSanitize) {
          if (obj._q) {
            obj = obj._q;
          } else {
            obj = { find: obj };
          }
        }

        return qry.then(function(resolved) {
          var _qry = extendQuery(resolved, obj);
          return replace(_qry);
        });
      }

      function next(num) {
        var promise;
        var extendSize;
        if (_pagingOpts.next) {
          lastBatchSize = extendSize = num || lastBatchSize;
          var extendObj = {
            limit: currentLimit + extendSize
          };
          promise = extendResults(extendObj, true);
        } else {
          var deferred = $q.defer();
          deferred.resolve();
          promise = deferred.promise;
        }

        return promise;
      }

      function prev(num) {
        var promise;
        var extendSize;
        if (_pagingOpts.prev) {
          lastBatchSize = extendSize = num || lastBatchSize;
          var extendObj = {
            skip: Math.max(currentSkip - extendSize, 0),
            limit: currentLimit + extendSize
          };
          promise = extendResults(extendObj, true);
        } else {
          var deferred = $q.defer();
          deferred.resolve();
          promise = deferred.promise;
        }

        return promise;
      }

      function get() {
        return Resource.get.apply(Resource, arguments);
      }

      function chain(Model, qryFn) {
        return Chain(results, Model, qryFn);
      }

      results.$newData = newData;
      results.$refresh = refreshQuery;
      results.extend = extendResults;
      results.replace = replace;
      results.get = get;
      results.next = next;
      results.prev = prev;
      results.$promise = refreshQuery().then(function(res) {
        results.$resolved = true;
        return res;
      });
      results.$resolved = false;
      results.chain = chain;
      results.$Model = Resource;
      results.$skip = 0;

      // Put currentSkip and currentLimit onto the results
      Object.defineProperty(results, 'currentLimit', {
        enumerable: true,
        get: () => {
          return currentLimit;
        }
      });
      Object.defineProperty(results, 'currentSkip', {
        enumerable: true,
        get: () => {
          return currentSkip;
        }
      });

      return results;
    }
672962
function(query, mongooseQuery, logger) {
    const Log = logger.bind()
    if (query.$page) {
      mongooseQuery = this.setPage(query, mongooseQuery, Log)
    } else {
      mongooseQuery = this.setSkip(query, mongooseQuery, Log)
    }

    mongooseQuery = this.setLimit(query, mongooseQuery, Log)

    return mongooseQuery
  }
311825
public T findOne(DBObject query, DBObject fields) {
        return findOne(query, fields, getReadPreference());
    }
1163343
function runQuery(query, connection) {
  let incomplete = false;
  const rows = [];

  const drillConfig = {
    host: connection.host,
    port: connection.port,
    user: connection.username,
    password: connection.password,
    defaultSchema: connection.drillDefaultSchema,
    ssl: connection.ssl || false
  };
  const client = new drill.Client(drillConfig);

  return client.query(drillConfig, query).then(result => {
    if (!result) {
      throw new Error('No result returned');
    } else if (result.errorMessage && result.errorMessage.length > 0) {
      console.log('Error with query: ' + query);
      console.log(result.errorMessage);
      throw new Error(result.errorMessage.split('\n')[0]);
    }
    if (result.length > connection.maxRows) {
      incomplete = true;
      result['rows'] = result['rows'].slice(0, connection.maxRows);
    }
    for (let r = 0; r < result['rows'].length; r++) {
      const row = {};
      for (let c = 0; c < result['columns'].length; c++) {
        row[result['columns'][c]] = result['rows'][r][result['columns'][c]];
      }
      rows.push(row);
    }
    return { rows, incomplete };
  });
}
678094
function query (query, params, options, session) {
    // require string for query
    if (typeof query !== 'string') {
        throw new Error('query error: query must be string')
    }
    // validate optional args - create objects if not passed in
    options = requireValidOptionalObject(options)
    params = requireValidOptionalObject(params)
    session = requireValidOptionalObject(session)
    // if the no insert flag is set then do not run insert queries
    if (session.noInsert && query.match(/^\s*INSERT/i)) {
        return Promise.resolve()
    }
    // get unique if for query
    var dbQueryId = randomUniqueId()
    // log query start
    this.logQuery(query, params, options, session, dbQueryId)
    // perform query using promisified interface
    return this.client.queryPromise(query, params, options)
    // success
    .then(res => {
        // perform formatting on response data
        formatResponse(res)
        // log response
        this.logQueryResponse(dbQueryId, options, res)
        // resolve with response data
        return res
    })
    // error
    .catch(err => {
        // log error
        this.logQueryError(dbQueryId, options, err)
        // reject with error
        return Promise.reject(err)
    })
}
458560
function runQuery(query, connection, user) {
  const driver = drivers[connection.driver];

  const queryResult = {
    id: uuid.v4(),
    cacheKey: null,
    startTime: new Date(),
    stopTime: null,
    queryRunTime: null,
    fields: [],
    incomplete: false,
    meta: {},
    rows: []
  };

  return driver.runQuery(query, connection).then(results => {
    const { rows, incomplete } = results;
    if (!Array.isArray(rows)) {
      throw new Error(`${connection.driver}.runQuery() must return rows array`);
    }

    queryResult.incomplete = incomplete || false;
    queryResult.rows = rows;
    queryResult.stopTime = new Date();
    queryResult.queryRunTime = queryResult.stopTime - queryResult.startTime;
    queryResult.meta = getMeta(rows);
    queryResult.fields = Object.keys(queryResult.meta);

    if (debug) {
      const connectionName = connection.name;
      const rowCount = rows.length;
      const { startTime, stopTime, queryRunTime } = queryResult;

      console.log(
        JSON.stringify({
          userId: user && user._id,
          userEmail: user && user.email,
          connectionName,
          startTime,
          stopTime,
          queryRunTime,
          rowCount,
          query
        })
      );
    }

    return queryResult;
  });
}
876632
function _find(collection, query, opts) {
  if (Tyr.logging.trace) {
    Tyr.trace({ e: 'db', c: collection.id, m: 'find', q: query });
    const cursor = collection.db.find(query, opts);
    //Tyr.Log.updateDuration(logPromise);
    return cursor;
  } else {
    return collection.db.find(query, opts);
  }
}
1326555
function query(connection, ...params){
    return new Promise(function(resolve, reject){
        // execute query
        connection.query(...params, function(err, result, fields){
            if (err){
                reject(err);
            }else{
                resolve([result, fields]);
            }
        });
    });
}
365631
function query (query) {
    // if cache is not connected immediately execute query and do not cache
    if (!this.redis.connected) {
        debug(`cache:${this.model.name}:false:redis:disconnected`)
        return query.executeQuery()
    }
    // build args for cache query instance
    var cacheQueryArgs = {
        cache: this,
        query: query,
    }
    // cache query object
    var cacheQuery
    // if query has views then cache after views are applied
    if (defined(query.modelViewEngine)) {
        // view query where underlying query is by id
        if (query.select.isSelectById) {
            // collection view is being applied
            if (query.modelViewEngine.hasCollection) {
                debug('cache:${this.model.name}:view:id:collection:true')
                // build cache query object
                cacheQuery = new ImmutableCoreModelCacheQueryViewIdCollection(cacheQueryArgs)
            }
            // only record view(s) being applied
            else {
                debug(`cache:${this.model.name}:view:id:record:true`)
                // build cache query object
                cacheQuery = new ImmutableCoreModelCacheQueryViewIdRecord(cacheQueryArgs)
            }
        }
        // view query where underlying query is select
        else if (query.select.isSelectOnlyIds && defined(query.model.columns.n)) {
            // if collection view is applied then cache result - if only
            // record view(s) are applied they are cached by id queries
            if (query.modelViewEngine.hasCollection) {
                debug(`cache:${this.model.name}:view:select:collection:true`)
                // build cache query object
                cacheQuery = new ImmutableCoreModelCacheQueryViewSelectCollection(cacheQueryArgs)
            }
        }
    }
    // if query is select by id then cache result
    else if (query.select.isSelectById) {
        debug(`cache:${this.model.name}:id:true`)
        // build cache query object
        cacheQuery = new ImmutableCoreModelCacheQueryId(cacheQueryArgs)
    }
    // if query has views then cache after views are applied
    else if (query.select.isSelectOnlyIds && defined(query.model.columns.n)) {
        debug(`cache:${this.model.name}:select:true`)
        // build cache query object
        cacheQuery = new ImmutableCoreModelCacheQuerySelect(cacheQueryArgs)
    }
    // execute cache query if available
    if (defined(cacheQuery)) {
        return cacheQuery.cacheQuery()
    }
    // execute original query uncached
    else {
        debug(`cache:${this.model.name}:false:unsupported`)
        return query.executeQuery()
    }
}
486671
function(query) {
        var self = this;
        return Q.ninvoke(fs, 'readdir', path.join(this.backend.options.path, this.name))
            .then(function(files) {
                return Q.all(files.map(function(f) {
                    return self.get(f);
                }));
            })
            .then(function(vals) {
                return _.query(vals, query);
            });
    }
672014
function fetch (fetchNum, offset) {
    // if all records already fetched resolve with undefined
    if (this.done) {
        return Promise.resolve([])
    }
    // set default fetchNum
    if (!fetchNum) {
        fetchNum = this.fetchNum
    }
    // if offset is set then set fetched with offset
    if (offset) {
        this.fetched = offset
    }
    // if fetchNum exceeds numner of remaining records then set to max
    fetchNum = _.clamp(fetchNum, this.length - this.fetched)
    // get list of ids to fetch
    var ids = this.ids.slice(this.fetched, this.fetched + fetchNum)
    // create where args for records query
    var whereArgs = {id: ids}
    // if isDeleted was set on original query then set for fetch
    if (defined(this.query.args.where.isDeleted)) {
        whereArgs.isDeleted = this.query.args.where.isDeleted
    }
    // fetch records
    return this.query.model.query({
        all: true,
        allow: this.query.args.allow,
        cache: this.query.args.cache,
        plain: this.query.args.plain,
        raw: this.query.args.raw,
        resolve: this.query.args.resolve,
        session: this.query.session,
        where: whereArgs,
        with: this.query.args.with,
        view: this.applyView ? this.query.args.view : false,
    })
    .then(records => {
        // add number of fetched records to count of fetched
        this.fetched += fetchNum
        // set done to true when all records fetched
        if (this.fetched === this.length) {
            this.done = true
        }

        return records
    })
}
84392
def find(query = {})
      query = query.map { |k, v| [FIELDS[k], v] if FIELDS[k] }.compact.to_h
      resource = query.delete(RESOURCE)
      matches = validate(
        find_all_cached_entries(
          query.reverse_merge(
            authority: @authority, client_id: @client.client_id))
      )
      resource_specific(matches, resource) || refresh_mrrt(matches, resource)
    end