Connects to the database.

@return void
@throws eZClusterHandlerDBNoConnectionException
@throws eZClusterHandlerDBNoDatabaseException
10328
public function _connect()
    {
        $siteINI = eZINI::instance( 'site.ini' );

        // DB Connection setup
        // This part is not actually required since _connect will only be called
        // once, but it is useful to run the unit tests. So be it.
        // @todo refactor this using eZINI::setVariable in unit tests
        if ( self::$dbparams === null )
        {
            $fileINI = eZINI::instance( 'file.ini' );

            self::$dbparams = array();
            self::$dbparams['host']       = $fileINI->variable( 'eZDFSClusteringSettings', 'DBHost' );
            $dbPort = $fileINI->variable( 'eZDFSClusteringSettings', 'DBPort' );
            self::$dbparams['port']       = $dbPort !== '' ? $dbPort : null;
            self::$dbparams['socket']     = $fileINI->variable( 'eZDFSClusteringSettings', 'DBSocket' );
            self::$dbparams['dbname']     = $fileINI->variable( 'eZDFSClusteringSettings', 'DBName' );
            self::$dbparams['user']       = $fileINI->variable( 'eZDFSClusteringSettings', 'DBUser' );
            self::$dbparams['pass']       = $fileINI->variable( 'eZDFSClusteringSettings', 'DBPassword' );

            self::$dbparams['max_connect_tries'] = $fileINI->variable( 'eZDFSClusteringSettings', 'DBConnectRetries' );
            self::$dbparams['max_execute_tries'] = $fileINI->variable( 'eZDFSClusteringSettings', 'DBExecuteRetries' );

            self::$dbparams['sql_output'] = $siteINI->variable( "DatabaseSettings", "SQLOutput" ) == "enabled";

            self::$dbparams['cache_generation_timeout'] = $siteINI->variable( "ContentSettings", "CacheGenerationTimeout" );
        }

        $serverString = self::$dbparams['host'];
        if ( self::$dbparams['socket'] )
            $serverString .= ':' . self::$dbparams['socket'];
        elseif ( self::$dbparams['port'] )
            $serverString .= ':' . self::$dbparams['port'];

        $maxTries = self::$dbparams['max_connect_tries'];
        $tries = 0;
        eZDebug::accumulatorStart( 'mysql_cluster_connect', 'MySQL Cluster', 'Cluster database connection' );
        while ( $tries < $maxTries )
        {
            if ( $this->db = mysqli_connect( self::$dbparams['host'], self::$dbparams['user'], self::$dbparams['pass'], self::$dbparams['dbname'], self::$dbparams['port'] ) )
                break;
            ++$tries;
        }
        eZDebug::accumulatorStop( 'mysql_cluster_connect' );
        if ( !$this->db )
        {
            throw new eZClusterHandlerDBNoConnectionException(
                $serverString,
                self::$dbparams['user'],
                self::$dbparams['pass'],
                'Error ' . mysqli_connect_errno() . ': ' . mysqli_connect_error()
            );
        }

        /*if ( !mysql_select_db( self::$dbparams['dbname'], $this->db ) )
            throw new eZClusterHandlerDBNoDatabaseException( self::$dbparams['dbname'] );*/

        // DFS setup
        $this->dfsbackend = eZDFSFileHandlerBackendFactory::build();

        $charset = trim( $siteINI->variable( 'DatabaseSettings', 'Charset' ) );
        if ( $charset === '' )
        {
            $charset = eZTextCodec::internalCharset();
        }

        if ( $charset )
        {
            if ( !mysqli_set_charset( $this->db, eZMySQLCharset::mapTo( $charset ) ) )
            {
                $this->_fail( "Failed to set Database charset to $charset." );
            }
        }
    }
901641
public function connect()
    {
        try {
            if (!$this->controllerStarter->isExistsPidFile()) {
                throw new ConnectionException('Pid file is not exists.');
            }
            $this->client->connect($this->connectAddress);
        } catch (ConnectionException $e) {
            $this->controllerStarter->start();
        }
//        $this->client->block();
    }
890812
public function connect(): void
    {
        // no need to get excited
        if ($this->isConnected()) {
            return;
        }

        // export credentials & others
        [$host, $name, $username, $password] = [
            $this->config['host'], $this->config['name'],
            $this->config['username'], $this->config['password'],
        ];
        $port = (int) $this->config['port'];
        $socket = (string) $this->config['socket'];

        // call big boss
        $resource = mysqli_init();

        // supported constants: http://php.net/mysqli.options
        if (isset($this->config['options'])) {
            foreach ($this->config['options'] as $option => $value) {
                if (!$resource->options($option, $value)) {
                    throw new ConnectionException("Setting '{$option}' option failed!");
                }
            }
        }

        // start connection profile
        $this->profiler && $this->profiler->start('connection');

        $resourceStatus =@ $resource->real_connect($host, $username, $password, $name, $port, $socket);
        if (!$resourceStatus) {
            $error = $this->parseConnectionError();
            throw new ConnectionException($error['message'], $error['code'], $error['sql_state']);
        }

        // finish connection profile
        $this->profiler && $this->profiler->end('connection');

        // log with info level
        $this->logger && $this->logger->log(Logger::INFO, sprintf('New connection via %s addr.', Util::getIp()));

        // set charset for connection
        if (isset($this->config['charset'])) {
            $run = $resource->set_charset($this->config['charset']);
            if (!$run) {
                throw new ConnectionException(sprintf('Unable to connect to MySQL server at "%s", '.
                    'invalid or not-supported character set "%s" given!', $this->config['host'], $this->config['charset']),
                        $resource->errno, SqlState::OPPA_CHARSET_ERROR);
            }
        }

        // set timezone for connection
        if (isset($this->config['timezone'])) {
            $run = $resource->query('SET time_zone = \''. $resource->real_escape_string($this->config['timezone']) .'\'');
            if (!$run) {
                throw new ConnectionException(sprintf('Unable to connect to MySQL server at "%s", '.
                    'invalid or not-supported timezone "%s" given.', $this->config['host'], $this->config['timezone']),
                        $resource->errno, SqlState::OPPA_TIMEZONE_ERROR);
            }
        }

        // assign resource
        $this->resource = new Resource($resource);

        // fill mapper map for once
        if ($this->mapper) {
            $map = $cache = null;
            if ($this->config['map_result_cache']) {
                $cache = new Cache();
                $cache->read('mapper.map', $map, true, $this->config['map_result_cache_ttl']);
            }

            if ($map == null) {
                try {
                    $result = $this->query("SELECT table_name, column_name, data_type, is_nullable, numeric_precision, character_maximum_length FROM information_schema.columns WHERE table_schema = '{$name}'", null, -1, 2);
                    if ($result->count()) {
                        $map = [];
                        foreach ($result->items() as $item) {
                            $item = (object) array_change_key_case($item); // normalize key cases

                            $length = null;
                            if ($item->data_type == 'bit') { // for only bools
                                $length = (int) $item->numeric_precision;
                            } elseif (substr($item->data_type, -4) == 'char') { // for extra (char) crop
                                $length = (int) $item->character_maximum_length;
                            }

                            $map[$item->table_name][$item->column_name] = [
                                /* type */ Mapper::normalizeType($item->data_type, $length),
                                /* length */ $length,
                                /* nullable */ ($item->is_nullable == 'YES'),
                            ];
                        }

                        $cache && $cache->write('mapper.map', $map);
                    }
                    $result->reset();
                } catch (QueryException $e) {
                    throw new QueryException('Could not retrieve schema info for mapper!', null,
                        SqlState::OPPA_CONNECTION_ERROR, $e);
                }
            }

            // set map
            $this->mapper->setMap($map);
        }
    }
770946
private function _connect()
    {
        if (empty($this->_config))
            throw new \Exception('Empty connection settings provided'); 
        
        $port = $this->_config->getPort();
        $port = !empty($port) ? $port : 3306;
        $dsn = $this->_config->getType().':host='.$this->_config->getHost().';port='.$port.';dbname='.$this->_config->getName();
        // Create a PDO Instance for this user + database combination
        try {
            $this->_conn = new \PDO($dsn, $this->_config->getUser(), $this->_config->getPassword());
        } catch(\PDOException $pe) {
            throw new \RuntimeException("Cannot connect to DB '".$this->_config->getName().
                "' with user '".$this->_config->getUser()."'".PHP_EOL."Message: ".$pe->getMessage());
        }

        $this->_conn->setAttribute(\PDO::ATTR_PERSISTENT, false);
        $this->_conn->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
        $this->_conn->setAttribute(\PDO::MYSQL_ATTR_INIT_COMMAND, "SET NAMES 'UTF8'");
        $this->_conn->setAttribute(\PDO::ATTR_DEFAULT_FETCH_MODE, \PDO::FETCH_ASSOC);
        $this->_conn->setAttribute(\PDO::ATTR_ORACLE_NULLS, \PDO::NULL_TO_STRING);
        $this->_conn->setAttribute(\PDO::ATTR_EMULATE_PREPARES, true);
    }
384256
public function connect(): bool
    {
        try {
            $this->checkConnect();
            $this->log('Connect to ' . $this->connect['host']);
            $this->handler = new \PDO(
                $this->connect['type'] . ':host=' . $this->connect['host'] . ';dbname=' . $this->connect['name'],
                $this->connect['user'],
                $this->connect['pass'],
                $this->connect['options']
            );

            foreach ($this->attributes as $attribute => $value) {
                $this->handler->setAttribute($attribute, $value);
            }

            $this->ok();
        } catch (\Exception $e) {
            throw new DbException("Attempt connection to database is failed: {$e->getMessage()}");
        }
        return true;
    }
744448
public function connect()
    {
        if (self::$profiling) {
            $timer = $this->initProfiler();
        }

        $this->connection = mysqli_init();


        if($this->enable_ssl){
            mysqli_ssl_set($this->connection, $this->ssl_key, $this->ssl_cert, $this->ssl_ca, $this->ssl_ca_path, $this->ssl_cipher);
        }

        // Make sure MySQL returns all matched rows on update queries including
        // rows that actually didn't have to be updated because the values didn't
        // change. This matches common behaviour among other database systems.
        // See #6296 why this is important in tracker
        $flags = MYSQLI_CLIENT_FOUND_ROWS;
        if ($this->enable_ssl){
            $flags = $flags | MYSQLI_CLIENT_SSL;
        }
        if ($this->ssl_no_verify && defined('MYSQLI_CLIENT_SSL_DONT_VERIFY_SERVER_CERT')){
            $flags = $flags | MYSQLI_CLIENT_SSL_DONT_VERIFY_SERVER_CERT;
        }
        mysqli_real_connect($this->connection, $this->host, $this->username, $this->password, $this->dbname, $this->port, $this->socket, $flags);
        if (!$this->connection || mysqli_connect_errno()) {
            throw new DbException("Connect failed: " . mysqli_connect_error());
        }

        if ($this->charset && !mysqli_set_charset($this->connection, $this->charset)) {
            throw new DbException("Set Charset failed: " . mysqli_error($this->connection));
        }

        $this->password = '';

        if (self::$profiling && isset($timer)) {
            $this->recordQueryProfile('connect', $timer);
        }
    }
1087722
private function connect()
    {
        // Connecting with PDO.
        try {
            switch ($this->dbType) {
                case 'sqlite':
                    $this->dbHandler = @new PDO("sqlite:".$this->dbName, null, null, $this->pdoSettings);
                    break;
                case 'mysql':
                case 'pgsql':
                case 'dblib':
                    $this->dbHandler = @new PDO(
                        $this->dsn,
                        $this->user,
                        $this->pass,
                        $this->pdoSettings
                    );
                    // Execute init commands once connected
                    foreach ($this->dumpSettings['init_commands'] as $stmt) {
                        $this->dbHandler->exec($stmt);
                    }
                    // Store server version
                    $this->version = $this->dbHandler->getAttribute(PDO::ATTR_SERVER_VERSION);
                    break;
                default:
                    throw new Exception("Unsupported database type (".$this->dbType.")");
            }
        } catch (PDOException $e) {
            throw new Exception(
                "Connection to ".$this->dbType." failed with message: ".
                $e->getMessage()
            );
        }

        if (is_null($this->dbHandler)) {
            throw new Exception("Connection to ".$this->dbType."failed");
        }

        $this->dbHandler->setAttribute(PDO::ATTR_ORACLE_NULLS, PDO::NULL_NATURAL);
        $this->typeAdapter = TypeAdapterFactory::create($this->dbType, $this->dbHandler, $this->dumpSettings);
    }
1212728
protected function connect()
    {
        // Already connected
        if ($this->database !== null) {
            return;
        }

        $connection = $this->resolver
            ->connection($this->config('connection'));

        if ($connection->getDriverName() !== 'pgsql') {
            throw new \InvalidArgumentException('Connection should use pgsql driver.');
        }

        $this->database = $connection;
    }
544817
public function connect()
    {
        $dsnString = "{$this->dbDriver}:host={$this->dbHostname};dbname={$this->dbName};";
        $dsnString .= "charset={$this->dbCharset}";
        /*
         * Try to connect to database
         */
        try {
            $this->dbConnection = new \PDO(
                $dsnString,
                "{$this->dbUsername}",
                "{$this->dbPassword}",
                $this->driverOptions
            );
        } catch (\PDOException $ex) {
            // Error during database connection, check params.
            throw new \InvalidArgumentException(
                __METHOD__.': '.$ex->getMessage()
            );
        }

        return $this->dbConnection;
    }
1251048
protected function _connect(){

		$this->_connection = @mysqli_connect(
			$this->_server, $this->_username, $this->_password);

		if(!@mysqli_select_db($this->_connection, $this->_database)){

			// Connection established, but unable to access the database

			if(!$this->_connection){

				throw new ConnectionException('Could not open the
					requested database');
			}
			else{

				throw new ConnectionException('Could not connect to the
					MySQL server');
			}
		}
	}
1359554
private function connect() {
    // connect
    if (isset($this->connectionParams['dbType']) && isset($this->connectionParams['dbHostName']) &&
      isset($this->connectionParams['dbUserName']) && isset($this->connectionParams['dbPassword']) &&
      isset($this->connectionParams['dbName'])) {

      $dbType = strtolower($this->connectionParams['dbType']);
      $this->isFileDB = $dbType == 'sqlite' && strtolower($this->connectionParams['dbName']) != ':memory:';

      $this->connId = join(',', [$this->connectionParams['dbType'], $this->connectionParams['dbHostName'],
          $this->connectionParams['dbUserName'], $this->connectionParams['dbPassword'], $this->connectionParams['dbName'],
          // make sure that the sequence mapper uses it's own connection for separate transaction management
          (!$this->isFileDB && $this->getType() == $this->getSequenceMapper()->getType())
      ]);

      // reuse an existing adapter if possible
      if (isset(self::$adapters[$this->connId])) {
        $this->adapter = self::$adapters[$this->connId];
      }
      else {
        try {
          $charSet = isset($this->connectionParams['dbCharSet']) ?
                  $this->connectionParams['dbCharSet'] : 'utf8';

          // create new connection
          $pdoParams = [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION];
          // driver specific
          switch ($dbType) {
            case 'mysql':
              $pdoParams[PDO::MYSQL_ATTR_USE_BUFFERED_QUERY] = true;
              $pdoParams[PDO::MYSQL_ATTR_INIT_COMMAND] = "SET NAMES ".$charSet;
              break;
            case 'sqlite':
              if (!$this->isFileDB) {
                $pdoParams[PDO::ATTR_PERSISTENT] = true;
              }
              else {
                $this->connectionParams['dbName'] = FileUtil::realpath(WCMF_BASE.$this->connectionParams['dbName']);
              }
              break;
          }

          $params = [
            'hostname' => $this->connectionParams['dbHostName'],
            'username' => $this->connectionParams['dbUserName'],
            'password' => $this->connectionParams['dbPassword'],
            'database' => $this->connectionParams['dbName'],
            'driver' => 'Pdo_'.ucfirst($this->connectionParams['dbType']),
            'driver_options' => $pdoParams
          ];

          if (!empty($this->connectionParams['dbPort'])) {
            $params['port'] = $this->connectionParams['dbPort'];
          }
          $this->adapter = new Adapter($params);

          // store the connection for reuse
          self::$adapters[$this->connId] = $this->adapter;
        }
        catch(\Exception $ex) {
          throw new PersistenceException("Connection to ".$this->connectionParams['dbHostName'].".".
            $this->connectionParams['dbName']." failed: ".$ex->getMessage());
        }
      }
      // get database prefix if defined
      if (isset($this->connectionParams['dbPrefix'])) {
        $this->dbPrefix = $this->connectionParams['dbPrefix'];
      }
    }
    else {
      throw new IllegalArgumentException("Wrong parameters for constructor.");
    }
  }
336677
private function Connect()
    {
        $this->conn = parent::getConn();
        $this->delete = $this->conn->prepare($this->delete);
    }
683401
protected function connect()
        {
                $this->_socket=@stream_socket_client(
                        $this->hostname.':'.$this->port,
                        $errorNumber,
                        $errorDescription,
                        $this->timeout ? $this->timeout : ini_get("default_socket_timeout")
                );
                if ($this->_socket)
                {
                        if($this->password!==null)
                                $this->executeCommand('AUTH',array($this->password));
                        $this->executeCommand('SELECT',array($this->database));
                }
                else
                        throw new CException('Failed to connect to redis: '.$errorDescription,(int)$errorNumber);
        }
1005234
function connect()
    {
        $db_config = $this->config;
        if (empty($db_config['persistent']))
        {
            $this->conn = mysql_connect($db_config['host'] . ':' . $db_config['port'],
                $db_config['user'],
                $db_config['passwd']);
        }
        else
        {
            $this->conn = mysql_pconnect($db_config['host'] . ':' . $db_config['port'],
                $db_config['user'],
                $db_config['passwd']);
        }
        if (!$this->conn)
        {
            Swoole\Error::info(__CLASS__." SQL Error", mysql_error($this->conn));
            return false;
        }
        mysql_select_db($db_config['name'], $this->conn) or Swoole\Error::info("SQL Error", mysql_error($this->conn));
        if ($db_config['setname'])
        {
            mysql_query('set names ' . $db_config['charset'], $this->conn) or Swoole\Error::info("SQL Error",
                mysql_error($this->conn));
        }
        return true;
    }
371302
protected function connect()
    {
        if ($this->databaseHandle !== null) {
            return;
        }
        try {
            $splitdsn = explode(':', $this->dataSourceName, 2);
            $this->pdoDriver = $splitdsn[0];

            if ($this->pdoDriver === 'sqlite' && !file_exists($splitdsn[1])) {
                if (!file_exists(dirname($splitdsn[1]))) {
                    Files::createDirectoryRecursively(dirname($splitdsn[1]));
                }
                $this->databaseHandle = new \PDO($this->dataSourceName, $this->username, $this->password);
                $this->createCacheTables();
            } else {
                $this->databaseHandle = new \PDO($this->dataSourceName, $this->username, $this->password);
            }
            $this->databaseHandle->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);

            if ($this->pdoDriver === 'mysql') {
                $this->databaseHandle->exec('SET SESSION sql_mode=\'ANSI\';');
            }
        } catch (\PDOException $exception) {
            throw new Exception('Could not connect to cache table with DSN "' . $this->dataSourceName . '". PDO error: ' . $exception->getMessage(), 1334736164);
        }
    }
857376
private function connect () {
    $connectionString = "host=".$this->server." port=".$this->port." dbname=".$this->db." user=".$this->user." password=".$this->password;
    $this->handler = pg_connect ($connectionString);
  }
908217
public function connect(): DatabaseConnection
    {
        if (null !== $this->pdo) {
            return $this;
        }

        try {
            $pdoCreator = $this->getPdoCreator();
            $this->pdo  = $pdoCreator($this->configuration);
            $this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            $this->pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
            if ($this->configuration->hasInitialQuery()) {
                $this->pdo->query($this->configuration->getInitialQuery());
            }
        } catch (PDOException $pdoe) {
            throw new DatabaseException($pdoe->getMessage(), $pdoe);
        }

        return $this;
    }