Connects to the database.

@return void
@throw eZClusterHandlerDBNoConnectionException
@throw eZClusterHandlerDBNoDatabaseException
963566
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' );
            self::$dbparams['port']       = $fileINI->variable( 'eZDFSClusteringSettings', 'DBPort' );
            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' );
        }


        $connectString = sprintf( 'pgsql:host=%s;port=%s;dbname=%s;user=%s;password=%s',
            self::$dbparams['host'],
            self::$dbparams['port'],
            self::$dbparams['dbname'],
            self::$dbparams['user'],
            self::$dbparams['pass']
        );
        $tries = 0;
        while ( $tries < self::$dbparams['max_connect_tries'] )
        {
            try {
                $this->db = new PDO( $connectString, self::$dbparams['user'], self::$dbparams['pass'] );
            } catch ( PDOException $e ) {
                eZDebug::writeError( $e->getMessage() );
                ++$tries;
                continue;
            }
            break;
        }
        if ( !( $this->db instanceof PDO ) )
        {
            $this->_die( "Unable to connect to storage server" );
            throw new eZClusterHandlerDBNoConnectionException( $connectString, self::$dbparams['user'], self::$dbparams['pass'] );
        }


        if ( !$this->db )
            throw new eZClusterHandlerDBNoConnectionException( $connectString, self::$dbparams['user'], self::$dbparams['pass'] );

        $this->db->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
        $this->db->exec( "SET NAMES 'utf8'" );


        // DFS setup
        if ( $this->dfsbackend === null )
            $this->dfsbackend = new eZDFSFileHandlerDFSBackend();
    }
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.");
    }
  }
123256
public function _connect()
    {
        if ($this->_connection) {
            return;
        }
        parent::_connect();

        $this->getConnection()->setAttribute(Zend_Db::ATTR_STRINGIFY_FETCHES, true);

        try {
            if ($this->_serverType === null) {
                $server = substr($this->getConnection()->getAttribute(PDO::ATTR_SERVER_INFO), 0, 3);

                switch ($server) {
                    case 'DB2':
                        $this->_serverType = new Zend_Db_Adapter_Pdo_Ibm_Db2($this);

                        // Add DB2-specific numeric types
                        $this->_numericDataTypes['DECFLOAT'] = Zend_Db::FLOAT_TYPE;
                        $this->_numericDataTypes['DOUBLE']   = Zend_Db::FLOAT_TYPE;
                        $this->_numericDataTypes['NUM']      = Zend_Db::FLOAT_TYPE;

                        break;
                    case 'IDS':
                        $this->_serverType = new Zend_Db_Adapter_Pdo_Ibm_Ids($this);

                        // Add IDS-specific numeric types
                        $this->_numericDataTypes['SERIAL']       = Zend_Db::INT_TYPE;
                        $this->_numericDataTypes['SERIAL8']      = Zend_Db::BIGINT_TYPE;
                        $this->_numericDataTypes['INT8']         = Zend_Db::BIGINT_TYPE;
                        $this->_numericDataTypes['SMALLFLOAT']   = Zend_Db::FLOAT_TYPE;
                        $this->_numericDataTypes['MONEY']        = Zend_Db::FLOAT_TYPE;

                        break;
                    }
            }
        } catch (PDOException $e) {
            /** @see Zend_Db_Adapter_Exception */
            // require_once 'Zend/Db/Adapter/Exception.php';
            $error = strpos($e->getMessage(), 'driver does not support that attribute');
            if ($error) {
                throw new Zend_Db_Adapter_Exception("PDO_IBM driver extension is downlevel.  Please use driver release version 1.2.1 or later", 0, $e);
            } else {
                throw new Zend_Db_Adapter_Exception($e->getMessage(), $e->getCode(), $e);
            }
        }
    }
5000
private function connect () {
        if ($this->isConnected()) {
            return;
        }

        parent::__construct(
            $this->data_source->getDSN(),
            $this->data_source->getUser(),
            $this->data_source->getPassword(),
            $this->data_source->getDriverOptions()
        );

        parent::setAttribute(\PDO::ATTR_EMULATE_PREPARES, false);
        parent::setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
        parent::setAttribute(\PDO::ATTR_STATEMENT_CLASS, ['Gajus\Doll\PDOStatement', [$this]]);
        parent::setAttribute(\PDO::ATTR_DEFAULT_FETCH_MODE, \PDO::FETCH_ASSOC);

        $this->is_connected = true;

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

        if ($this->getAttribute(\Gajus\Doll\PDO::ATTR_LOGGING)) {
            parent::exec('SET `profiling` = 1');
            parent::exec('SET `profiling_history_size` = 100');
        }
    }
252489
public function connect() {

		if(false === $this -> connection instanceof \mysqli) {
			
			$this -> connection = new \mysqli($this -> data -> host, $this -> data -> username, $this -> data -> password, $this -> data -> db, $this -> data -> port);
			
			if($this -> data -> charset) {
	            $this -> connection -> set_charset($this -> data -> charset);
	        }
		}
	}
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);
    }
980696
protected function connect()
    {
        // Build a database connection if we don't have one connected

        $adapter = '\\Pixie\\ConnectionAdapters\\' . ucfirst(strtolower($this->adapter));

        $adapterInstance = $this->container->build($adapter, array($this->container));

        $pdo = $adapterInstance->connect($this->adapterConfig);
        $this->setPdoInstance($pdo);

        // Preserve the first database connection with a static property
        if (!static::$storedConnection) {
            static::$storedConnection = $this;
        }
    }
729330
public function connect() {

		if($this->db !== null) return $this->db;

		try {

			$this->db = new \PDO(
				$this->config['datasource'],
				$this->config['username'],
				$this->config['password']
			);

			$this->db->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);

			return true;

		} catch(\PDOException $e) {
			throw new \HybridLogic\DB\Exception\ConnectionException($e);
		}

	}
536763
protected function _connect()
    {
        if ($this->_connection) {
            return;
        }

        if (!extension_loaded('mysqli')) {
            /**
             * @see Zend_Db_Adapter_Mysqli_Exception
             */
            // require_once 'Zend/Db/Adapter/Mysqli/Exception.php';
            throw new Zend_Db_Adapter_Mysqli_Exception('The Mysqli extension is required for this adapter but the extension is not loaded');
        }

        if (isset($this->_config['port'])) {
            $port = (integer) $this->_config['port'];
        } else {
            $port = null;
        }

        $this->_connection = mysqli_init();

        $enable_ssl = false;
        $ssl_options = array (
            'ssl_ca' => null,
            'ssl_ca_path' => null,
            'ssl_cert' => null,
            'ssl_cipher' => null,
            'ssl_key' => null,
        );

        if(!empty($this->_config['driver_options'])) {
            foreach($this->_config['driver_options'] as $option=>$value) {
                if(array_key_exists($option, $ssl_options)) {
                    $ssl_options[$option] = $value;
                    $enable_ssl = true;
                } elseif(is_string($option)) {
                    // Suppress warnings here
                    // Ignore it if it's not a valid constant
                    $option = @constant(strtoupper($option));
                    if($option === null)
                        continue;
                }
                mysqli_options($this->_connection, $option, $value);
            }
        }


        if ($enable_ssl) {
            mysqli_ssl_set(
                $this->_connection,
                $ssl_options['ssl_key'],
                $ssl_options['ssl_cert'],
                $ssl_options['ssl_ca'],
                $ssl_options['ssl_ca_path'],
                $ssl_options['ssl_cipher']
            );
        }

        $flags = null;
        if ($enable_ssl) {
            $flags = MYSQLI_CLIENT_SSL;
            if (!empty($this->_config['driver_options']['ssl_no_verify'])
                && defined('MYSQLI_CLIENT_SSL_DONT_VERIFY_SERVER_CERT')
            ) {
                $flags = MYSQLI_CLIENT_SSL_DONT_VERIFY_SERVER_CERT;
            }
        }

        // Suppress connection warnings here.
        // Throw an exception instead.
        $_isConnected = @mysqli_real_connect(
            $this->_connection,
            $this->_config['host'],
            $this->_config['username'],
            $this->_config['password'],
            $this->_config['dbname'],
            $port,
            $socket = null,
            $enable_ssl ? $flags : null
        );

        if ($_isConnected === false || mysqli_connect_errno()) {

            $this->closeConnection();
            /**
             * @see Zend_Db_Adapter_Mysqli_Exception
             */
            // require_once 'Zend/Db/Adapter/Mysqli/Exception.php';
            throw new Zend_Db_Adapter_Mysqli_Exception(mysqli_connect_error());
        }

        if (!empty($this->_config['charset'])) {
            mysqli_set_charset($this->_connection, $this->_config['charset']);
        }
    }
1077581
public function connect()
    {
        if (!$this->isConnected()) {
            $this->pdo = $this->createPDO();
            $this->pdo->setAttribute(\PDO::ATTR_STATEMENT_CLASS, [Statement::class]);
        }
    }
1346749
private function connect()
    {
		$this->sessionLink = mysqli_connect($this->host_master,$this->user,$this->password,$this->name) or die("Error " . mysqli_error($this->sessionLink));

//        $this->pdo = new \PDO($dsn, $this->username, $this->password, $this->connectionOptions);
//        $this->pdo->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
//        $this->driver = $this->pdo->getAttribute(\PDO::ATTR_DRIVER_NAME);
    }
1246503
private function connect()
    {
        if (!$this->isConnected) {
            parent::__construct(
                $this->dsn,
                $this->server->getUsername(),
                $this->server->getPassword(),
                $this->driverOptions
            );
            parent::setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            parent::setAttribute(
                PDO::ATTR_STATEMENT_CLASS,
                [__NAMESPACE__ . '\\' . self::PDO_STATEMENT_CLASS, [$this]]
            );

            $this->isConnected = true;
        }
    }
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);
        }
    }
498346
public function connect() {
		try {
			$this->_connect ();
			return true;
		} catch ( \PDOException $e ) {
			throw new DBException ( $e->getMessage (), $e->getCode (), $e->getPrevious () );
		}
	}
570776
protected function connect()
    {
        if (!is_object(self::$instance)) {
            self::$instance = new \Memcache();

            // Cluster connections
            $hosts = explode(',', $this->options['host']);
            $ports = explode(',', $this->options['port']);
            if (empty($ports[0])) {
                $ports[0] = 11211;
            }

            // connection establishment
            foreach ((array) $hosts as $i => $host) {
                $port = isset($ports[$i]) ? $ports[$i] : $ports[0];
                $this->options['timeout'] > 0 ?
                    self::$instance->addServer($host, $port, $this->options['persistent'], 1, $this->options['timeout']) :
                    self::$instance->addServer($host, $port, $this->options['persistent'], 1);
            }
        }
    }
150770
public static function connectDb() {
        if 
            (!isset(self::$dbLink)) {
            $dbParams = self::getDatabaseParameters();
            self::validateDbParameters($dbParams);
            $dbParamsSan = self::sanitizeDbParameters($dbParams);
            $config = new Configuration();
            self::$dbLink = DriverManager::getConnection($dbParamsSan, $config);
        }
        
        return self::$dbLink;
    }
34467
private function connect()
    {
        $username = $this->config->get('username');
        $password = $this->config->get('password');
        $host = $this->config->get('hostname');
        $database = $this->config->get('database');
        $schema = $this->config->get('schema');
        $this->dsn = $this->config->get('dsn');
        if (!$this->config->has('type', Type::STRING))
            throw new ConfigurationException("Please specify the database type in the configuration section [sql]");

        $type = $this->config->getString('type');

        // Set up the driver
        $this->driver = $this->setupDriver($type);
        $this->driver->setTablePrefix($this->config->dget('prefix', ''));
            
        if (!$this->dsn)
        {
            $this->dsn = $this->driver->generateDSN($this->config->toArray());
            self::$logger->debug("Generated DSN: {0}", [$this->dsn]);
            $this->config->set('dsn', $this->dsn);
        }
            
        // Create the PDO and connect it to the database, setting default options
        //$pdo = new PDO($this->dsn, $username, $password);
        $pdo = DI::getInjector()
            ->newInstance(
                PDO::class,
                ['dsn' => $this->dsn, 'username' => $username, 'passwd' => $password]
            )
        ;
        $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        $pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
            
        $this->pdo = $pdo;
    }