Collects data from a single TraceablePDO instance

@param TraceablePDO $pdo
@param TimeDataCollector $timeCollector
@param string|null $connectionName the pdo connection (eg default | read | write)
@return array
341229
protected function collectPDO(TraceablePDO $pdo, TimeDataCollector $timeCollector = null, $connectionName = null)
    {
        if (empty($connectionName) || $connectionName == 'default') {
            $connectionName = 'pdo';
        } else {
            $connectionName = 'pdo ' . $connectionName;
        }
        $stmts = array();
        foreach ($pdo->getExecutedStatements() as $stmt) {
            $stmts[] = array(
                'sql' => $this->renderSqlWithParams ? $stmt->getSqlWithParams($this->sqlQuotationChar) : $stmt->getSql(),
                'row_count' => $stmt->getRowCount(),
                'stmt_id' => $stmt->getPreparedId(),
                'prepared_stmt' => $stmt->getSql(),
                'params' => (object) $stmt->getParameters(),
                'duration' => $stmt->getDuration(),
                'duration_str' => $this->getDataFormatter()->formatDuration($stmt->getDuration()),
                'memory' => $stmt->getMemoryUsage(),
                'memory_str' => $this->getDataFormatter()->formatBytes($stmt->getMemoryUsage()),
                'end_memory' => $stmt->getEndMemory(),
                'end_memory_str' => $this->getDataFormatter()->formatBytes($stmt->getEndMemory()),
                'is_success' => $stmt->isSuccess(),
                'error_code' => $stmt->getErrorCode(),
                'error_message' => $stmt->getErrorMessage()
            );
            if ($timeCollector !== null) {
                $timeCollector->addMeasure($stmt->getSql(), $stmt->getStartTime(), $stmt->getEndTime(), array(), $connectionName);
            }
        }

        return array(
            'nb_statements' => count($stmts),
            'nb_failed_statements' => count($pdo->getFailedExecutedStatements()),
            'accumulated_duration' => $pdo->getAccumulatedStatementsDuration(),
            'accumulated_duration_str' => $this->getDataFormatter()->formatDuration($pdo->getAccumulatedStatementsDuration()),
            'memory_usage' => $pdo->getMemoryUsage(),
            'memory_usage_str' => $this->getDataFormatter()->formatBytes($pdo->getPeakMemoryUsage()),
            'peak_memory_usage' => $pdo->getPeakMemoryUsage(),
            'peak_memory_usage_str' => $this->getDataFormatter()->formatBytes($pdo->getPeakMemoryUsage()),
            'statements' => $stmts
        );
    }
1368424
function collect()
    {
        $totalTime = 0;
        $queries = $this->sqlLogger->queries;
        $statements = [];

        foreach ($queries as $query) {
            $totalTime += $query['executionMS'];

            if ($this->isSqlRenderedWithParams()) {
                $this->addParamsToSql($query['sql'], $query['params']);
                unset($query['params']);
            }

            $statements[] = [
                'sql' => $query['sql'],
                'params' => $query['params'],
                'duration' => $query['executionMS'],
                'duration_str' => $this->formatDuration($query['executionMS']),
                'connection' => $this->connection->getDatabase(),
            ];
        }

        $data = [
            'nb_statements' => count($queries),
            'nb_failed_statements' => 0,
            'accumulated_duration' => $totalTime,
            'accumulated_duration_str' => $this->formatDuration($totalTime),
            'statements' => $statements,
        ];

        return $data;
    }
807328
public function makeUpdate(string $connectionName = ''): UpdateQueryBuilder
    {
        $connection = $this->provideConnection($connectionName);
        $statementBuilder = new UpdateStatementBuilder;
        return new UpdateQueryBuilder($connection, $statementBuilder);
    }
149816
public function getAggregation(
        ConnectionInterface $connection,
        $addedAggregateNames = []
    ) {
        if (!$this->annotations) {
            return [];
        }
        $hasLimit = ($this->offset || $this->limit);
        $hasExistingAnnotations = false;
        foreach ($this->annotations as $alias => $annotation) {
            $hasExistingAnnotations = ($hasExistingAnnotations ||
                !in_array($alias, $addedAggregateNames));
        }

        // we have of $hasExistingAnnotations  we need to make the core query a
        // subquery and aggregate over it.
        if ($hasExistingAnnotations || $hasLimit || $this->distinct ||
            is_array($this->groupBy)) {
            $outQuery = new AggregateQuery($this->model);
            $innerQuery = $this->deepClone();

            $innerQuery->selectRelected = false;

            if (!$hasLimit && !$this->distinctFields) {
                // Queries with distinct_fields need ordering and when a limit
                // is applied we must take the slice from the ordered query.
                // Otherwise no need for ordering, so clear.
                $innerQuery->clearOrdering(true);
            }

            if (!$innerQuery->distinct) {
                // if we are using default columns and we already have
                // aggregate annotations existing
                // then we must make sure the inner
                // query is grouped by the main model's primary key. However,
                // clearing the select clause can alter results if distinct is
                // used.
                if ($innerQuery->useDefaultCols && $hasExistingAnnotations) {
                    $innerQuery->groupBy = [
                        $this->getMeta()->primaryKey
                            ->getColExpression($innerQuery->getInitialAlias()),
                    ];
                }
                $innerQuery->useDefaultCols = false;
            }

            // add annotations to the outerquery todo
            foreach ($innerQuery->annotations as $alias => $annotation) {
                if ($annotation->isSummarize()) {
                    $outQuery->annotations[$alias] = $annotation;
                    unset($innerQuery->annotations[$alias]);
                }
            }

            if ($innerQuery->select == [] && !$innerQuery->useDefaultCols) {
                $innerQuery->select = [
                    $this->getMeta()->primaryKey->getColExpression(
                        $innerQuery->getInitialAlias()
                    ),
                ];
            }

            $outQuery->addSubQuery($innerQuery, $connection);
        } else {
            $outQuery = $this;
            $outQuery->select = [];
            $outQuery->useDefaultCols = false;
        }
        $outQuery->clearOrdering(true);
        $outQuery->clearLimits();
        $outQuery->selectRelected = false;

        $results = $outQuery->getSqlCompiler($connection)
            ->executeSql()->fetch();

        $result = [];
        foreach (array_combine(
                     array_keys($outQuery->annotations),
                     array_values($results)
                 ) as $key => $item) {
            $result[$key] = $item;
        }

        return $result;
    }
185555
public function setDbCollection(string $dbName, string $collectionName): \MongoCollection
    {
        return $this->mongoClient->selectDB($dbName)->selectCollection($collectionName);
    }
125748
public static function setupPDO($connectionString, $user, $password)
    {
        try {
            self::$pdoInstance = new PDO($connectionString, $user, $password);
        } catch (PDOException $e) {
            trigger_error($e->getMessage(), E_USER_ERROR);
        }
    }
1193426
public function getCollections($databaseName = null) {
		$database = $this->getDatabase($databaseName);

		if ($this->_profilerEnabled) {
			$event = $this->getProfiler()->startRead('Collections list');
		}

		$collections = $database->getCollectionNames();

		if ($this->_profilerEnabled) {
			$event->stopSuccess();
		}

		return $collections;
	}
669308
public static function getQueryBuilder(Connection $connection)
    {
        switch ($connection->getDriver()->getName()) {
            case 'pdo_mysql':
                $adapter = new Database\Mysql\Adapter($connection);
                break;

            case 'pdo_sqlite':
                $adapter = new Database\Sqlite\Adapter($connection);
                break;

            case 'pdo_pgsql':
                $adapter = new Database\Pgsql\Adapter($connection);
                break;

            default:
                throw new NotSupportedException('Unknown driver');
        }

        $lookupBuilder = new LookupBuilder();
        $lookupBuilder->addLookupCollection($adapter->getLookupCollection());

        return new QueryBuilder($connection, $adapter, $lookupBuilder);
    }
261667
protected function _getPdoWarning(PDO $pdo)
    {
        $originalErrorMode = $pdo->getAttribute(PDO::ATTR_ERRMODE);
        $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);
        $stm = $pdo->query('SHOW WARNINGS');
        $pdo->setAttribute(PDO::ATTR_ERRMODE, $originalErrorMode);
        return $stm->fetchObject();
    }
442398
private function registerClient(Connection $connection, $timeout)
    {
        $deferred = new Deferred();

        $responseTimer = $this->loop->addTimer(
            $timeout,
            function () use ($deferred, $timeout) {
                $exception = new \RuntimeException(sprintf('No response after %d seconds.', $timeout));
                $deferred->reject($exception);
            }
        );

        $this->startFlow(new OutgoingConnectFlow($connection, $this->identifierGenerator), true)
            ->always(function () use ($responseTimer) {
                $this->loop->cancelTimer($responseTimer);
            })->then(function (Connection $connection) use ($deferred) {
                $this->timer[] = $this->loop->addPeriodicTimer(
                    floor($connection->getKeepAlive() * 0.75),
                    function () {
                        $this->startFlow(new OutgoingPingFlow());
                    }
                );

                $deferred->resolve($connection);
            })->otherwise(function (\Exception $e) use ($deferred) {
                $deferred->reject($e);
            });

        return $deferred->promise();
    }
263470
public function logQuery($connection, $query, array $bindings, $time)
    {
        if (! empty($bindings)) {
            $query = vsprintf(
                // Replace pdo bindings to printf string bindings escaping % char.
                str_replace(['%', '?'], ['%%', "'%s'"], $query),

                // Convert all query attributes to strings.
                $this->normalizeQueryAttributes($bindings)
            );
        }

        // Finish query with semicolon.
        $query = rtrim($query, ';') . ';';

        $this->queries[] = compact('connection', 'query', 'time');
    }
1104553
public function searchTable(
        Connection $connection,
        string $databaseName,
        string $tableName,
        string $searchTerm
    ): \Generator {
        $tableMetadata = (new MetadataFactory())->getTableMetadata($connection, $databaseName, $tableName);

        if (!$tableMetadata->hasStringTypeColumn()) {
            return;
        }

        $rowResultList = (new StringMatchTableSearchStrategy())->getMatches(
            $connection,
            $tableMetadata,
            $searchTerm
        );

        // Yield batch tracking rows returned
        foreach ($rowResultList as $rowResult) {
            yield $rowResult;
        }
    }
271762
public function getResponseCollection(float $timeout = 0): ResponseCollection
    {
        if ($timeout < $this->timeout) {
            $timeout = $this->timeout;
        }

        $now = microtime(true);
        $responseCollection = new JsonRpcResponseCollection();

        do {
            $message = $this->queue->get(Constants::AMQP_AUTOACK);

            if ($message instanceof Envelope) {
                $responseCollection->addResponse($this->responseFromEnvelope($message));
            } else {
                usleep($this->waitMillis * 1000);
            }
            $time = microtime(true);
        } while (
            $responseCollection->count() < $this->countRequests
            && (0 == $timeout || ($timeout > 0 && (($time - $now) < $timeout)))
        );

        $this->requestIds = [];
        $this->timeout = 0;
        $this->countRequests = 0;

        return $responseCollection;
    }
350087
public function logQuery($sql, $bindings = [], $time = 0, $name = null, PDO $pdo = null, $driver = 'mysql')
    {
        $this->counter++;
        $this->totalTime += $time;
        $source = static::findSource();
        $editorLink = static::editorLink($source);
        $this->queries[] = [
            'sql' => $sql,
            'bindings' => $bindings,
            'time' => $time,
            'name' => $name,
            'pdo' => $pdo,
            'driver' => $driver,
            'source' => $source,
            'editorLink' => $editorLink,
            'hightlight' => null,
        ];

        return $this;
    }
1259037
public function getForeignTableNames($tableName = null, $connectionName = null)
    {
        $foreignKeys = $this->getTableForeignKeys($tableName, $connectionName);
        $tableNames  = [];

        foreach ($foreignKeys as $foreignKey) {
            $tableNames[] = $foreignKey->getForeignTableName();
        }

        return array_unique($tableNames);
    }
816822
private function process(MapperInterface $mapper, Connection $connection, Node $cursor, $field = null, $type = null)
    {
        while ($result = $connection->executeFragment($cursor)) {
            if (pg_num_rows($result) === 0) {
                break;
            }

            while ($value = pg_fetch_assoc($result)) {
                $value = json_decode($value['json'], true);

                if ($field !== null) {
                    $value = $value[$field];
                }

                if ($type !== null) {
                    $value = $mapper->fromPg($value, $type);
                }

                yield $value;
            }

            pg_free_result($result);
        }

        pg_free_result($result);
    }
705320
public function listIndexes($collectionName, $options = [])
    {
        $this->document = $this->db->getQueryBuilder()->listIndexes($collectionName, $options);

        try {
            $cursor = $this->execute();
        } catch (Exception $e) {
            // The server may return an error if the collection does not exist.
            $notFoundCodes = [
                26, // namespace not found
                60 // database not found
            ];
            if (in_array($e->getCode(), $notFoundCodes, true)) {
                return [];
            }

            throw $e;
        }

        return $cursor->toArray();
    }