Return some statistics about finished jobs still in the Database.
TO-DO: rewrite as virtual field

@return \Cake\ORM\Query
761854
public function getStats() {
		$driverName = $this->_getDriverName();
		$options = [
			'fields' => function (Query $query) use ($driverName) {
				$alltime = $query->func()->avg('UNIX_TIMESTAMP(completed) - UNIX_TIMESTAMP(created)');
				$runtime = $query->func()->avg('UNIX_TIMESTAMP(completed) - UNIX_TIMESTAMP(fetched)');
				$fetchdelay = $query->func()->avg('UNIX_TIMESTAMP(fetched) - IF(notbefore is NULL, UNIX_TIMESTAMP(created), UNIX_TIMESTAMP(notbefore))');
				switch ($driverName) {
					case static::DRIVER_SQLSERVER:
						$alltime = $query->func()->avg("DATEDIFF(s, '1970-01-01 00:00:00', completed) - DATEDIFF(s, '1970-01-01 00:00:00', created)");
						$runtime = $query->func()->avg("DATEDIFF(s, '1970-01-01 00:00:00', completed) - DATEDIFF(s, '1970-01-01 00:00:00', fetched)");
						$fetchdelay = $query->func()->avg("DATEDIFF(s, '1970-01-01 00:00:00', fetched) - (CASE WHEN notbefore IS NULL THEN DATEDIFF(s, '1970-01-01 00:00:00', created) ELSE DATEDIFF(s, '1970-01-01 00:00:00', notbefore) END)");
						break;
				}
					/**
						 * @var \Cake\ORM\Query
						 */
				return [
					'job_type',
					'num' => $query->func()->count('*'),
					'alltime' => $alltime,
					'runtime' => $runtime,
					'fetchdelay' => $fetchdelay,
				];
			},
			'conditions' => [
				'completed IS NOT' => null,
			],
			'group' => [
				'job_type',
			],
		];
		return $this->find('all', $options);
	}
766210
public function complete()
    {
        $this->last_run_date = date('Y-m-d H:i:s', time());
        if (0 != $this->next_task_id) {
            $this->status = DeferredQueue::STATUS_SUCCESS_AND_NEXT;
        } else {
            $this->status = DeferredQueue::STATUS_COMPLETE;
        }

        if ($this->planNextRun() === true) {
            return $this->save();
        } else {
            if ($this->delete_after_run) {
                return $this->delete() !== false;
            } else {
                return $this->save();
            }
        }
    }
601374
public function measuredJobs()
    {
        $classes = (array) $this->connection()->smembers('measured_jobs');

        return collect($classes)->map(function ($class) {
            return preg_match('/job:(.*)$/', $class, $matches) ? $matches[1] : $class;
        })->all();
    }
527952
public function stats() {
		$this->out('Jobs currently in the queue:');

		$types = $this->QueuedJobs->getTypes()->toArray();
		foreach ($types as $type) {
			$this->out('      ' . str_pad($type, 20, ' ', STR_PAD_RIGHT) . ': ' . $this->QueuedJobs->getLength($type));
		}
		$this->hr();
		$this->out('Total unfinished jobs: ' . $this->QueuedJobs->getLength());
		$this->out('Running workers (processes): ' . $this->QueueProcesses->findActive()->count());
		$this->out('Server name: ' . $this->QueueProcesses->buildServerString());
		$this->hr();
		$this->out('Finished job statistics:');
		$data = $this->QueuedJobs->getStats();
		foreach ($data as $item) {
			$this->out(' ' . $item['job_type'] . ': ');
			$this->out('   Finished Jobs in Database: ' . $item['num']);
			$this->out('   Average Job existence    : ' . str_pad(Number::precision($item['alltime']), 8, ' ', STR_PAD_LEFT) . 's');
			$this->out('   Average Execution delay  : ' . str_pad(Number::precision($item['fetchdelay']), 8, ' ', STR_PAD_LEFT) . 's');
			$this->out('   Average Execution time   : ' . str_pad(Number::precision($item['runtime']), 8, ' ', STR_PAD_LEFT) . 's');
		}
	}
545328
protected function getCurrentSQL() {
        $cloneQuery = clone $this->query;
        $cloneQuery = $this->loadElements($cloneQuery);
        return $cloneQuery->compile();
    }
193431
public function getNbResults()
    {
        if (isset($this->nbResults)) {
            return $this->nbResults;
        }

        $countQuery = clone $this->query;
        $countQuery->limit = 0;

        return $this->nbResults = $this->findService->findNodes($countQuery)->totalCount;
    }
792912
public function findCount()
    {
        $this->compile();
        $queryArr   = $this->queryArr;
        $queryArr['field'] = 'count(*)';
        unset($queryArr['limit']);
        return $this->connection->fetchColumn(implode(" ", $queryArr), $this->arguments);
    }
100548
public function runQuery()
    {
        $filters = $this->filters->get();
        $this->documents  = [];
        if (empty($filters))
            $filters = 'findAll';
        $this->documents = $this->databaseHandler->findAll()->getDocuments();
        if ($filters !== 'findAll')
            $this->filter($filters);
        $this->sort();
        $this->offsetLimit();
        if (is_array($this->fields) && !empty($this->fields))
        {
            foreach($this->documents as $index => $document)
            {
                $fields = new \stdClass();
                foreach($this->fields as $fieldTarget)
                    $fields->{$fieldTarget} = $document->{$fieldTarget};
                $this->documents[$index] = $fields;
            }
        }
        $this->databaseHandler->setDocuments($this->documents);
        return $this->databaseHandler;
    }
833930
public function getNbResults()
    {
        if (isset($this->nbResults)) {
            return $this->nbResults;
        }

        $countQuery = clone $this->query;
        $countQuery->limit = 0;

        return $this->nbResults = $this->searchService->findLocations($countQuery)->totalCount;
    }
799793
function getNbResults()
    {
        $this->sphinx->SetLimits(1, 1, $this->options['max_results']);
        $results = $this->sphinx->searchEx($this->query, $this->options['entity']);

        return $results['total_found'];
    }
438439
public function cleanup()
    {
        $this->saveState();

        if (null === $this->current_job) {
            $this->logger->debug('received cleanup call on worker ['.$this->id.'], no job is currently processing, exit now', [
                'category' => get_class($this),
                'pm' => $this->process,
            ]);

            $this->exit();

            return null;
        }

        $this->logger->debug('received cleanup call on worker ['.$this->id.'], reschedule current processing job ['.$this->current_job['_id'].']', [
            'category' => get_class($this),
            'pm' => $this->process,
        ]);

        $this->updateJob($this->current_job, JobInterface::STATUS_CANCELED);

        $this->db->{$this->scheduler->getEventQueue()}->insertOne([
            'job' => $this->current_job['_id'],
            'worker' => $this->id,
            'status' => JobInterface::STATUS_CANCELED,
            'timestamp' => new UTCDateTime(),
        ]);

        $options = $this->current_job['options'];
        $options['at'] = 0;

        $result = $this->scheduler->addJob($this->current_job['class'], $this->current_job['data'], $options)->getId();
        $this->exit();

        return $result;
    }
1300582
protected function finishQuery() {
        $this->query .= $this->closeOperation();

        if ($this->count) {
            $this->query = $this->getDriverEscaper()->dbCommand('SELECT') . ' ' .
                    'COUNT(*)' . ' ' .
                    $this->getDriverEscaper()->dbCommand('AS') . ' cpt ' .
                    $this->getDriverEscaper()->dbCommand('FROM') . ' ' .
                    '(' . $this->query . ') ' .
                    $this->getDriverEscaper()->dbCommand('AS') . ' rootq ';
        } else {
            $this->addSort($this->criteriaList->getSort());
            $this->query .= $this->operationSeparator . $this->addLimit($this->criteriaList->getLimit(), $this->criteriaList->getOffset());
        }

        $this->predicateLoop = 0;
        return $this;
    }
1158006
public function getLast()
    {
        $result = $this->table()
            ->where('batch', $this->getLastBatchNumber())
            ->orderBy('mapping', 'desc')
            ->get();

        if (is_array($result)) {
            return $result;
        }

        return $result->toArray();
    }
946842
public function getLastQueryStrings() {
    $result = [];
    foreach ($this->queries as $query) {
      $result[] = $query->getLastQueryString();
    }
    return $result;
  }
10868
public function index()
    {
        return [
            'jobsPerMinute' => app(MetricsRepository::class)->jobsProcessedPerMinute(),
            'processes' => $this->totalProcessCount(),
            'queueWithMaxRuntime' => app(MetricsRepository::class)->queueWithMaximumRuntime(),
            'queueWithMaxThroughput' => app(MetricsRepository::class)->queueWithMaximumThroughput(),
            'recentlyFailed' => app(JobRepository::class)->countRecentlyFailed(),
            'recentJobs' => app(JobRepository::class)->countRecent(),
            'status' => $this->currentStatus(),
            'wait' => collect(app(WaitTimeCalculator::class)->calculate())->take(1),
            'periods' => [
                'recentJobs' => config('horizon.trim.recent'),
                'recentlyFailed' => config('horizon.trim.failed'),
            ],
        ];
    }
802417
public function getStats()
    {
        $result = [
            self::STATS_QUEUES_LIST   => [],
            self::STATS_JOBS_TOTAL    => 0,
            self::STATS_JOBS_READY    => 0,
            self::STATS_JOBS_RESERVED => 0,
            self::STATS_JOBS_DELAYED  => 0,
            self::STATS_JOBS_BURIED   => 0,
        ];

        $queueList = $this->getQueueNames();
        if (count($queueList) == 0) {
            return $result;
        }

        $result[self::STATS_QUEUES_LIST] = $queueList;

        foreach ($queueList as $queueName) {
            $itemStats = $this->getQueueInfo($queueName);
            $result[self::STATS_JOBS_READY] += $itemStats[self::STATS_JOBS_READY];
            $result[self::STATS_JOBS_RESERVED] += $itemStats[self::STATS_JOBS_RESERVED];
            $result[self::STATS_JOBS_DELAYED] += $itemStats[self::STATS_JOBS_DELAYED];
            $result[self::STATS_JOBS_BURIED] += $itemStats[self::STATS_JOBS_BURIED];
            $result[self::STATS_JOBS_TOTAL] += $itemStats[self::STATS_JOBS_TOTAL];
            $result[self::STATS_QUEUES][$queueName] = $itemStats;
        }

        return $result;
    }
695417
public function getCountAll()
    {
        if ($this->sync && $this->countAll !== null) return $this->countAll;
        
        $query = clone $this->query;
        $query->resetQueryPart('orderBy')
              ->setMaxResults(null)
              ->setFirstResult(null)
              ->select('COUNT(1)');
			  
        $this->fixWhere($query);
                            
        $stmt = $query->execute();  
        if ($stmt->rowCount() > 1) {
            $this->countAll = $stmt->rowCount();
        } 
        else {
            $this->countAll = $stmt->fetchColumn();
        }
        
        return $this->countAll;  
    }