/* 提取query中_mcss字段和combo的元素
354766
function(query) {
        var queryObj = {q: ''};
        if(!query) {
            return queryObj;
        }

        var qArray = query.split('&');
        var qObj = qs.parse(query);
        for(var i = 0, len = qArray.length; i < len; i++) {
            var queryItem = decodeURIComponent(qArray[i]).replace('=', '');
            if(/^\?/g.test(queryItem)) {
                debug('matched query: %s', queryItem) ;
                queryObj.q = queryItem;
                break;
            }
        }

        queryObj.m = qObj._mcss == 'true' || qObj._mcss == 'y';
        return queryObj;
    }
84406
function joinQuery(queryObj, skipEmpties)
{
	var i,len,value,varname;
	var count = { i:0 };  // literals do not persist across functions
	var output = "";
	
	for (varname in queryObj)
	{
		if (queryObj.hasOwnProperty(varname)===true)
		{
			value = queryObj[varname];
			
			// "?var1=a&var1=b" would've been parsed to { var1: ["a","b"] }
			if (Array.isArray(value) === false)
			{
				output += joinValue(varname, value, count, skipEmpties);
			}
			else
			{
				len = value.length;
				
				for (i=0; i<len; i++)
				{
					output += joinValue(varname, value[i], count, skipEmpties);
				}
			}
		}
	}
	
	return output;
}
1121143
function (qs) {
        var items = qs.split('&');
        var options = {};
        items = items.filter(function (item) {
            return item.match(/^[\w_-]+=?$|^[\w_-]+=[^=]+$/);
        }).forEach(function (item) {
            var kv = item.split('=');
            var value = kv[1];
            if (value === undefined || value === '') {
                value = true;
            }
            else if (value.toLowerCase() === 'false') {
                value = false;
            }
            options[kv[0]] = value;
        });

        return options;
    }
578672
public Query getMiniSelectQuery(Collection<String> columns, Collection<Match> matches) {
        int matchSize = matches == null ? 0 : matches.size();

        int maxSqlLength = matches == null ? 50 : (matchSize + 3) * 10;
        StringBuilder sb = new StringBuilder(maxSqlLength);

        // SQL语句和参数列表的构造
        sb.append("select ");
        if (columns == null || columns.size() == 0) {
            sb.append("*,");
        } else {
            for (String column : columns) {
                sb.append(column).append(',');
            }
        }
        sb.deleteCharAt(sb.length() - 1);
        sb.append(" from ").append(dao.getTableName());

        if (matchSize == 0) {
            return new Query(sb.toString(), new ArrayList<Object>(0));
        }

        // 如果有条件
        List<Object> params = new ArrayList<Object>(matchSize + 1);
        appendQuerytoSQL(matches, sb, params);
        return new Query(sb.toString(), params);
    }
10860
function(z_query) {
			
			// hash query
			if(typeof z_query == 'object') {
				return query_hash(z_query);
			}
			// string
			else if(typeof z_query == 'string') {

				if(z_query[0] == ':' || z_query[0] == '?') {
					return qb({
						select: '',
						where: '\n'+z_query,
						tail: '',
						group: '',
						order: '',
						limit: '',
					});
				}

				return query_string(z_query);
			}
		}
588912
function(schemaName, where, cb, options) {
  if (arguments.length < 2) {
    cb && cb(new Error('select error: invalid params'))
    return
  }

  /*
  No where provider?
  */
  else if (where instanceof Function) {
    options = cb
    cb      = where
    where   = {}
  }

  options = options || {}

  var schema      = SCHEMA[schemaName]
    , conditions  = Object.keys(where)
    , count1      = 0
    , count2      = 0
    //选择条件， 这些条件只在有序集合中起作用
    , from        = typeof options.from == 'number' ? options.from : 0
    , to          = typeof options.to == 'number' ? options.to : 1000
    , desc        = options.desc


  var getFromIDs = function(objectIDs) {
    /*
    集合ID为空，直接返回
    */
    if (objectIDs.length < 1) {
      cb && cb(null, [])
      return
    }

    /*
    将交集集合提取元素
    */
    var count2  = 0
      , objects = []


    var isAllDone = function(err) {
      if (err) {
        console.error(err)
      }

      if (++count2 == objectIDs.length) {
        //如果是删除操作符，则只返回受影响行数
        if (options.mode == 'remove') {
          cb && cb(null, count2)
        } else {
          cb && cb(null, objects)
        }
      }
    }

    var getObject = function(id) {
      var key = schemaName + ':' + id

      var onRemoveRelate = function(err, result) {
        if (err) {
          console.error(err)
        }

        client.del(key, isAllDone)
      }

      var onGetAll = function(err, object) {
        if (err) {
          console.error(err)
        } else if (options.mode == 'remove' && object) {
          removeRelate(schemaName, object, onRemoveRelate)
          //Avoid isAllDone execute twice
          return
        } else if (object) {
          objects.push(object)
        }

        isAllDone()
      }

      client.hgetall(key, onGetAll)
    }

    objectIDs.forEach(getObject)
  }


  /*
  ********************************************************
  CASE 1: 有序集合和无序集合，相互交集，分别查询出列表，并将所有集合并求其交集
  ********************************************************
  */
  var resultHandler = function(results) {
    /*
    将所有集合求其交集; 第一个集合是最小的数组
    */
    results.sort(function(a, b) {
      a.length - b.length
    })

    var firstArr  = results[0].length
      , objectIDs = []

    for (var i = 0; i < results[0].length; i++) {
      var item = results[0][i]
        , flag = true

      for (var j = 1; j < results.length; j++) {
        if (results[j].indexOf(item) < 0) {
          flag = false
          j = results.length
        }
      }

      flag && objectIDs.push(item)
    }

    getFromIDs(objectIDs)
  }

  /*
  将where中的每个条件的集合提取出来；如果全部条件均为set则可使用inter, union等连接查询指令
  */
  var multi   = client.multi()
      //所有集合均是set
    , skeys   = []
      //所有集合均是sorted set
    , zkeys   = []

  var conditionHandler = function(condition) {
    count1++

    /*
    查询的字段在schema中有无定义
    condition: email
    rules:     { shown: [], email: [], minlen: [ '4' ], maxlen: [ '32' ], require: [], index: [ 'user_email' ] }
    */
    var rules = schema[condition]
    if (!rules) {
      var err = new Error('select error ' + condition + '@' + schemaName + ' is not defined in schema')
      console.error(err)
      cb && cb(err, [])
      return
    }

    /*
    若是ID字段则无需根据索引字段查找出ID， where[condition]的值即为ID
    */
    if (rules.id) {
      var idArr = [ where[condition] ]
      skeys = null
      zkeys = null
    } else {
      //只有index或keywords属性才能让where条件起作用
      var conditionSchema = rules.index || rules.keywords
      if (!conditionSchema) {
        var err = new Error('select error ' + schemaName + ':' + condition + ' is not an index field')
        console.error(err)
        cb && cb(err, [])
        return
      }

      var conditionKey = conditionSchema[0] + ':' + where[condition]

      //schema中只有一个参数为无序集合(set); 两个参数则为有序集合(sorted set)
      if (conditionSchema.length > 1) {

        desc === true
          ? multi.zrevrange(conditionKey, from, to)
          : multi.zrange(conditionKey, from, to)

        zkeys && zkeys.push(conditionKey)
        skeys = null
      } else {
        multi.smembers(conditionKey)
        zkeys && zkeys.push(conditionKey)
        skeys && skeys.push(conditionKey)
      }
    }


    if (count1 == conditions.length) {
      /*
      返回的是一个纯set类型的二维数组，使用sinter函数
      */
      if (skeys && skeys.length > 1) {
        multi.discard()
        skeys.push(function(err, IDs) {
          if (err) {
            cb && cb(err)
            return
          }

          getFromIDs(IDs)
        })

        client.sinter.apply(client, skeys)
      }

      /*
      返回的是一个纯sorted set类型的二维数组，使用; zinterstore同时支持zets和sets
      http://blog.redsmin.com/post/55718899396/how-to-use-zinterstore-with-both-zsets-and-sets
      */
      else if (zkeys && zkeys.length > 1) {
        multi.discard()

        var transaction   = client.multi()
            //生成一个随机的keys作为临时查询结果存储地
          , tempStoreKey = '_tmp_ix_' + (+new Date()).toString(36) + (Math.random() * 100000000 | 0).toString(36)

        zkeys.unshift(tempStoreKey, zkeys.length)

        transaction.zinterstore.apply(transaction, zkeys)

        desc === true
          ? transaction.zrevrange(conditionKey, from, to)
          : transaction.zrange(conditionKey, from, to)

        transaction.del(tempStoreKey)
        transaction.exec(function(err, results) {
          if (err) {
            cb && cb(err)
            return
          }

          //第二条
          getFromIDs(results[1] || [])
        })

        //console.log(transaction.queue)
      }

      /*
      返回的是一个类型多样的含ID的二维数组，求其交集or并集？先从少到多排列，减少比较次数
      不建议使用ID作为多个查询条件
      results: [ ['airjd'], ['kris', 'airjd'] ]
      */
      else {
        multi.exec(function(err, results) {
          if (err) {
            cb && cb(err)
            return
          }

          idArr && results.push(idArr)
          resultHandler(results)
        })
      }
    }
  }

  /*
  只传入schemaName使用keys查找，性能较差
  */
  if (conditions.length < 1) {
    client.keys(schemaName + ':*', function(err, keys) {
      if (err) {
        cb && cb(err)
        return
      }

      if (keys && keys.length) {
        var prefix = schemaName + ':'
        for (var i = 0; i < keys.length; i++) {
          keys[i] = keys[i].replace(prefix, '')
        }
      }

      resultHandler([keys])
    })
  } else {
    conditions.forEach(conditionHandler)
  }
}
1212795
function parseQueryString(query) {
  const result = {};

  _.each(query.replace(/\+/g, ' ').split('&'), (key) => {
    const index = key.indexOf('=');
    let val = '';

    if (index >= 0) {
      val = decodeURIComponent(key.slice(index + 1));
      key = key.slice(0, index);
    }
    if (!key) return;

    key = decodeURIComponent(key);

    // brackets notation for array value
    if (key.slice(-2) === '[]') {
      key = key.slice(0, -2);
      val = [val];
    }

    // if there are multiple values per key, concatenate
    result[key] = _.has(result, key) ? [].concat(result[key], val) : val;
  });

  return result;
}
934908
function collectQueryParams(req, paramNames) {
    var result = {
        query: {},
        fields: {},
        options: {},
        params: {}
    };
    paramNames.forEach(function (paramName) {
        var paramValue = req.anyParam(paramName);
        if (paramValue) {
            paramValue = paramValue.trim();
            if (paramValue && paramValue !== '*') {
                if (paramValue.charAt(paramValue.length - 1) === '*') {
                    // regexp to match prefix
                    paramValue = new RegExp('^' + paramValue.substring(0, paramValue.length - 1));
                }
                result.query[paramName] = paramValue;
            }
            result.params[paramName] = paramValue;
        }
    });
    var fields = req.anyParam('fields');
    if (fields) {
        result.fields = {};
        fields.split(',').forEach(function (field) {
            field = field.trim();
            if (field) {
                var select = 1;
                switch (field.charAt(0)) {
                    case '-':
                        field = field.substring(1);
                        select = 0;
                        break;
                    case '+':
                        field = field.substring(1);
                        break;
                }
                result.fields[field] = select;
            }
        });
    }
    var sort = req.anyParam('sort');
    if (sort) {
        result.options.sort = {};
        sort.split(',').forEach(function (field) {
            field = field.trim();
            if (field) {
                var order = 1;
                switch (field.charAt(0)) {
                    case '-':
                        field = field.substring(1);
                        order = -1;
                        break;
                    case '+':
                        field = field.substring(1);
                        break;
                }
                result.options.sort[field] = order;
            }
        });
        result.params.sort = sort;
    }
    var skip = req.anyParam('skip') || req.anyParam('offset');
    if (skip) {
        result.options.skip = parseInt(skip, 10);
        result.params.skip = skip;
    }
    var limit = req.anyParam('limit');
    if (limit) {
        result.options.limit = parseInt(limit, 10);
        result.params.limit = limit;
    }
    return result;
}
772835
function query (options$$1, next) {

    var urlParams = Object.keys(Url.options.params), query = {}, url = next(options$$1);

    each(options$$1.params, function (value, key) {
        if (urlParams.indexOf(key) === -1) {
            query[key] = value;
        }
    });

    query = Url.params(query);

    if (query) {
        url += (url.indexOf('?') == -1 ? '?' : '&') + query;
    }

    return url;
}
125300
function getValueQuery(tagInfo) {
        var query;
        if (tagInfo.token.string === "=") {
            return "";
        }
        // Remove quotation marks in query.
        query = tagInfo.token.string.substr(1, tagInfo.offset - 1);

        // Get the last option to use as a query to support multiple options.
        return query.split(/\s+/).slice(-1)[0];
    }
201266
function all(options, cb) {
  var q
    , page = Number(options.page) || 1
    , limit = Number(options.limit) || conf.objects_by_page
    , offset = (page - 1) * limit;

  count(function(err, count) {
    if(err) { return cb(err); }

    q = select('LEFT JOIN');
    q += ' LIMIT ' + limit + ' OFFSET ' + offset;

    db.getClient(function(err, client, done) {
      client.query(q, function(err, r) {
        if(err) {
          cb(err);
          done(err);
        } else {
          cb(null, {
            rows: r.rows,
            count: count,
            limit: limit,
            offset: offset,
            page: page
          });
          done();
        }
      });
    });
  });
}
503216
function query (query, params) {
        let rows = [];
        let stmt = sql.prepare(query);
        params = normalizeParams(params);
        stmt.bind(params);
        while(stmt.step()) {
            rows.push(stmt.getAsObject());
        }
        stmt.free();
        return rows;
    }
872623
function querystring(query) {
      var parser = /([^=?&]+)=([^&]*)/g
        , result = {}
        , part;

      //
      // Little nifty parsing hack, leverage the fact that RegExp.exec increments
      // the lastIndex property so we can continue executing this loop until we've
      // parsed all results.
      //
      for (;
        part = parser.exec(query);
        result[decodeURIComponent(part[1])] = decodeURIComponent(part[2])
      );

      return result;
    }
219430
function queryBat (queue, cb) {
  const res = []

  queue.forEach(item => {
    const { selector, single, fields, component } = item
    // selector 的容器节点
    /* eslint-disable */
    const container = (
      component !== null ?
        (Nerv.findDOMNode(component) || document) :
        document
    )
    /* eslint-enable */

    // 特殊处理 ---- 选自己
    let selectSelf = false
    if (container !== document) {
      const $nodeList = container.parentNode.querySelectorAll(selector)
      for (let i = 0, len = $nodeList.length; i < len; ++i) {
        if (container === $nodeList[i]) {
          selectSelf = true
          break
        }
      }
    }

    if (single) {
      const el = selectSelf === true ? container : container.querySelector(selector)
      res.push(filter(fields, el, selector))
    } else {
      const $children = container.querySelectorAll(selector)
      const children = []
      selectSelf === true && children.push(container)
      for (let i = 0, len = $children.length; i < len; ++i) {
        children.push($children[i])
      }
      res.push(children.map(dom => filter(fields, dom)))
    }
  })
  cb(res)
}
1058732
function  doQuery(option, inQuery, cb)  {
	var  expr = option.expr,
		 tables = toTableArrays(expr.table),
		 mainTable = tables[0].alias || tables[0].name;
	//console.log('table names are:\n%s', JSON.stringify(tables, null, 4));

	getQueryTableSchema(tables, function(err, tableSchema) {
		if (err)
			return cb(err);

		//console.log('table schema:\n%s', JSON.stringify(tableSchema, null, 4));
		// now we can move on to analyze the query
		// first, we need to collect filter columns...
		var  noColumnSpecified = !(expr.columns || option.raw),
			 whereCol = [];
		if (expr.filters)
			collectFilterColumns(mainTable, expr.filters, whereCol);

		var  colInfo = scanColumns(tableSchema, mainTable, expr.columns, whereCol),
			 isSqlCol = colInfo.nc.length === 0,
			 isSqlFilter = matchSQLFilter(tableSchema, whereCol);
		//console.log('colInfo is:\n%s', JSON.stringify(colInfo, null, 4));
		//console.log('whereCol is:\n%s', JSON.stringify(whereCol, null, 4));

		if (isSqlCol && isSqlFilter)  {
			// all query column are 'inertia', go ahead to do SQL query
			//console.log('doing standard SQL query');
			//option.debug = true;
			soar.execute( option, inQuery, function(err, result) {
				if (noColumnSpecified && result)  {
					// user does not specify what columns to be returned.
					// return all columns and json_columns are extracted/added
					if (tableSchema[mainTable].columns.indexOf('_c_json') >= 0)
						mergeJsonColumns(option.op === 'query'  ?  [result] : result);
				}
				//console.log('query result is:\n%s', JSON.stringify(result, null, 4));
				cb(err, result);
			});
		}
		else  {
			// there are variable columns, we have to reconstruct the query terms to make them SQL only
			var  schema = tableSchema[mainTable],
				 sqlExpr = cloneObj(expr),
				 sqlCmd = {op: 'list', expr: sqlExpr};
				 
			sqlExpr.columns = colInfo.cc;
			//sqlCmd.range = sqlCmd.range || soar.range(1, _queryLimit);

			if (!isSqlFilter)
				sqlExpr.filters = buildSqlFilter(expr.filters, schema.columns);
			//console.log('The adjusted SQL expression is\n%s', JSON.stringify(sqlCmd, null, 2));

			// now we're ready to perform SQL query
			var  listQuery = sqlExpr.filters  ?  inQuery : null;
			
			var  pgIdx = 1,
				 hasMore = true,
				 listSum = [];
			async.whilst(
				function()  {return  hasMore;},
				function(cb)  {
					sqlCmd.range = soar.range(pgIdx++, _queryPageSize);
					//sqlCmd.debug = true;
					soar.execute( sqlCmd, listQuery, function(err, result, count) {
						if (err)  {
							console.log( err.stack );
							return cb(err);
						}
						
						hasMore = result.length === _queryPageSize;
		
						//console.log('result of adjusted SQL:\n%s', JSON.stringify(result, null, 2));
						if (!isSqlCol)
							// add back specified non-sql properties
							mergeSelectedJsonColumns(colInfo, result);
						else
							// user does not specify what columns to be returned.
							// return all columns and json_columns are extracted/added
							mergeJsonColumns(result);
						//console.log('result before final filtering\n%s', JSON.stringify(result, null, 2));
		
						if (!isSqlFilter)  {
							// ok, let's run a JSON-FP program to get the final result
							var  rdQuery = {},
								 reducedF = reduceFilter(mainTable, expr.filters, schema.columns, colInfo.nc, inQuery, rdQuery);
							//console.log('filter is\n%s', JSON.stringify(reducedF, null, 2));
							//console.log('query value is\n%s', JSON.stringify(rdQuery, null, 2));
							result = jsonQ.filter( result, reducedF, rdQuery );
						}
						//console.log('result after final filtering\n%s', JSON.stringify(result, null, 2));
		
						if (colInfo.more.length)  {
							// remove auto-added columns
							var  rmc = colInfo.more;
							result.forEach(function(data) {
								for (var i in rmc)
									delete  data[rmc[i]];
							});
						}
		
						// not using listSum = listSum.concat(result) for potential performance gains
						for (var i in result)
							listSum.push( result[i] );
							
						//console.log('current size: %d, accumulated size: %d, total size: %d, hasMore: %s', result.length, listSum.length, count, hasMore);
						cb();
					});
				},
				function(err)  {
					cb(err, listSum);
				}
			);
		}
	});
}
896976
function(query,options) {
           for (var key in query) {
               if (query[key].$in) {
                   query[key]=query[key].$in;
               }
           }
           return this.inherited(arguments);
       }
386134
function(query) {
                    tsdb.searchLookup(query, true, null, function (data) {
                        receivedResponses++;
                        results.push(perResultFn(query,data));
                        if (receivedResponses == expectedResponses) {
                            if (errorsReceived.length == 0) {
                                successFn(results);
                            }
                            else {
                                errorFn(errorsReceived, results);
                            }

                        }
                    }, function (error) {
                        receivedResponses++;
                        errorsReceived.push({query:query,msg:error});
                        if (receivedResponses == expectedResponses) {
                            errorFn(errorsReceived, results);
                        }
                    });
                }