/* =================================================================================
ADVANCED METHODS
Use these methods to build up more complex queries
=================================================================================
192710
public function post($params = array(), $options = array())
        {
            // If its an array (instead of a query string) then format it correctly
            if (Array::isArray($params)) {
                $params = http_build_query($params, null, '&');
            }

            // Add in the specific options provided
            $this->options($options);

            $this->http_method('post');

            $this->option(CURLOPT_POST, true);
            $this->option(CURLOPT_POSTFIELDS, $params);
        }
1269213
function addQueryParams(req, res, next) {
  _assign(res.locals, req.params, req.query);
  next();
}
908372
function () {
			this.writeDebug('checkQueryStringFilters',arguments);

			// Loop through the filters.
			for(var key in filters) {
				if (filters.hasOwnProperty(key)) {
					var filterVal = this.getQueryString(key);

					// Check for multiple values separated by comma.
					if ( filterVal.indexOf( ',' ) !== -1 ) {
						filterVal = filterVal.split( ',' );
					}

					// Only add the taxonomy id if it doesn't already exist
					if (typeof filterVal !== 'undefined' && filterVal !== '' && filters[key].indexOf(filterVal) === -1) {
						if ( Array.isArray( filterVal ) ) {
							filters[key] = filterVal;
						} else {
							filters[key] = [filterVal];
						}
					}

					// Select the filters indicated in the query string.
					if ( filters[key].length ) {
						this.selectQueryStringFilters( key, filters[key] );
					}
				}
			}

		}
806140
public function getQuery(): Query
    {
    	// TODO: Bindings could be defined only locally in this method because it has to be regenerated on every call

        if (count($this->from) == 0) {
            throw new Exception('Can not build SELECT query, there is no FROM table defined');
        }

        $query = "SELECT\n";

        if (sizeof($this->fields) == 0) {
            $query .= "\t*";
        } else {
            foreach ($this->fields as $fld) {
                $field = $fld['name'];
                $as = $fld['as'];

                $query .= "\t{$field}";
                if ($as !== null) {
                    $query .= " as {$as}";
                }

                $query .= ",\n";
            }

            $query = substr($query, 0, -2);
        }

        $query .= "\nFROM";
        foreach ($this->from as $from) {
            if ($from['table'] instanceof static) {
                /* @var $subSelect \Koldy\Db\Query\Select */
                $subSelect = $from['table'];
                $subSql = $subSelect->__toString();
                $subSql = str_replace("\n", "\n\t", $subSql);
                $query .= " (\n\t{$subSql}\n) {$from['alias']}\n";

                $subSelectBindings = $subSelect->getBindings();
                if (!$subSelectBindings->isEmpty()) {
                    $this->getBindings()->addBindingsFromInstance($subSelectBindings);
                }
            } else {
                $query .= "\n\t{$from['table']}";
                if ($from['alias'] !== null) {
                    $query .= " as {$from['alias']},";
                } else {
                    $query .= ',';
                }
            }
        }
        $query = substr($query, 0, -1);

        foreach ($this->joins as $join) {
            $query .= "\n\t{$join['type']} {$join['table']} ON ";

            if (is_array($join['first'])) {
                foreach ($join['first'] as $joinArg) {
                    if ($joinArg instanceof Expr) {
                        $query .= "{$joinArg} AND ";

                    } else if (is_array($joinArg) && count($joinArg) == 2) {
                        $query .= "{$joinArg[0]} = {$joinArg[1]} AND ";

                    } else if (is_array($joinArg) && count($joinArg) == 3) {
                        $query .= "{$joinArg[0]} {$joinArg[1]} {$joinArg[2]} AND ";

                    } else if (is_array($joinArg) && count($joinArg) == 4) {
                        if (substr($query, -5) == ' AND ') {
                            $query = substr($query, 0, -5);
                        }

                        $query .= " {$joinArg[0]} {$joinArg[1]} {$joinArg[2]} {$joinArg[3]} AND ";

                    } else {
                        throw new Exception('Unknown JOIN argument');

                    }
                }

                $query = substr($query, 0, -5);
            } else {
                if ($join['operator'] === null) {
                    throw new Exception('Operator can\'t be null');
                }

                if ($join['second'] === null) {
                    throw new Exception('Second parameter can\'t be null');
                }

                $query .= "{$join['first']} {$join['operator']} {$join['second']}";
            }
        }

        if ($this->hasWhere()) {
            $query .= "\nWHERE\n\t" . trim($this->getWhereSql());
        }

        if (sizeof($this->groupBy) > 0) {
            $query .= "\nGROUP BY";
            foreach ($this->groupBy as $r) {
                $query .= " {$r['field']},";
            }
            $query = substr($query, 0, -1);
        }

        $sizeofHaving = count($this->having);
        if ($sizeofHaving > 0) {
            $query .= "\nHAVING";
            if ($sizeofHaving == 1) {
                $nl = ' ';
            } else {
                $nl = "\n\t";
            }

            foreach ($this->having as $index => $having) {
                $link = ($index > 0) ? "{$having['link']} " : '';
                if ($having['value'] instanceof Expr) {
                    $query .= "{$nl}{$link}{$having['field']} {$having['operator']} {$having['value']}";
                } else {
	                //$bindName = $this->bind($having['field'], $having['value'], 'h');
	                $bindName = $this->getBindings()->makeAndSet('h' . $having['field'], $having['value']);
	                $query .= "{$nl}{$link}{$having['field']} {$having['operator']} :{$bindName}";
                }
            }
        }

        if (sizeof($this->orderBy) > 0) {
            $query .= "\nORDER BY";
            foreach ($this->orderBy as $r) {
                $query .= "\n\t{$r['field']} {$r['direction']},";
            }
            $query = substr($query, 0, -1);
        }

        if ($this->limit !== null) {
            $query .= "\nLIMIT {$this->limit->howMuch} OFFSET {$this->limit->start}";
        }

        return new Query($query, $this->getBindings(), $this->getAdapterConnection());
    }
697855
private StringBuilder appendPagingSortSQL(final StringBuilder sql, final Post.Sort sort,final Paging paging) {

      if(paging.interval != null) {
         sql.append(" AND post_date");
         sql.append(paging.startIsOpen ? " >" : " >=");
         sql.append("?");

         sql.append(" AND post_date");
         sql.append(paging.endIsOpen ? " <" : " <=");
         sql.append("?");
      }

      switch(sort) {
         case ASC:
            sql.append(" ORDER BY post_date ASC");
            break;
         case DESC:
            sql.append(" ORDER BY post_date DESC");
            break;
         case ASC_MOD:
            sql.append(" ORDER BY post_modified ASC");
            break;
         case DESC_MOD:
            sql.append(" ORDER BY post_modified DESC");
            break;
         case ID_ASC:
            sql.append(" ORDER BY ID ASC");
            break;
         case ID_DESC:
            sql.append(" ORDER BY ID DESC");
            break;
         default:
            sql.append(" ORDER BY post_date DESC");
            break;
      }
      sql.append(" LIMIT ?,?");
      return sql;
   }
277449
public function buildQuery()
    {
        foreach ($this->fields as $_nextRow) {
            $this->columns[$_nextRow['name']] = $this->buildNextField($_nextRow);
        }
    }
102410
function createSOQL(query) {
  var soql = [
    "SELECT ",
    createFieldsClause(query.fields, query.includes),
    " FROM ",
    query.table
  ].join("");
  var cond = createConditionClause(query.conditions);
  if (cond) {
    soql += " WHERE " + cond;
  }
  var orderby = createOrderByClause(query.sort);
  if (orderby) {
    soql += " ORDER BY " + orderby;
  }
  if (query.limit) {
    soql += " LIMIT " + query.limit;
  }
  if (query.offset) {
    soql += " OFFSET " + query.offset;
  }
  return soql;
}
928567
public function assemble()
    {
        $queryString = array();

        $queryString[] = $this->query['type'];

        // Select query
        if ($this->query['type'] == "SELECT"
        or  $this->query['type'] == "SELECT DISTINCT") {
            // Build columns to select
            $queryString[] = $this->buildSelectColumns();

            // From
            $queryString[] = "FROM `{$this->query['table']}`";

            // Joins
            if (array_key_exists('joins', $this->query)) {
                $queryString[] = $this->buildJoins();
            }

            // Where
            $queryString[] = $this->buildWhere();

            // Custom SQL
            if (array_key_exists('sql', $this->query)) {
                $queryString[] = $this->query['sql'];
            }

            // Order by
            if (array_key_exists('order_by', $this->query)) {
                $queryString[] = "ORDER BY " . implode(", ", $this->query['order_by']);
            }
        }
        // Insert
        elseif ($this->query['type'] == "INSERT INTO") {
            // Table
            $queryString[] = "`{$this->query['table']}`";

            // Get the columns and values
            $columns = $values = array();
            foreach ($this->query['data'] as $column => $value) {
                $columns[] = $this->columnName($column);
                $values[] = $this->processValue($value);
            }

            // Add columns and values to query
            $queryString[] = "(" . implode(',', $columns) . ")";
            $queryString[] = "VALUES (" . implode(',', $values) . ")";
        }
        // Update
        elseif ($this->query['type'] == "UPDATE") {
            // Table
            $queryString[] = "`{$this->query['table']}`";

            // Set values
            $values = array();
            foreach ($this->query['data'] as $column => $value) {
                // Process column name
                $column = $this->columnName($column);

                // Add value to bind queue
                $valueBindKey = "new_" . str_replace(array('.', '`'), array('_', ''), $column);
                $this->valuesToBind[$valueBindKey] = $value;

                // Add to values
                $values[] = $column . " = :{$valueBindKey}";
            }

            // Add values to query
            $queryString[] = "SET " . implode(", ", $values);

            $queryString[] = $this->buildWhere();
        }
        // Delete from
        elseif ($this->query['type'] == "DELETE") {
            // Table
            $queryString[] = "FROM `{$this->query['table']}`";

            // Where
            $queryString[] = $this->buildWhere();
        }

        return implode(" ", str_replace("{prefix}", $this->prefix, $queryString));
    }
1302602
public Query customizeQuery(Object anObject, PersistenceBroker aBroker, CollectionDescriptor aCod, QueryByCriteria aQuery)
    {
        return aQuery;
    }
645476
public function buildQuery()
    {
        $model = $this->model;
        $query = $model::query();

        // perform joins
        if (is_array($this->join)) {
            foreach ($this->join as $condition) {
                list($joinModel, $column, $foreignKey) = $condition;
                $query->join($joinModel, $column, $foreignKey);
            }
        }

        // sanitze and set the filter
        $filter = $this->parseFilterInput($this->filter);
        $query->where($filter);

        // performs a search using LIKE queries
        // WARNING use sparingly, these queries are expensive
        if (!empty($this->search) && is_string($this->search) && property_exists($model, 'searchableProperties')) {
            $w = [];
            $search = addslashes($this->search);
            foreach ($model::$searchableProperties as $name) {
                $w[] = "`$name` LIKE '%$search%'";
            }

            if (count($w) > 0) {
                $query->where('('.implode(' OR ', $w).')');
            }
        }

        // eager loading
        foreach ($this->expand as $k) {
            $property = $model::getProperty($k);
            if ($property && isset($property['relation'])) {
                if (isset($property['id_property'])) {
                    $query->with($property['id_property']);
                } else {
                    $query->with($k);
                }
            }
        }

        if (isset($this->sort)) {
            $query->sort($this->sort);
        }

        // calculate limit and offset
        $start = ($this->page - 1) * $this->perPage;
        $query->start($start)->limit($this->perPage);

        return $query;
    }
1034251
function(query) {
	//	console.log(query);
	// Loop over all sources
	// Todo: make this loop smaller and more graspable
	for (var k = 0, klen = query.sources.length; k < klen; k++) {
		var source = query.sources[k];
		delete source.ix;
		// If there is indexation rule
		//console.log('preIndex', source);
		//console.log(source);
		if (k > 0 && source.optimization == 'ix' && source.onleftfn && source.onrightfn) {
			// If there is no table.indices - create it
			if (source.databaseid && alasql.databases[source.databaseid].tables[source.tableid]) {
				if (!alasql.databases[source.databaseid].tables[source.tableid].indices)
					query.database.tables[source.tableid].indices = {};
				// Check if index already exists
				var ixx =
					alasql.databases[source.databaseid].tables[source.tableid].indices[
						hash(source.onrightfns + '`' + source.srcwherefns)
					];
				if (!alasql.databases[source.databaseid].tables[source.tableid].dirty && ixx) {
					source.ix = ixx;
				}
			}

			if (!source.ix) {
				source.ix = {};
				// Walking over source data
				var scope = {};
				var i = 0;
				var ilen = source.data.length;
				var dataw;
				//				while(source.getfn i<ilen) {

				while (
					(dataw = source.data[i]) ||
					(source.getfn && (dataw = source.getfn(i))) ||
					i < ilen
				) {
					if (source.getfn && !source.dontcache) source.data[i] = dataw;
					//					scope[tableid] = dataw;

					//				for(var i=0, ilen=source.data.length; i<ilen; i++) {
					// Prepare scope for indexation
					scope[source.alias || source.tableid] = dataw;

					// Check if it apply to where function
					if (source.srcwherefn(scope, query.params, alasql)) {
						// Create index entry for each address
						var addr = source.onrightfn(scope, query.params, alasql);
						var group = source.ix[addr];
						if (!group) {
							group = source.ix[addr] = [];
						}
						group.push(dataw);
					}
					i++;
				}

				if (
					source.databaseid &&
					alasql.databases[source.databaseid].tables[source.tableid]
				) {
					// Save index to original table
					alasql.databases[source.databaseid].tables[source.tableid].indices[
						hash(source.onrightfns + '`' + source.srcwherefns)
					] =
						source.ix;
				}
			}
			//console.log(38,274,source.ix);

			// Optimization for WHERE column = expression
		} else if (source.wxleftfn) {
			if (!alasql.databases[source.databaseid].engineid) {
				// Check if index exists
				ixx =
					alasql.databases[source.databaseid].tables[source.tableid].indices[
						hash(source.wxleftfns + '`')
					];
			}
			if (!alasql.databases[source.databaseid].tables[source.tableid].dirty && ixx) {
				// Use old index if exists
				source.ix = ixx;
				// Reduce data (apply filter)
				source.data = source.ix[source.wxrightfn(null, query.params, alasql)];
			} else {
				// Create new index
				source.ix = {};
				// Prepare scope
				scope = {};
				// Walking on each source line
				i = 0;
				ilen = source.data.length;
				dataw;
				//				while(source.getfn i<ilen) {

				while (
					(dataw = source.data[i]) ||
					(source.getfn && (dataw = source.getfn(i))) ||
					i < ilen
				) {
					if (source.getfn && !source.dontcache) source.data[i] = dataw;
					//					for(var i=0, ilen=source.data.length; i<ilen; i++) {
					scope[source.alias || source.tableid] = source.data[i];
					// Create index entry
					addr = source.wxleftfn(scope, query.params, alasql);
					group = source.ix[addr];
					if (!group) {
						group = source.ix[addr] = [];
					}
					group.push(source.data[i]);
					i++;
				}
				//					query.database.tables[source.tableid].indices[hash(source.wxleftfns+'`'+source.onwherefns)] = source.ix;
				if (!alasql.databases[source.databaseid].engineid) {
					alasql.databases[source.databaseid].tables[source.tableid].indices[
						hash(source.wxleftfns + '`')
					] =
						source.ix;
				}
			}
			// Apply where filter to reduces rows
			if (source.srcwherefns) {
				if (source.data) {
					scope = {};
					source.data = source.data.filter(function(r) {
						scope[source.alias] = r;
						return source.srcwherefn(scope, query.params, alasql);
					});
				} else {
					source.data = [];
				}
			}
			//			}
			// If there is no any optimization than apply srcwhere filter
		} else if (source.srcwherefns && !source.dontcache) {
			if (source.data) {
				var scope = {};
				// TODO!!!!! Data as Function

				source.data = source.data.filter(function(r) {
					scope[source.alias] = r;
					//					console.log(288,source);
					return source.srcwherefn(scope, query.params, alasql);
				});

				scope = {};
				i = 0;
				ilen = source.data.length;
				//var dataw;
				var res = [];
				//				while(source.getfn i<ilen) {

				while (
					(dataw = source.data[i]) ||
					(source.getfn && (dataw = source.getfn(i))) ||
					i < ilen
				) {
					if (source.getfn && !source.dontcache) source.data[i] = dataw;
					scope[source.alias] = dataw;
					if (source.srcwherefn(scope, query.params, alasql)) res.push(dataw);
					i++;
				}
				source.data = res;
			} else {
				source.data = [];
			}
		}
		// Change this to another place (this is a wrong)
		if (source.databaseid && alasql.databases[source.databaseid].tables[source.tableid]) {
			//query.database.tables[source.tableid].dirty = false;
		} else {
			// this is a subquery?
		}
	}
}
187645
function Mql(query, values){
  var self = this;
  if(dynamicMatch){
    var mql = dynamicMatch.call(window, query);
    this.matches = mql.matches;
    this.media = mql.media;
    // TODO: is there a time it makes sense to remove this listener?
    mql.addListener(update);
  } else {
    this.matches = staticMatch(query, values);
    this.media = query;
  }

  this.addListener = addListener;
  this.removeListener = removeListener;
  this.dispose = dispose;

  function addListener(listener){
    if(mql){
      mql.addListener(listener);
    }
  }

  function removeListener(listener){
    if(mql){
      mql.removeListener(listener);
    }
  }

  // update ourselves!
  function update(evt){
    self.matches = evt.matches;
    self.media = evt.media;
  }

  function dispose(){
    mql.removeListener(update);
  }
}
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;
    }
280742
private function buildQuery()
    {
        $this->validateQuery();

        $statement = "";
        if ($this->select !== null) {
            $statement .= sprintf("%s %s ", self::SELECT, $this->select);
        }
        if ($this->from !== null) {
            $statement .= sprintf("%s %s ", self::FROM, $this->from);
        }
        if ($this->where !== null) {
            $statement .= sprintf("%s %s ", self::WHERE, $this->where);
        }
        if ($this->orderBy !== null) {
            $statement .= sprintf("%s %s ", self::ORDER_BY, $this->orderBy);
        }
        if ($this->limit !== null) {
            $statement .= sprintf("%s %s ", self::LIMIT, $this->limit);
        }
        if ($this->offset !== null) {
            $statement .= sprintf("%s %s ", self::OFFSET, $this->offset);
        }

        return trim($statement);
    }
324306
private function _buildQueryParams() {
		$query = [];

		$this->_where = is_array($this->_where) ? $this->_where : [];
		foreach ($this->_where as $key => $val) {
			$query[$key] = is_numeric($val) ? (int) $val : $val;
		}

		if(count($this->_select)) {
			$query[$this->selectFieldsKey] = implode(',', $this->_select);
		}
		if($this->_limit !== null) {
			$query[$this->limitKey] = $this->_limit;
		}
		if($this->_offset !== null) {
			$query[$this->offsetKey] = $this->_offset;
		}

		return $query;
	}
1240777
public function do_search()
    {
        $query = (string) $this->request->request('query');

        $ipl = new PageList();
        $aksearch = false;
        $akIDs = $this->request->request('akID');
        if (is_array($akIDs)) {
            foreach ($akIDs as $akID => $req) {
                $fak = CollectionAttributeKey::getByID($akID);
                if (is_object($fak)) {
                    $type = $fak->getAttributeType();
                    $cnt = $type->getController();
                    $cnt->setAttributeKey($fak);
                    $cnt->searchForm($ipl);
                    $aksearch = true;
                }
            }
        }

        if ($this->request->request('month') !== null && $this->request->request('year') !== null) {
            $year = @(int) ($this->request->request('year'));
            $month = abs(@(int) ($this->request->request('month')));
            if (strlen(abs($year)) < 4) {
                $year = (($year < 0) ? '-' : '') . str_pad(abs($year), 4, '0', STR_PAD_LEFT);
            }
            if ($month < 12) {
                $month = str_pad($month, 2, '0', STR_PAD_LEFT);
            }
            $daysInMonth = date('t', strtotime("$year-$month-01"));
            $dh = Core::make('helper/date');
            /* @var $dh \Concrete\Core\Localization\Service\Date */
            $start = $dh->toDB("$year-$month-01 00:00:00", 'user');
            $end = $dh->toDB("$year-$month-$daysInMonth 23:59:59", 'user');
            $ipl->filterByPublicDate($start, '>=');
            $ipl->filterByPublicDate($end, '<=');
            $aksearch = true;
        }

        if ($query === '' && $aksearch === false) {
            return false;
        }

        if ($query !== '') {
            $ipl->filterByKeywords($query);
        }

        $search_paths = $this->request->request('search_paths');
        if (is_array($search_paths)) {
            foreach ($search_paths as $path) {
                if ($path === '') {
                    continue;
                }
                $ipl->filterByPath($path);
            }
        } elseif ($this->baseSearchPath != '') {
            $ipl->filterByPath($this->baseSearchPath);
        }

        $cak = CollectionKey::getByHandle('exclude_search_index');
        if (is_object($cak)) {
            $ipl->filterByExcludeSearchIndex(false);
        }

        $pagination = $ipl->getPagination();
        $results = $pagination->getCurrentPageResults();

        $this->set('query', $query);
        $this->set('results', $results);
        $this->set('do_search', true);
        $this->set('searchList', $ipl);
        $this->set('pagination', $pagination);
    }
135096
final protected function build_query(){
        $select = empty($this->_select) ? $this->default_select() : implode(', ', $this->_select);
        $calc = $this->_calc_rows ? ' SQL_CALC_FOUND_ROWS' : '';
        $distinct = $this->_distinct ? sprintf('DISTINCT(%s)', $this->escape_column_name($this->_distinct)) : '';
        $from = empty($this->_from) ? $this->table : $this->_from;
        // Build query
        $sql = <<<SQL
          SELECT{$calc} {$distinct} {$select} FROM {$from}
SQL;
        // Add join
        $join = [];
        if( !empty($this->_join) ){
            $join = $this->_join;
        }else{
            $default_join = $this->default_join();
            if( !empty($default_join) ){
                $join = $default_join;
            }
        }
        foreach($join as list($table, $on, $method)){
            $method = 'INNER' === strtoupper($method) ? 'INNER' : 'LEFT';
            $sql .= <<<SQL
            {$method} JOIN {$table}
            ON {$on}
SQL;
        }
        // Add where
        if( !empty($this->_wheres) ){
            $where_clause = $this->build_where($this->_wheres);
            $sql .= <<<SQL
            WHERE {$where_clause}
SQL;
        }
        // Add group by
        if( !empty($this->_group_by) ){
            $group_by = implode(', ', $this->_group_by);
            $sql .= <<<SQL
            GROUP BY {$group_by}
SQL;
        }
        // Add order by
        if( !empty($this->_order_by) ){
            $order_by = implode(', ', $this->_order_by);
            $sql .= <<<SQL
            ORDER BY {$order_by}
SQL;
        }
        // Add limit
        if( !empty($this->_limit) ){
            list($per_page, $offset) = $this->_limit;
            $limit = <<<SQL
            LIMIT %d, %d
SQL;
            $sql .= sprintf($limit, $offset, $per_page);
        }
        return $sql;
    }