Exports data returned by a model listing query to a file.

@param EloquentBuilder|QueryBuilder $query
@param string                       $path full path to save the output to
@return string|false     full path string if successful
345417
public function export($query, $path)
    {
        $this->query      = $query;
        $this->modelClass = get_class($query->getModel());

        return $this->generateExport($path);
    }
220632
public function export($page, $format)
    {
        $this->authorize('index', app('scaffold.module')->model());

        $query = app('scaffold.finder')->getQuery();

        return app('scaffold.actions')->exec('export', [$query, $format]);
    }
1077363
final public function forward($path, $query=null)
    {
        $this->stop();
        
        $parts = parse_url($path);
        $path  = $parts['path'];
        $pathQuery = isset($parts['query']) ? $parts['query'] : null;
        
        if (strpos($path, '/') === 0) {
            $controller = Ioc::web()->getController($path);
        } else {
            $controller = $this->getModule()->getController($path);
        }
        
        if (!$controller) {
            $this->request = $this->request->withUri(Uri::createFromString($path));
            
            return $this->notFound();
        }
        
        if ($pathQuery && is_string($pathQuery)) {
            parse_str($pathQuery, $pathQuery);
        }
        if ($query && is_string($query)) {
            parse_str($query, $query);
        }
        $query = array_merge((array)$pathQuery, (array)$query);
        
        if ($query) {
            $this->request = $this->request->withQueryParams($pathQuery);
        }
        
        return $controller->handle($this->request, $this->response);
    }
232047
public function processReportQueryFilter(& $query) {
		$where = [];
		foreach ($this->fields as $k => $v) {
			// filter by value
			if (!empty($v['options']['query_builder']) && isset($this->values[$k])) {
				if (is_array($this->values[$k]) && empty($this->values[$k])) continue;
				$where[$v['options']['query_builder']] = $this->values[$k];
			}
			// subquery - fetch data
			if (!empty($v['options']['subquery'])) {
				$on = [];
				foreach ($v['options']['subquery']['on'] as $v2) {
					$v2[3] = true;
					$on[] = ['AND', $v2, false];
				}
				$query->join('LEFT', function (& $query) use ($v) {
					$model = new $v['options']['subquery']['model']();
					$query = $model->queryBuilder(['skip_acl' => true, 'alias' => $v['options']['subquery']['alias'] . '_inner'])->select();
					$columns = [];
					if (is_array($v['options']['subquery']['groupby'])) {
						$columns = $v['options']['subquery']['groupby'];
					} else {
						$columns[] = $v['options']['subquery']['groupby'];
					}
					$columns[$v['name']] = $query->db_object->sqlHelper('string_agg', ['expression' => $query->db_object->cast($v['name'], 'varchar'), 'delimiter' => ';;']);
					$query->columns($columns);
					$query->groupby(is_array($v['options']['subquery']['groupby']) ? $v['options']['subquery']['groupby'] : [$v['options']['subquery']['groupby']]);
				}, $v['options']['subquery']['alias'], 'ON', $on);
				// special constants to fix
				$this->misc_settings['list']['subquery'][$v['name']] = ['delimiter' => ';;'];
			}
			// subquery - filter
			if (!empty($v['options']['subquery_builder'])) {
				if (is_array($this->values[$k]) && empty($this->values[$k])) continue;
				$on = [];
				foreach ($v['options']['subquery_builder']['on'] as $v2) {
					$v2[3] = true;
					$on[] = $v2;
				}
				$values = $this->values[$k];
				$query->where('AND', function (& $query) use ($values, $on, $v) {
					$model = new $v['options']['subquery_builder']['model']();
					$query = $model->queryBuilder(['alias' => $v['options']['subquery_builder']['alias']])->select();
					$query->columns(1);
					foreach ($on as $v2) {
						$query->where('AND', $v2);
					}
					$query->where('AND', [$v['options']['subquery_builder']['column'], '=', $values, false]);
				}, 'EXISTS');
			}
		}
		if (isset($this->values['full_text_search'])) {
			$where['full_text_search;FTS'] = [
				'fields' => $this->fields['full_text_search']['options']['full_text_search_columns'],
				'str' => $this->values['full_text_search']
			];
		}
		if (!empty($where)) {
			$query->whereMultiple('AND', $where);
		}
	}
186772
public function saveSearchResults(QueryModel $query)
    {
        $adapter = $this->getConnection();
        $table = $this->getMainTable();

        $numResults     = $query->getNumResults();
        $isSpellchecked = (int) $query->getIsSpellchecked();

        $saveData = [
            'store_id'        => $query->getStoreId(),
            'query_text'      => $query->getQueryText(),
            'num_results'     => $numResults,
            'is_spellchecked' => $isSpellchecked,
        ];

        $updateData = ['num_results' => $numResults, 'is_spellchecked' => $isSpellchecked];

        $adapter->insertOnDuplicate($table, $saveData, $updateData);
    }
1058953
public function compileWheres(Query $query)
	{
		$wheres = $query->wheres;

		$sql = [];

		foreach ($wheres as $where)
		{
			if ($where instanceof Expression)
			{
				switch ($where->type)
				{
					case 'raw':

						$sql[] = $this->compileRawWhere($where);

						break;

					case 'disjunct':
						
						$sql[] = $this->compileBasicWhere($where);

						break;

					case 'builder':

						$query = Query::$self->newQuery();

						call_user_func($where->clause, $query);

						$sql[] = '(' . substr($this->compileWheres($query), 6) . ')';

						break;
					
					default:
						# code...
						break;
				}
			}
			elseif (($operator = $where) instanceof Operator)
			{
				$sql[] = $operator->getType();
			}
		}

		return 'WHERE ' . implode(' ', $sql);
	}
684772
public function createSavedSearch($query)
	{
		// Set the API path
		$path = '/saved_searches/create.json';

		// Set POST request data
		$data['query'] = rawurlencode($query);

		// Send the request.
		return $this->sendRequest($path, 'POST', $data);
	}
648231
private function logQuery($path, $method, $data, array $query, $start, $engineMS = 0, $itemCount = 0)
    {
        if (!$this->_logger or !$this->_logger instanceof ElasticaLogger) {
            return;
        }

        $time = microtime(true) - $start;
        $connection = $this->getLastRequest()->getConnection();

        $connection_array = array(
            'host' => $connection->getHost(),
            'port' => $connection->getPort(),
            'transport' => $connection->getTransport(),
            'headers' => $connection->hasConfig('headers') ? $connection->getConfig('headers') : array(),
        );

        $this->_logger->logQuery($path, $method, $data, $time, $connection_array, $query, $engineMS, $itemCount);
    }
289314
protected function exportableQuery(Builder $query): Builder
    {
        // Allow executing custom exportable query.
        if (method_exists($this->module, 'exportableQuery')) {
            return $this->module->exportableQuery($query);
        }

        return $query
            ->when($query->getModel() instanceof Translatable, function ($query) {
                $query->translated();
            })
            // leave select after joining with translations
            // table in order to rewrite selected columns
            ->select($this->exportableColumns());
    }
736046
protected function setKeysForSaveQuery(Builder $query)
    {
        if (count($this->primaryKey)) {
            foreach ($this->primaryKey as $key) {
                if (isset($this->original[$key])) {
                    $value = $this->original[$key];
                } else {
                    $value = $this->getAttribute($key);
                }
                $query->where($key, $value);
            }
        } else {
            $query->where($this->getKeyName(), '=', $this->getKeyForSaveQuery());
        }

        return $query;
    }
816501
public function request($path, $method = Request::GET, $data = [], array $query = [])
    {
        return $this->_client->request('_snapshot/'.$path, $method, $data, $query);
    }
1250998
public function query(QueryBuilderCache $queryBuilderCache)
    {
        // Reconnect the connection in case isn't connected yet.
        $this->reconnect();

        $result = false;
        $queryStatement = new QueryStatement($queryBuilderCache);

        $startTime = microtime(true);

        // Run the query for real
        if ($this->disableQueryExecution === false) {
            $rows = $this->platformQueryHandler($queryStatement);
            $result = new Result($rows);

            if ($this->transactionInProgress) {
                $this->transactionStatus = ($queryStatement->hasErrors() ? false : true);
            }
        }

        $queryStatement->setDuration($startTime);

        $this->queriesCache[] = $queryStatement;

        if ($queryStatement->hasErrors()) {
            if ($this->debugEnabled) {
                throw new RuntimeException($queryStatement->getLatestErrorMessage(),
                    $queryStatement->getLatestErrorCode());
            }

            if ($this->transactionInProgress) {
                $this->transactionStatus = false;
                $this->transactionInProgress = false;
            }

            return false;
        }

        return $result;
    }
608414
private static function smartQuery($path, $fields = null) {
        $root = self::$_env->get('app_root');
        $rest = substr($path, 1);
        if(substr($path, 0, 1) == '>') {
            $sql = $rest;
        } else {
            $parts = explode('/', $rest);
            $file = isset($parts[1]) ? $parts[1] : $parts[0];
            $filePath = '/' . self::$_env->get('file_location') . '/';
            $filePath .= $parts[0] . '/' . $file . '.sql';
            $sql = file_get_contents($root . $filePath);
        }
        if(!empty($fields)) {
            $sql = preg_replace_callback(
                '/\{\{([a-zA-Z_]+)\}\}/', function($hit) use ($fields) {
                if(!isset($fields[$hit[1]])) {
                    self::$_ops->formatError($hit, 'Required field missing: ' . $hit[1]);
                }
                self::$_ops->addExclusion($fields[$hit[1]]);
                return '?';
            }, $sql
            );
        }
        return self::handleResults($sql);

    }
524852
public static function getFullSQL($query)
    {
        $sql = $query->getSql();
        $paramsList = self::getListParamsByDql($query->getDql());
        $paramsArr = self::getParamsArray($query->getParameters());
        $fullSql = '';
        for ($i = 0; $i < strlen($sql); $i++) {
            if ($sql[$i] == '?') {
                $nameParam = array_shift($paramsList);

                if (!isset($paramsArr[$nameParam])) {
                    $fullSql .= ':' . $nameParam;
                } elseif (is_string($paramsArr[$nameParam])) {
                    $fullSql .= '"' . addslashes($paramsArr[$nameParam]) . '"';
                } elseif (is_array($paramsArr[$nameParam])) {
                    $sqlArr = '';
                    foreach ($paramsArr[$nameParam] as $var) {
                        if (!empty($sqlArr))
                            $sqlArr .= ',';

                        if (is_string($var)) {
                            $sqlArr .= '"' . addslashes($var) . '"';
                        } else
                            $sqlArr .= $var;
                    }
                    $fullSql .= $sqlArr;
                } elseif (is_object($paramsArr[$nameParam])) {
                    switch (get_class($paramsArr[$nameParam])) {
                        case 'DateTime':
                            $fullSql .= '\'' . $paramsArr[$nameParam]->format('Y-m-d H:i:s') . '\'';
                            break;
                        default:
                            $fullSql .= $paramsArr[$nameParam]->getId();
                    }

                } else
                    $fullSql .= $paramsArr[$nameParam];

            } else {
                $fullSql .= $sql[$i];
            }
        }
        return $fullSql;
    }
603738
protected function url($path = '', $query = [])
    {
        $path = $this->urlBase() . $path;
        $query = http_build_query(array_merge($this->params, $query));

        $url = $path;
        if (!empty($query)) {
            $url .= '?' . $query;
        }

        return $url;
    }
1077310
function queryData($query, $keyField=null, $resultType = MYSQLI_ASSOC)
  {
    $data = [];
    $res = $this->q($query);
    if ($keyField == null)
      $data = $res->fetch_all($resultType);
    else while ($row = $res->fetch_array($resultType))
    {
      if ($keyField)
        $data[$row[$keyField]] = $row;
    }
    $res->close();
    return $data;
  }
1366143
private function export(SessionInterface $session, $path, $stream)
    {
        $session->exportSystemView(
            $path,
            $stream,
            true,
            false
        );
    }