Check if database is available and initialized correctly

@return  bool
183634
final public static function database(Configuration $configuration) {

        try {

            $dbh = Database::init($configuration);

            $dbh->connect();

            $manager = $dbh->getSchemaManager();

            $manager->getTable($configuration->get('database-jobs-table'));
            $manager->getTable($configuration->get('database-worklogs-table'));
            $manager->getTable($configuration->get('database-queue-table'));

        } catch (Exception $e) {

            return false;

        } finally {

            $dhb->close();

        }

        return true;

    }
1045849
public function is_connected() {
		$retval = false;
		if(isset($this->dbh) && count($this->dbh->getAvailableDrivers())) {
			$retval = true;
		}
		return($retval);
	}
291270
protected function verifyConnection()
    {
        if (count(config('database.connections', [])) > 1) {
            $connections = array_keys(config('database.connections'));
            $default = array_search(config('database.default'), $connections);

            return $this->choice('Which connection do we use?', $connections, $default);
        }

        return config('database.default');
    }
631787
public function check()
    {
        $this->loadDatabase();

        $current = $this->getCurrentUptime();

        $this->persist($current);

        $rebooted =
            ($cs = $this->uptimeInSeconds($current)) <
            ($ss = $this->uptimeInSeconds($this->database));

        return $this->makeResult(
            ! $rebooted,
            $this->makeMessage($current, $this->database)
        );
    }
1301925
protected static function _tableExists()
    {
        $db = ConnectionManager::get('default');
        $tables = $db->schemaCollection()->listTables();

        if (in_array('settings_configurations', $tables)) {
            return true;
        }
        return false;
    }
672852
public function createDatabase()
    {
        try {
            $dsn = 'mysql:host=' . $this->host . ';';
            $options = [\PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES UTF8'];
            $connect = new \PDO($dsn, $this->user, $this->pass, $options);
            $connect->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);

            $command = $connect->prepare("CREATE DATABASE {$this->database}");
            $command->execute();

        } catch (\PDOException $e) {
            return false;
        }
    }
822428
public function hasDatabase()
    {
        try {
            $pdo = new \PDO(
                'mysql:host='.$this->txpcfg['host'].';dbname='.$this->txpcfg['db'],
                $this->txpcfg['user'],
                $this->txpcfg['pass']
            );
        } catch (\PDOException $e) {
            $pdo = false;
        }

        if ($pdo === false) {
            throw new \InvalidArgumentException(
                'Unable connect to Textpattern database: '.$this->txpcfg['db'].'@'.$this->txpcfg['host']
            );
        }

        if (!$pdo->prepare('SHOW TABLES LIKE ?')->execute(array($this->txpcfg['table_prefix'] . 'textpattern'))) {
            throw new \InvalidArgumentException('Textpattern is not installed');
        }
    }
506811
private function validateDatabase()
    {
        /*
        * Check Database Connection
        */
        $dsn = $this->DBConnectComand();
        try {
            $DBConnection = new \PDO($dsn, $this->DB_USERNAME, $this->DB_PASSWORD, array(\PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION));
        }
        catch (PDOException $ex) {
            throw new \Exception('Connection to database failed: ' . $ex->getMessage());
        }

        /*
         * Check if the database is empty on install
         */
        if(!$this->isInstalled) {
            $tables = 0;
            $fetch = $this->checkDatabase($DBConnection);
            while ($result = $fetch->fetch()){
                $tables++;
                break;
            }
            if ($tables > 0) {
                throw new \Exception('Database "' . $this->DB_DATABASE . '" is not empty. Please empty the database or specify another database.');
            }
        }

        return;
    }
828851
protected function onInit()
    {
        $host = Util::get($this->params, "host", "");//host\instanceName
        $username = Util::get($this->params, "username", "");
        $password = Util::get($this->params, "password", "");
        $dbname = Util::get($this->params, "dbname", "");
        $returnDatesAsStrings = Util::get($this->params, "returnDatesAsStrings", true);
        $charset = Util::get($this->params, "charset", 'utf-8');
        $connectionInfo = array(
            "Database"=>$dbname,
            "UID"=>$username,
            "PWD"=>$password, 
            "ReturnDatesAsStrings" => $returnDatesAsStrings, 
            "CharacterSet" => $charset
        );

        $key = md5($host.$username.$password.$dbname);
        if (isset(SQLSRVDataSource::$connections[$key])) {
            $this->connection = SQLSRVDataSource::$connections[$key];
        } else {
            $conn = sqlsrv_connect($host, $connectionInfo);
            if ($conn) {
                $this->connection = $conn;
            } else {
                throw new \Exception(
                    "Connection could not be established: "
                    .print_r(sqlsrv_errors(), true)
                );
            }    
            SQLSRVDataSource::$connections[$key] = $this->connection;
        }
    }
336995
protected function checkDatabaseInformation()
    {
        $this->title("Database Information");

        $errors = [];
        $driver = Request::$post->get('driver');

        // Check fields
        if ($driver == "pdo_pgsql" || $driver == "pdo_mysql") {
            if (!Request::$post->get('host')) {
                $errors[] = "Server is required";
            }

            if (!Request::$post->get('user')) {
                $errors[] = "Username is required";
            }

            if (!Request::$post->get('dbname')) {
                $errors[] = "Database name is required";
            }
        } elseif ($driver == "pdo_sqlite") {
            if (!Request::$post->get('path')) {
                $errors[] = "Database path is required";
            }
        }

        // Check connection
        if (!count($errors)) {
            $info = [
                'driver' => $driver,
            ];

            switch ($driver) {
                case "pdo_pgsql":
                case "pdo_mysql":
                    $info = $info + [
                        'host'     => Request::$post->get('host'),
                        'user'     => Request::$post->get('user'),
                        'password' => Request::$post->get('password'),
                        'dbname'   => Request::$post->get('dbname')
                    ];
                    break;

                case "pdo_sqlite":
                    $info['path'] = Request::$post->get('path');
                    break;
            }

            try {
                // Lets try to do a few things with the database to confirm a connection.
                $db = ConnectionManager::create($info);
                $sm = $db->getSchemaManager();
                $sm->listTables();
            } catch (DBALException $e) {
                $errors[] = "Unable to connect to database: " . $e->getMessage();
            }
        }

        if (count($errors)) {
            $this->title("Database Information");
            return $this->render("steps/database_information.phtml", [
                'errors' => $errors
            ]);
        }

        $_SESSION['db'] = $info;
    }
933226
public function isSupported()
    {
        $sql = 'SHOW TABLES LIKE :table';

        $stat = $this->pdo->prepare($sql);
        $stat->bindValue(':table', $this->table);
        $stat->execute();

        return (bool) $stat->fetch(\PDO::FETCH_ASSOC);
    }
866837
public function doFinalInitialization()
    {
        if (!$this->isInitialized) {
            foreach ($this->databases as $database) {
                $database->doFinalInitialization();
            }
            $this->isInitialized = true;
        }
    }
1215376
public function getMySqlAvailable() {
    $this->logger->debug("Verifying that MySQL is available...");
    /** @var \Robo\Result $result */
    $result = $this->executor->drush("sqlq \"SHOW DATABASES\"")
      ->run();

    return $result->wasSuccessful();
  }
143324
public function check()
    {
        $result = true;

        // TODO This check tries only to connect to the database
        // But it would make sense to check
        //  a) insert, select, update, delete, etc. access
        //  a) a) Which access rights do i need? Topic hardening?
        try {
            $this->database->connect($this->database->getConfig());
        } catch (\Exception $e) {
            $result = false;
        }

        return $result;
    }
998932
private function checkDB() {
		$res = $this->query('select * from sqlite_master where type=\'table\' and name=\'dropbox\'; ');
		if (! $res) {
			try {
				$this->DB->exec('create table '.$this->DB_TableName.'(path text, fname text, dat blob, isdir integer);');
				$this->DB->exec('create index nameidx on '.$this->DB_TableName.'(path, fname)');
				$this->DB->exec('create index isdiridx on '.$this->DB_TableName.'(isdir)');
			} catch (PDOException $e) {
				return $this->setError($e->getMessage());
			}
		}
		return true;
	}
335379
public function databaseIsEmpty()
    {
        try {
            $dsn = 'mysql:host=' . $this->host . ';dbname=' . $this->database;
            $options = [\PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES UTF8'];
            $connect = new \PDO($dsn, $this->user, $this->pass, $options);
            $connect->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);

            $command = $connect->prepare("show tables");
            $command->setFetchMode(\PDO::FETCH_ASSOC);
            $command->execute();
            return empty($command->fetchAll());

        } catch (\PDOException $e) {
            return false;
        }
    }
1289941
protected function initializeDB()
    {
        $dbUser = $this->Options['db-user'] ? $this->Options['db-user'] : false;
        $dbPassword = $this->Options['db-password'] ? $this->Options['db-password'] : false;
        $dbHost = $this->Options['db-host'] ? $this->Options['db-host'] : false;
        $dbName = $this->Options['db-database'] ? $this->Options['db-database'] : false;
        $dbImpl = $this->Options['db-driver'] ? $this->Options['db-driver'] : false;
        $showSQL = $this->Options['sql'] ? true : false;

        // Forcing creation of new instance to avoid mysql wait_timeout to kill
        // the connection before it's done
        $db = eZDB::instance( false, false, true );

        if ( $dbHost or $dbName or $dbUser or $dbImpl )
        {
            $params = array();
            if ( $dbHost !== false )
                $params['server'] = $dbHost;
            if ( $dbUser !== false )
            {
                $params['user'] = $dbUser;
                $params['password'] = '';
            }
            if ( $dbPassword !== false )
                $params['password'] = $dbPassword;
            if ( $dbName !== false )
                $params['database'] = $dbName;
            $db = eZDB::instance( $dbImpl, $params, true );
            eZDB::setInstance( $db );
        }

        $db->setIsSQLOutputEnabled( $showSQL );
    }