获取源数据 - 模板方法

@param PhalApi_ModelQuery $query 查询对象
@return mixed 返回源数据，但在失败的情况下别返回NULL，否则依然会穿透到此
965305
public function getData(Query $query = NULL) {
		$rs = NULL;

		if ($query === NULL) {
			$query = new Query();
		}

		if ($query->readCache) {
			$rs = $this->cache->get($this->getkey($query));
			if ($rs !== NULL) {
				return $rs;
			}
		}

		// 这里，将获取耗性能的数据
		$rs = $this->doGetData($query);

		if ($query->writeCache) {
			$this->cache->set($this->getKey($query), $rs, $this->getExpire($query));
		}

		return $rs;
	}
178205
public function execQuery(Query $query)
    {
        $this->connection->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
        $this->connection->setAttribute(\PDO::ATTR_EMULATE_PREPARES, $query->isSingle());
        $resultDataType = $query->getResultDataType();

        foreach ($query as $sql) {
            $sqlResult = $sql->getResult();
            if ($resultDataType instanceof DataInterface) {
                $sqlResult->setDataType($resultDataType);
            }

            try {
                if ($this->error->hasError()) {
                    throw new \PDOException($this->error->getMessage());
                    break;
                }
                $sqlQuery = $sql->toString();
                $totalRows = 0;
                if ($sql->getCommand() == 'SELECT' && !$query->isSingle()) {
                    $template = '{SQL}';
                    $templateCounter = 'SELECT COUNT(*) totalRows FROM (%s) fakeTable';
                    $templateParams = array(
                        'SQL' => $sqlQuery,
                        'LIMIT' => $query->getLimit(),
                        'OFFSET' => $query->getOffset(),
                    );
                    if ($query->getLimit()) {
                        switch ($this->config->getType()) {
                            case 'firebird':
                                $template = 'SELECT FIRST {LIMIT} SKIP {OFFSET} * FROM ({SQL}) fakeTable';
                            break;
                            case 'oci':
                                $templateCounter = 'SELECT COUNT(*) "totalRows" FROM (%s) "fakeTable"';
                                $template = 'SELECT a.* FROM (SELECT b.*, rownum "[]" FROM '.
                                            '({SQL}) b WHERE rownum <= {LIMIT}) a WHERE "[]" > {OFFSET}';
                            break;
                            default:
                                $template = 'SELECT * FROM ({SQL}) fakeTable LIMIT {LIMIT} OFFSET {OFFSET}';
                            break;
                        }
                    }

                    $resultCounter = $this->connection->prepare(sprintf($templateCounter, $sqlQuery));
                    $resultCounter->execute();
                    $totalRows = $resultCounter->fetch();

                    $sqlResult->setTotalRows((int) @$totalRows['totalRows']);
                    foreach ($templateParams as $key => $val) {
                        $template = str_replace('{'.$key.'}', $val, $template);
                    }
                    $sqlQuery = $template;
                }

                $result = $this->connection->prepare($sqlQuery);
                $stmt = $result->execute();
                $sql->execute();

                if ($sql->isRead()) {
                    $columns = $this->_define_column_types($result);

                    $sqlResult->setColumnTypes($columns);
                    $sqlResult->setAffected(0);
                    $sqlResult->setStartRow($query->getOffset());
                    if (!$sqlResult->getTotalRows()) {
                        $sqlResult->setTotalRows($result->rowCount());
                    }

                    $rows = $result->fetchAll(\PDO::FETCH_ASSOC);

                    foreach ($rows as $row) {
                        $data = $this->_merge_values($sql->getResult()->getDataType(), $row, $columns);
                        $sqlResult->add($data);
                    }

                    $sqlResult->setTotalShows($sqlResult->length());
                    $sqlResult->setEnd(microtime(true));
                } elseif ($sql->isWrite() || $sql->isDDL()) {
                    $insertId = $this->connection->lastInsertId();
                    $affected = $result->rowCount();
                    $endTime = microtime(true);
                    $sqlResult->setEnd($endTime);

                    $columns = array(
                        'affected' => 'integer',
                        'seconds' => 'double',
                    );

                    $row = array(
                        'affected' => $affected,
                        'seconds' => $sqlResult->getSeconds(),
                    );

                    $sqlResult->setColumnTypes($columns);
                    $sqlResult->setAffected($affected);

                    $data = new Data();
                    $this->_merge_values($data, $row, $columns);
                    $sqlResult->add($data);
                    $sqlResult->setInsertId($insertId);
                }
            } catch (\PDOException $e) {
                $sql->execute(false);
                $this->error->setMessage($e->getMessage().". \n".$sql->toString());
                $sqlResult->setEnd(microtime(true));
            } catch (\Exception $e) {
                $sql->execute(false);
                $this->error->setMessage($e->getMessage().". \n".$sql->toString());
                $sqlResult->setEnd(microtime(true));
            }
        }
    }
381487
protected function executeQuery($query)
    {
        $query   = null !== $this->getLocale() ? sprintf('%s&language=%s', $query, $this->getLocale()) : $query;
        $content = $this->getAdapter()->get($query)->getBody();

        if (!$data = json_decode($content, true)) {
            throw new NoResult(sprintf('Could not execute query: %s', $query));
        }

        if (!isset($data['Response']) && 'InvalidCredentials' === $data['subtype']) {
            throw new InvalidCredentials(sprintf('Invalid credentials: %s', $data['details']));
        } elseif (!isset($data['Response'])) {
            throw new NoResult(
                sprintf('Error type `%s` returned from api `%s`', $data['subtype'], $data['Details'])
            );
        }

        if (empty($data['Response']['View'])) {
            throw new NoResult(sprintf('Could not find results for given query: %s', $query));
        }

        $locations = $data['Response']['View'][0]['Result'];

        $results = array();
        foreach ($locations as $location) {
            $location       = $location['Location'];
            $coordinates    = isset($location['NavigationPosition'][0]) ? $location['NavigationPosition'][0] : $location['DisplayPosition'];
            $bounds         = $location['MapView'];
            $address        = $location['Address'];
            $additionalData = $location['Address']['AdditionalData'];

            $results[] = array_merge($this->getDefaults(), array(
                'latitude'     => $coordinates['Latitude']  ?: null,
                'longitude'    => $coordinates['Longitude'] ?: null,
                'bounds'       => array(
                    'south' => $bounds['BottomRight']['Latitude']  ?: null,
                    'west'  => $bounds['TopLeft']['Longitude']     ?: null,
                    'north' => $bounds['TopLeft']['Latitude']      ?: null,
                    'east'  => $bounds['BottomRight']['Longitude'] ?: null,
                ),
                'streetNumber' => isset($address['HouseNumber']) ? $address['HouseNumber'] : null,
                'streetName'   => isset($address['Street'])      ? $address['Street']      : null,
                'city'         => isset($address['City'])        ? $address['City']        : null,
                'cityDistrict' => isset($address['District'])    ? $address['District']    : null,
                'zipcode'      => isset($address['PostalCode'])  ? $address['PostalCode']  : null,
                'county'       => isset($address['County'])      ? $address['County']      : null,
                'regionCode'   => isset($address['State'])       ? $address['State']       : null,
                'countryCode'  => isset($address['Country'])     ? $address['Country']     : null,
                'region'       => $this->findByKey('StateName', $additionalData),
                'country'      => $this->findByKey('CountryName', $additionalData),
                'countyCode'   => null,
            ));
        }

        return $results;
    }
604818
public function fromQuery(Query $query, ApiResource $resource)
    {
        /** @var \Phalcon\Mvc\Model\Manager $modelsManager */
        $modelsManager = $this->di->getShared('modelsManager');

        /** @var \Phalcon\Mvc\Model\Query\Builder $builder */
        $builder = $modelsManager->createBuilder()->from($resource->getModel());

        $this->applyQuery($builder, $query, $resource);

        return $builder;
    }
694091
protected function exec($query)
    {
        try {
            Connect::getConn()->exec($query);
        } catch (Exception $e) {
            static::$response["status"] = "error";
            static::$response["response"] = $e->getMessage();
            static::$response["code"] = $e->getCode();

            return static::terminate(static::$response);
        }
        return null;
    }
941500
public function scopeExtrasWithValues($query, $model)
    {
        $modelSlug = $model ? getModelSlug($model) : false;
        return $query->with([
            'extras' => function($query) use($model,$modelSlug)
            {
                if ( ! $model ) return $query;

                return $query->with([
                    "{$modelSlug}s" => function($query) use($model,$modelSlug)
                    {
                        return $query->wherePivot("{$modelSlug}_id",$model->id);
                    }
                ]);
            }
        ]);
    }
1034176
public function findHandler(Query $query)
    {
        $query_name = get_class($query);

        return isset($this->handlers[$query_name]) ? $this->handlers[$query_name] : null;
    }
580378
public function query($query) {
    $dataConnection = $this->app->getDataConnection($this->connection);
    $foundObjects = $dataConnection->query($this->table, $query);
    $foundModels = array();
    foreach ($foundObjects as $foundObject) {
      /**
       * @var $model \MABI\Model
       */
      $model = call_user_func($this->modelClass . '::init', $this->app);
      $model->load($foundObject);
      $foundModels[] = $model;
    }
    return $foundModels;
  }
557976
public function one($query)
    {
        $authSession = $this->repositoryDispatcher->getCookieAuthSession();

        $url = null;
        $options = [
            RequestOptions::HEADERS => [
                'Cookie' => $authSession->getName() . '=' . $authSession->getValue(),
            ],
        ];

        // Prepares request options
        if (is_scalar($query)) {
            $url = $this->endpoint . '/rest/api/2/issue/' . $query;
        } elseif (is_array($query)
            && (array_key_exists('id', $query) || array_key_exists('key', $query))
        ) {
            // Prepares key by query
            if (isset($query['id'])) {
                $url = $this->endpoint . '/rest/api/2/issue/' . $query['id'];
                unset($query['id']);
            } elseif (isset($query['key'])) {
                $url = $this->endpoint . '/rest/api/2/issue/' . $query['key'];
                unset($query['key']);
            }

            // Prepares query params
            foreach ($query as $param => $value) {
                if ('fields' === $param) {
                    if (is_array($value)) {
                        $query[$param] = implode(',', $value);
                    }
                } elseif ('expand' === $param) {
                    if (is_array($value)) {
                        $query[$param] = implode(',', $value);
                    }
                } else {
                    unset($query[$param]);
                }
            }

            $options[RequestOptions::QUERY] = $query;
        } else {
            throw new \Exception('Bad params');
        }

        $response = $this->client->request('GET', $url, $options);

        $body = $response->getBody();
        $body->seek(0);
        $contents = $body->getContents();

        $issue = $this->createInstance(json_decode($contents, true));

        return $issue;
    }
740558
public function process(QueryInterface $query)
    {
        if (!$query instanceof DropQuery || $query->getObject() !== DropQuery::EXPRESSION_TABLE) {
            return null;
        }

        $command = new ApplySchema($query->getSql());
        $this->client->executeCommand($command);

        return new EmptyResult();
    }
1312270
public function query($query, $params = array())
  {
    $curl = new Curl();
    $params['key'] = $this->server_key;
    $result = json_decode($curl->call(self::GOOGLEPLUS_API_URL . trim($query, '/') . '?' . http_build_query($params), array(), 'GET', true), true);
    if(!isset($result['error'])) {
      return $result;
    }
    return $this->debug_mode ? $result['error']['message'] : null;
  }
1230516
public function findID(Query $query) {
        $pk = $this->getPrimaryKey();

        // Gather ID from where clause
        foreach ($query->getWhere()->getParams() as $param) {
            if ($param instanceof Expr && $param->getField() === $pk && in_array($param->getOperator(), ['=', 'in'])) {
                return $param->getValue();
            }
        }

        // Query for the ID then
        $select = clone $query;
        $results = array_values($select->setType(Query::SELECT)->fields($pk)->lists($pk, $pk, [
            'before' => false,
            'after' => false
        ]));

        if (count($results) > 1) {
            return $results;

        } else if (count($results) === 1) {
            return $results[0];
        }

        return null;
    }
1319213
public function run(&$query, $model, $request)
    {
        $this->query = $query;
        $this->getAttributes($model);
        $this->parseRequest($request);

        return $this->query();
    }
913892
protected function processSingleResult($query)
    {
        if (!empty($this->fetchRefs)) {
            $res = $query->fetch();
            $model = ($res ? $this->populateModelFromJoin($res) : $res);
        } else {
            $model = $query->fetchClass($this->modelClass);
        }
        if ($model && isset($this->manager)) {
            $this->manager->manageModel($model);
        }
        $this->fetchReferences(false);
        return $model;
    }
699765
public function executeRawQuery($query)
    {
        $resultSet = null;
        if($this->odbAdapter) {
            if(!empty($query)) {
                $resultSet = $this->getDbAdapter()->query($query, DbAdapter::QUERY_MODE_EXECUTE);

            }
        }


        return $resultSet;
    }
486031
public function setQuery($query = null)
    {

        try {

            // need to return << true
            $this->validator->verify($query, ['isNotNull', 'isAcceptLength']);

            if (false === $this->exact) {
                $this->query = ['query' => '%' . $query . '%'];
            }
            else {
                $this->query = ['query' => $query];
            }

        }
        catch(ExceptionFactory $e) {
            echo $e->getMessage();
        }

        return $this;
    }
719215
protected function getModelInstanceQuery(Model $model)
    {
        $query = $model->query();

        $this->applyOrderingToModelInstanceQuery($query);
        $this->applyStartAndStopLimitsToQuery($query);

        return $query;
    }