== View and multi-document based queries
 Query a CouchDB view as defined by a <tt>_design</tt> document. Accepts
 paramaters as described in http://wiki.apache.org/couchdb/HttpViewApi
182609
def view(name, params = {}, payload = {}, &block)
      opts = {}
      params = params.dup
      payload['keys'] = params.delete(:keys) if params[:keys]

      # Continuous feeds need to be parsed differently
      opts[:continuous] = true if params['feed'] == 'continuous'

      # Try recognising the name, otherwise assume already prepared
      view_path = name_to_view_path(name)
      req_path = CouchRest.paramify_url("#{path}/#{view_path}", params)

      if payload.empty?
        connection.get req_path, opts, &block
      else
        connection.post req_path, payload, opts, &block
      end
    end
81575
def get_view_doc(view, html=True):
    
    try:
        description = view.__doc__ or ''
        description = formatting.dedent(smart_text(description))

        # include filters in description
        filter_fields = get_filter_fields(view)
        if filter_fields:
            filter_doc = ['\n\n\n## Filters', '']
            for f in filter_fields:
                filter_doc.append('- `%s`' % f)
            description += '\n'.join(filter_doc)

        # replace {api_url} by current base url
        api_url = "/api"
        description = description.replace('{api_url}', api_url)
        if html:
            description = formatting.markup_description(description)
        return description
    except:
        import traceback
        traceback.print_exc()
        raise
40281
def view_exists?(query)
      if query.nil?
        raise ArgumentError, 'Query cannot be nil'
      end

      result = query(query)

      !result.empty?
    end
196636
def get_query(self):
        

        query = super(ExpandableViewMixin, self).get_query()
        expandable_fields = getattr(self, 'expandable_fields', [])

        if expandable_fields:
            requested_expands = parse_requested_expands(self.schema_class.QUERY_KEY, self.request)

            if requested_expands:
                available_expands = self.expandable_fields.keys()

                for name in requested_expands:
                    if name in available_expands:
                        field = self.expandable_fields[name]

                        innerjoin = field.get('join')
                        outerjoin = field.get('outerjoin')

                        if innerjoin:
                            query = query.join(innerjoin)
                        elif outerjoin:
                            query = query.outerjoin(outerjoin)

                        # Apply optional options
                        options = field.get('options')

                        if options:
                            query = query.options(*options)

        return query
695062
function(query, callback) {
      return nano.request({ path: encodeURIComponent(db) + '/_find',
        method: 'post',
        body: query}, callback);
    }
102220
def query(self,
              layerDefsFilter=None,
              geometryFilter=None,
              timeFilter=None,
              returnGeometry=True,
              returnIdsOnly=False,
              returnCountOnly=False,
              returnZ=False,
              returnM=False,
              outSR=None
              ):
        
        qurl = self._url + "/query"
        params = {"f": "json",
                  "returnGeometry": returnGeometry,
                  "returnIdsOnly": returnIdsOnly,
                  "returnCountOnly": returnCountOnly,
                  "returnZ": returnZ,
                  "returnM" : returnM}
        if not layerDefsFilter is None and \
           isinstance(layerDefsFilter, LayerDefinitionFilter):
            params['layerDefs'] = layerDefsFilter.filter
        if not geometryFilter is None and \
           isinstance(geometryFilter, GeometryFilter):
            gf = geometryFilter.filter
            params['geometryType'] = gf['geometryType']
            params['spatialRel'] = gf['spatialRel']
            params['geometry'] = gf['geometry']
            params['inSR'] = gf['inSR']
        if not outSR is None and \
           isinstance(outSR, SpatialReference):
            params['outSR'] = outSR.asDictionary
        if not timeFilter is None and \
           isinstance(timeFilter, TimeFilter):
            params['time'] = timeFilter.filter

        res = self._post(url=qurl,
                            param_dict=params,
                            securityHandler=self._securityHandler,
                            proxy_url=self._proxy_url,
                            proxy_port=self._proxy_port)
        if returnIdsOnly == False and returnCountOnly == False:
            if isinstance(res, str):
                jd = json.loads(res)
                return [FeatureSet.fromJSON(json.dumps(lyr)) for lyr in jd['layers']]
            elif isinstance(res, dict):
                return [FeatureSet.fromJSON(json.dumps(lyr)) for lyr in res['layers']]
            else:
                return res
        return res
517794
protected ViewQuery createQuery(String viewName) {
		return new ViewQuery()
				.dbPath(db.path())
				.designDocId(stdDesignDocumentId)
				.viewName(viewName);
	}
166817
@View(name = "by_linkedid", map = "function(doc) { if(doc.linkedid){ emit(doc.linkedid, doc) } }")
    public CouchDbProfileDocument findByLinkedid(final String linkedid) {
        return queryView("by_linkedid", linkedid).stream().findFirst().orElse(null);
    }
679128
public Set<DOCUMENT> query(@NonNull DOCUMENT document, @NonNull Predicate<? super DOCUMENT> filter) {
      return query(documentMapper.apply(document), filter);
   }
962738
public CouchDbSamlIdPMetadataDocument getOne() {
        val view = createQuery("all").limit(1);
        return db.queryView(view, CouchDbSamlIdPMetadataDocument.class).stream().findFirst().orElse(null);
    }
550702
def _query_view(self, model, **kwargs):
        
        QueryForm = functions.get_form('QueryForm')

        if 'form_cls' not in kwargs:
            kwargs['form_cls'] = QueryForm
        query = functions.QueryView(model, **kwargs)
        return query
231124
@Override
    public DesignDocument getFromDatabase(CouchDbConnector db, String designDocumentId) {
    	return db.get(DesignDocument.class, designDocumentId);
    }
1184756
def _verify_views():
    '''
    
    '''
    global VERIFIED_VIEWS

    if VERIFIED_VIEWS or __opts__.get('couchbase.skip_verify_views', False):
        return
    cb_ = _get_connection()
    ddoc = {'views': {'jids': {'map': "function (doc, meta) { if (meta.id.indexOf('/') === -1 && doc.load){ emit(meta.id, null) } }"},
                      'jid_returns': {'map': "function (doc, meta) { if (meta.id.indexOf('/') > -1){ key_parts = meta.id.split('/'); emit(key_parts[0], key_parts[1]); } }"}
                      }
            }

    try:
        curr_ddoc = cb_.design_get(DESIGN_NAME, use_devmode=False).value
        if curr_ddoc['views'] == ddoc['views']:
            VERIFIED_VIEWS = True
            return
    except couchbase.exceptions.HTTPError:
        pass

    cb_.design_create(DESIGN_NAME, ddoc, use_devmode=False)
    VERIFIED_VIEWS = True
465197
List createAndExecuteQuery(CouchDBQueryInterpreter interpreter)
    {
        EntityMetadata m = interpreter.getMetadata();
        List results = new ArrayList();
        try
        {
            MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata().getMetamodel(
                    m.getPersistenceUnit());
            StringBuilder q = new StringBuilder();
            String _id = CouchDBConstants.URL_SEPARATOR + m.getSchema().toLowerCase() + CouchDBConstants.URL_SEPARATOR
                    + CouchDBConstants.DESIGN + m.getTableName() + CouchDBConstants.VIEW;
            if ((interpreter.isIdQuery() && !interpreter.isRangeQuery() && interpreter.getOperator() == null)
                    || interpreter.isQueryOnCompositeKey())
            {
                Object object = null;
                if (metaModel.isEmbeddable(m.getIdAttribute().getBindableJavaType()))
                {
                    EmbeddableType embeddableType = metaModel.embeddable(m.getIdAttribute().getBindableJavaType());
                    if (KunderaCoreUtils.countNonSyntheticFields(m.getIdAttribute().getBindableJavaType()) == interpreter
                            .getKeyValues().size())
                    {
                        Object key = CouchDBObjectMapper.getObjectFromJson(gson.toJsonTree(interpreter.getKeyValues())
                                .getAsJsonObject(), m.getIdAttribute().getBindableJavaType(), embeddableType
                                .getAttributes());
                        object = find(m.getEntityClazz(), key);
                        if (object != null)
                        {
                            results.add(object);
                        }
                        return results;
                    }
                    else if (m.getIdAttribute().getName().equals(interpreter.getKeyName())
                            && interpreter.getKeyValues().size() == 1)
                    {
                        object = find(m.getEntityClazz(), interpreter.getKeyValue());
                        if (object != null)
                        {
                            results.add(object);
                        }
                        return results;
                    }
                    else
                    {
                        log.error("There should be each and every field of composite key.");
                        throw new QueryHandlerException("There should be each and every field of composite key.");
                    }
                }
                object = find(m.getEntityClazz(), interpreter.getKeyValue());
                if (object != null)
                {
                    results.add(object);
                }
                return results;
            }

            // creating query.
            _id = createQuery(interpreter, m, q, _id);

            if (interpreter.getLimit() > 0)
            {
                q.append("&limit=" + interpreter.getLimit());
            }
            if (interpreter.isDescending())
            {
                q.append("&descending=" + false);
            }

            // execute query.
            executeQueryAndGetResults(q, _id, m, results, interpreter);
        }
        catch (Exception e)
        {
            log.error("Error while executing query, Caused by {}.", e);
            throw new KunderaException(e);
        }
        return results;
    }
690860
function(db) {

		function get_documents(data, config, plv8, ERROR, WARNING) {

			function get_document(id, fields) {
				fields = (fields || [{'query':'*'}]);

				var map = {};

				var obj = plv8.execute("SELECT "+fields.map(function(f, i) {
					var k;
					if(f.key) {
						k = 'p__' + i;
						map[k] = f;
						return f.query + ' AS ' + k;
					} else {
						return f.query;
					}
				}).join(', ')+" FROM documents WHERE id = $1 LIMIT 1", [id])[0];

				if(!obj) {
					return obj;
				}

				Object.keys(obj).forEach(function(key) {
					if(!map.hasOwnProperty(key)) {
						return;
					}

					var spec = map[key];
					if(!is_object(spec)) {
						return error('mapped resource missing');
					}
					if(!is_string(spec.key)) {
						return error('key missing');
					}
					var value = obj[key];
					delete obj[key];

					if(is_string(spec.datakey)) {
						if(!obj[spec.datakey]) {
							obj[spec.datakey] = {};
						}
						obj[spec.datakey][spec.key] = value;
					} else {
						obj[spec.key] = value;
					}
				});

				return obj;
			}

			//function get_type(id) {
			//	return plv8.execute("SELECT * FROM types WHERE id = $1 LIMIT 1", [id])[0];
			//}

			function error(msg) {
				plv8.elog(ERROR, msg);
			}

			function warn(msg) {
				plv8.elog(WARNING, msg);
			}

			function is_object(a) {
				return a && (typeof a === 'object');
			}

			function is_array(a) {
				return a && (a instanceof Array);
			}

			function is_string(a) {
				return a && (typeof a === 'string');
			}

			function is_uuid(obj) {
				return /^[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12}$/.test(obj);
			}

			function get_property_step(last, current) {
				return is_object(last) ? last[current] : undefined;
			}

			/** Get value of property from provided object using a path.
			 * @param obj {object} The object from where to find the value.
			 * @param path {string} The path to the value in object.
			 * @returns {mixed} The value from the object at the end of path or `undefined` if any part is missing.
			 */
			function get_property(obj, path) {
				if(!is_object(obj)) { return error('get_property(obj, ...) not object: '+ obj); }
				if(!is_string(path)) { return error('get_property(..., path) not string: '+ path); }
				return path.split('.').reduce(get_property_step, obj);
			}

			/** Get document by UUID */
			function fetch_object_by_uuid(data, prop, fields, uuid) {
				if(!is_object(data)) { return error('fetch_object_by_uuid(data, ..., ...) not object: '+ data); }
				if(!is_string(prop)) { return error('fetch_object_by_uuid(..., prop, ...) not string: '+ prop); }
				if(!is_uuid(uuid)) { return warn('Property ' + prop + ' was not uuid: ' + uuid); }
				if(data.documents[uuid] === undefined) {
					data.documents[uuid] = get_document(uuid, fields);
				} else {
					return warn('Document already fetched: ' + uuid);
				}
			}

			/* */
			function fetch_object(data, config) {
				var prop, fields;

				if(is_object(config)) {
					prop = config.prop;
					fields = config.fields;
				} else if(is_string(config)) {
					prop = config;
				}

				if(!is_string(prop)) {
					return error('property is not valid: ' + prop);
				}

				fields = fields ? fields : [{'query':'*'}];

				if(!is_array(fields)) {
					return error('fields are not valid: ' + fields);
				}

				var uuid = get_property(data, prop);

				if(is_array(uuid)) {
					// FIXME: This could be implemented with one query
					return uuid.forEach(fetch_object_by_uuid.bind(undefined, data, prop, fields));
				}
				return fetch_object_by_uuid(data, prop, fields, uuid);
			}

			// Check for bad input

			if(!is_object(data)) { return error("get_documents(data, ...) not object"); }
			if(!is_array(config)) { return error("get_documents(..., config) not array"); }

			//var types_id = data.types_id;
			//if(!is_uuid(types_id)) { return error("data.types_id not valid UUID: " + types_id); }

			// Get document type
			//var type = get_type(types_id);
			//if(!is_object(type)) { return error("type not valid object: " + type); }

			//var relations = type.relations || {};
			//if(!is_object(relations)) { return error("type.relations not valid object: " + relations); }

			// Populate documents from `config`
			data.documents = {};
			config.forEach( fetch_object.bind(undefined, data) );
			return data.documents;
		}

		return db.query('CREATE OR REPLACE FUNCTION get_documents(data json, config json) RETURNS json LANGUAGE plv8 VOLATILE AS ' + NoPg._escapeFunction(get_documents, ["data", "config", "plv8", "ERROR", "WARNING"]));
	}
831547
def design_docs
      req = __http_query(:management, :get, "/pools/default/buckets/#{bucket}/ddocs", nil, nil, nil, nil, nil)
      docmap = {}
      res = MultiJson.load(req[:chunks].join)
      res["rows"].each do |obj|
        obj['doc']['value'] = obj['doc'].delete('json') if obj['doc']
        doc = DesignDoc.new(self, obj)
        next if environment == :production && doc.id =~ /dev_/
        docmap[doc.id] = doc
      end
      docmap
    end
668511
def has_item(self, url):
        

        _hash = self.build_hash(url)
        query = {'_id': _hash}
        doc = self.dbase.cache.find_one(query, {'id': 1})
        return doc is not None