Get data about sql usage of the application

@param object $dbConnection
@returns array
555910
public function gatherQueryData($dbConnection = null)
    {
        if (is_null($dbConnection)) {
            return array();
        }

        if (empty($this->profiledQueries) && property_exists($dbConnection, 'queries')) {
            $this->setProfiledQueries($dbConnection->queries);
        }

        $data = array();
        foreach ($this->profiledQueries as $query) {
            array_push($data, array(
                'sql'     => $query['sql'],
                'explain' => $this->explainQuery($dbConnection, $query['sql'], $query['parameters']),
                'time'    => $query['time']
            ));
        }
        return $data;
    }
1324680
function doSelect(PDO $conn = null) {
		$q = clone $this;

		if (!$q->getTable()) {
			throw new RuntimeException('No table specified.');
		}

		$q->setAction(self::ACTION_SELECT);
		return $q->getQuery($conn)->bindAndExecute();
	}
782902
public function getConnectionParameters()
    {

        // load the datasource node
        $datasourceNode = $this->getDatasourceNode();

        // initialize the database node
        $databaseNode = $datasourceNode->getDatabase();

        // initialize the connection parameters
        $connectionParameters = array(
            AbstractDatabaseStep::CONNECTION_PARAM_DRIVER => $databaseNode->getDriver()->getNodeValue()->__toString(),
            AbstractDatabaseStep::CONNECTION_PARAM_USER => $databaseNode->getUser()->getNodeValue()->__toString(),
            AbstractDatabaseStep::CONNECTION_PARAM_PASSWORD => $databaseNode->getPassword()->getNodeValue()->__toString()
        );

        // initialize the path to the database when we use sqlite for example
        if ($databaseNode->getPath()) {
            if ($path = $databaseNode->getPath()->getNodeValue()->__toString()) {
                $connectionParameters[AbstractDatabaseStep::CONNECTION_PARAM_PATH] = $this->getWebappPath() . DIRECTORY_SEPARATOR . $path;
            }
        }

        // add database name if using another PDO driver than sqlite
        if ($databaseNode->getDatabaseName()) {
            $databaseName = $databaseNode->getDatabaseName()->getNodeValue()->__toString();
            $connectionParameters[AbstractDatabaseStep::CONNECTION_PARAM_DATABASENAME] = $databaseName;
        }

        // add database host if using another PDO driver than sqlite
        if ($databaseNode->getDatabaseHost()) {
            $databaseHost = $databaseNode->getDatabaseHost()->getNodeValue()->__toString();
            $connectionParameters[AbstractDatabaseStep::CONNECTION_PARAM_HOST] = $databaseHost;
        }

        // set the connection parameters
        return $connectionParameters;
    }
1100947
public function getLogs(bool $groupedByConnection = true): array
	{
		$logs = [];

		if($groupedByConnection)
		{
			foreach($this->connections as $connection)
			{
				$logs[$connection->getName()] = $connection->getLog();
			}
		}
		else
		{
			foreach($this->connections as $connection)
			{
				$logs = array_merge($logs, $connection->getLog());
			}
		}

		return $logs;
	}
155352
public function query($sql, $values = null, $connection = null)
  {
    if ($this->isDebug()) {
      $i = $this->getQueriesCount();
      $t = microtime(true);

      $this->queries[$i] = array('query' => $sql, 'values' => $values);
    }

    $pdo = $this->getConnection($connection);

    if ($sql instanceof Query) {
      $values = $values ?: $sql->getBindedValues();
      $sql    = $sql->asStatement();
    }

    $stmt = $pdo->prepare($sql);
    $res = $stmt->execute($values);

    if ($this->isDebug()) {
      $this->queries[$i]['time'] = microtime(true) - $t;
    }

    if (!$res) {
      Exception::ThrowError(Exception::QUERY, $stmt->errorInfo());
    }

    return $stmt;
  }
870188
function getConnection() {
        try {
            if (is_null($this->conn)) {
                $this->conn = new PDO($this->getDbDsn(), $this->getDbUser(), $this->getDbPass());
            }
            return $this->conn;
        } catch (PDOException $e) {
            print "Error!: " . $e->getMessage() . "<br/>";
            die();
        }
    }
514549
public function search($db = null)
    {
        if (!empty($this->emulateExecution)) {
            return [
                'hits' => [],
                'facets' => [],
                'meta' => [],
            ];
        }

        $command = $this->createCommand($db);
        $dataReader = $command->query();
        $rawRows = $dataReader->readAll();

        $facets = [];
        foreach ($this->facets as $facetKey => $facetValue) {
            $dataReader->nextResult();
            $rawFacetResults = $dataReader->readAll();

            if (is_numeric($facetKey)) {
                $facet = [
                    'name' => $facetValue,
                    'value' => $facetValue,
                    'count' => 'count(*)',
                ];
            } else {
                $facet = array_merge(
                    [
                        'name' => $facetKey,
                        'value' => $facetKey,
                        'count' => 'count(*)',
                    ],
                    $facetValue
                );
            }

            foreach ($rawFacetResults as $rawFacetResult) {
                $rawFacetResult['value'] = $rawFacetResult[strtolower($facet['value'])];
                $rawFacetResult['count'] = $rawFacetResult[$facet['count']];
                $facets[$facet['name']][] = $rawFacetResult;
            }
        }

        $meta = [];
        if (!empty($this->showMeta)) {
            $dataReader->nextResult();
            $rawMetaResults = $dataReader->readAll();
            foreach ($rawMetaResults as $rawMetaResult) {
                $meta[$rawMetaResult['Variable_name']] = $rawMetaResult['Value'];
            }
        }

        // rows should be populated after all data read from cursor, avoiding possible 'unbuffered query' error
        $rows = $this->populate($this->fillUpSnippets($rawRows));

        return [
            'hits' => $rows,
            'facets' => $facets,
            'meta' => $meta,
        ];
    }
176641
public function getDatabaseMetadata(
        Connection $connection,
        string $databaseName
    ): DatabaseMetadata {
        // Get a list of table names
        $tableNameStatement = $connection
            ->createQueryBuilder()
            ->select([
                'tables.TABLE_NAME AS name'
            ])
            ->from('information_schema.TABLES', 'tables')
            ->where('TABLE_SCHEMA = :schema')
            ->andWhere('TABLE_TYPE = "BASE TABLE"')
            ->setParameter('schema', $databaseName)
            ->execute();

        // Build table metadata
        $tableMetadataList = [];
        while ($tableName = $tableNameStatement->fetchColumn(0)) {
            $tableMetadataList[] = $this->getTableMetadata($connection, $databaseName, $tableName);
        }

        return new DatabaseMetadata($databaseName, $tableMetadataList);
    }
1085280
public function getHostData($snmpConnection) {
        
        $return = Array();
        
        $hostFullData = $snmpConnection->useLinux_Host()->returnFullData();

        $return['uptime'] = $hostFullData['system']['uptime'];
        $return['users_connected'] = $hostFullData['system']['num_users'];
        $return['running_process'] = $hostFullData['system']['processes'];

        return $return;
    }
1057268
public function getServiceData($snmpConnection) {
        
        $phpFpmData = $snmpConnection->realWalkToArray('NET-SNMP-EXTEND-MIB::nsExtendOutLine."Php-Fpm"', true);
        
        $return = Array();

        $return['num_listen_queue'] = $phpFpmData[1];
        $return['num_accepted_connections'] = $phpFpmData[2];
        $return['num_idle_processes'] = $phpFpmData[3];
        $return['num_max_listen_queue'] = $phpFpmData[4];
        $return['num_slow_requests'] = $phpFpmData[5];
        $return['num_max_active_processes'] = $phpFpmData[6];
        $return['num_active_processes'] = $phpFpmData[7];
        $return['num_start_since'] = $phpFpmData[8];
        $return['des_start_time'] = "$phpFpmData[9]";
        $return['num_listen_queue_len'] = $phpFpmData[10];
        $return['des_pool'] = "$phpFpmData[11]";
        $return['num_max_children_reached'] = $phpFpmData[12];
        $return['num_total_processes'] = $phpFpmData[13];
        $return['des_process_manager'] = "$phpFpmData[14]";

        return $return;
    }
486802
protected function explainQuery($dbConnection, $query, $parameters = array())
    {
        $driver = $dbConnection->getAttribute(\PDO::ATTR_DRIVER_NAME);
        $query = $this->getExplainQuery($query, $driver);
        $statement = $dbConnection->prepare($query);
        if ($statement === false) {
            throw new Exception('Invalid query passed to explainQuery method');
        }
        $statement->execute($parameters);
        $result = $statement->fetch(\PDO::FETCH_ASSOC);
        if ($result === false) {
            throw new Exception('Query could not be explained with given parameters');
        }
        return $result;
    }
242235
public function getDbConnectionCmd()
    {
        $dbParams = $this->getDbConnectionParams();
        
        $dbConnectionCmd = 'mysql -u ' . $dbParams['user']
                         . ' -h ' . $dbParams['host']
                         . ' -P ' . $dbParams['port'];
        
        if (strlen($dbParams['password']) > 0) {
            $dbConnectionCmd .= ' -p"' . $dbParams['password'] . '"';
        }
        
        return $dbConnectionCmd;
    }
193674
public function getRelations ($db, $table)
	{
		
		// If there are no table constraints
		
		if (!isset ($this->relations[$db][$table]))
		{
			
			// Set blank array
			
			$this->relations[$db][$table]	= array ();
			
			// Query database
			
			$query	= $this->db->query ('SHOW CREATE TABLE ' . $db . '.' . $table);
			
			// get SQL
			
			$sql	= $query->fetchColumn (1);
			
			// For each line
			
			foreach (explode ("\n", $sql) as $line)
			{
				
				// Trim
				
				$line	= trim ($line);
				
				// If the line starts with CONSTRAINT
				
				if (strpos ($line, 'CONSTRAINT') === 0)
				{
					
					// Reset pattern
					
					$pattern	= array ();
					
					// Get necessary information out of the constraint
					
					preg_match ('/FOREIGN KEY \(`(.*?)`\) REFERENCES `(.*?)` \(`(.*?)`\)/', 
						$line, $pattern);
					
					// Add to relations array
					
					$this->relations[$db][$table][]	= array (
						'attribute'		=> $pattern[1], 
						'table'			=> $pattern[2], 
						'column'		=> $pattern[3]
					);
					
				}
				
			}
			
		}
		
		// Return relations
		
		return $this->relations[$db][$table];
		
	}
56951
static public function activeConnectionData()
    {
        if (!self::$activeConnectionName)
            throw new Exception\RuntimeException("No database connection is active");
        return array_merge(self::$_connection_data[self::$activeConnectionName], ['name' => self::$activeConnectionName]);
    }
1185757
public function getDoctrineConnection()
    {
        if (is_null($this->doctrineConnection)) {
            $data                     = ['pdo' => $this->getPdo(), 'user' => $this->getConfig('username')];
            $this->doctrineConnection = new DoctrineConnection(
                $data,
                $this->getDoctrineDriver()
            );
        }

        return $this->doctrineConnection;
    }
1023139
protected function getDatabaseConnections()
    {
        $configFile = $this->findDatabaseFile();
        
        if (!$configFile) {
            return false;
        }
        
        switch (substr($configFile, -3)) {
            case 'php':
                $connections = require $configFile;
                break;
            
            case 'yml':
                $connections = Yaml::readFile($configFile);
                break;
        }
        
        return $connections;
    }
663557
function getQuery(PDO $conn = null) {
		if (null === $conn && class_exists('DBManager')) {
			$conn = DBManager::getConnection();
		}

		// the QueryStatement for the Query
		$stmnt = new QueryStatement($conn);

		// the string $statement will use
		$qry_s = '';

		$action = $this->action;

		switch ($action) {
			default:
			case self::ACTION_COUNT:
			case self::ACTION_SELECT:
				$columns_stmnt = $this->getColumnsClause($conn);
				$stmnt->addIdentifiers($columns_stmnt->identifiers);
				$stmnt->addParams($columns_stmnt->params);
				$qry_s .= 'SELECT ' . $columns_stmnt->string . "\nFROM ";
				break;
			case self::ACTION_DELETE:
				$qry_s .= "DELETE\nFROM ";
				break;
			case self::ACTION_UPDATE:
				$qry_s .= "UPDATE\n";
				break;
		}

		$table_stmnt = $this->getTablesClause($conn);
		$stmnt->addIdentifiers($table_stmnt->identifiers);
		$stmnt->addParams($table_stmnt->params);
		$qry_s .= $table_stmnt->string;

		if ($this->joins) {
			foreach ($this->joins as $join) {
				$join_stmnt = $join->getQueryStatement($conn);
				$qry_s .= "\n\t" . $join_stmnt->string;
				$stmnt->addParams($join_stmnt->params);
				$stmnt->addIdentifiers($join_stmnt->identifiers);
			}
		}

		if (self::ACTION_UPDATE === $action) {
			if (empty($this->updateColumnValues)) {
				throw new RuntimeException('Unable to build UPDATE query without update column values');
			}

			$column_updates = array();

			foreach ($this->updateColumnValues as $column_name => &$column_value) {
				$column_updates[] = QueryStatement::IDENTIFIER . '=' . QueryStatement::PARAM;
				$stmnt->addIdentifier($column_name);
				$stmnt->addParam($column_value);
			}
			$qry_s .= "\nSET " . implode(',', $column_updates);
		}

		$where_stmnt = $this->getWhereClause();

		if (null !== $where_stmnt && $where_stmnt->string !== '') {
			$qry_s .= "\nWHERE " . $where_stmnt->string;
			$stmnt->addParams($where_stmnt->params);
			$stmnt->addIdentifiers($where_stmnt->identifiers);
		}

		if ($this->groups) {
			$clause = $this->getGroupByClause();
			$stmnt->addIdentifiers($clause->identifiers);
			$stmnt->addParams($clause->params);
			$qry_s .= $clause->string;
		}

		if (null !== $this->getHaving()) {
			$having_stmnt = $this->getHaving()->getQueryStatement();
			if (null !== $having_stmnt) {
				$qry_s .= "\nHAVING " . $having_stmnt->string;
				$stmnt->addParams($having_stmnt->params);
				$stmnt->addIdentifiers($having_stmnt->identifiers);
			}
		}

		if ($action !== self::ACTION_COUNT && $this->orders) {
			$clause = $this->getOrderByClause();
			$stmnt->addIdentifiers($clause->identifiers);
			$stmnt->addParams($clause->params);
			$qry_s .= $clause->string;
		}

		if (null !== $this->limit) {
			if ($conn) {
				if (class_exists('DBMSSQL') && $conn instanceof DBMSSQL) {
					$qry_s = QueryStatement::embedIdentifiers($qry_s, $stmnt->getIdentifiers(), $conn);
					$stmnt->setIdentifiers(array());
				}
				$conn->applyLimit($qry_s, $this->offset, $this->limit);
			} else {
				$qry_s .= "\nLIMIT " . ($this->offset ? $this->offset . ', ' : '') . $this->limit;
			}
		}

		if (self::ACTION_COUNT === $action && $this->needsComplexCount()) {
			$qry_s = "SELECT count(0)\nFROM ($qry_s) a";
		}

		$stmnt->string = $qry_s;
		return $stmnt;
	}