Connect to the database

@param string $dbType Database adapter type for Zend_Db
@param array|object $dbDescription Adapter-specific connection settings
@return Zend_Db_Adapter_Abstract
@see Zend_Db::factory()
977146
protected function _connect($dbType, $dbDescription)
    {
        if(is_object($dbDescription)) {
            $dbDescription = get_object_vars($dbDescription);
        }
        return Zend_Db::factory($dbType, $dbDescription);
    }
480344
protected function _setDbAdapter(Zend_Db_Adapter_Abstract $zendDb = null)
    {
        $this->_zendDb = $zendDb;

        /**
         * If no adapter is specified, fetch default database adapter.
         */
        if(null === $this->_zendDb) {
            require_once 'Zend/Db/Table/Abstract.php';
            $this->_zendDb = Zend_Db_Table_Abstract::getDefaultAdapter();
            if (null === $this->_zendDb) {
                require_once 'Zend/Auth/Adapter/Exception.php';
                throw new Zend_Auth_Adapter_Exception('No database adapter present');
            }
        }

        return $this;
    }
1101773
public function databaseConnection($dataSource = 'default')
    {
        try {
            $connection = ConnectionManager::get($dataSource);
            $connected = $connection->connect();
        } catch (MissingConnectionException $connectionError) {
            $connected = false;
        }
        return $connected;
    }
511693
protected function _morphTable($tableName, $definition, $foreignKeys, $dbAdapter)
    {
        $ignoreDropForeignKeys = array();
        /** @var \Phalcon\Db\Adapter $connection */
        $connection = $this->getDI()->get($dbAdapter);
        if ($dbAdapter === 'dbCassandra') {
            $schema = $connection->getDescriptor()['keyspace'];
        } elseif ($dbAdapter === 'dbPostgresql') {
            $schema = $connection->getDescriptor()['schema'];
        } else {
            $schema = $connection->getDescriptor()['dbname'];
        }

        $sql = array();
        $tableExists = $connection->tableExists($tableName, $schema);
        if (isset($definition['columns'])) {

            if (count($definition['columns']) == 0) {
                throw new Exception('Table must have at least one column');
            }

            $fields = array();
            foreach ($definition['columns'] as $tableColumn) {
                if (!is_object($tableColumn)) {
                    throw new Exception('Table must have at least one column');
                }
                $fields[$tableColumn->getName()] = $tableColumn;
            }

            if ($tableExists) {

                $localFields = array();
                $description = $connection->describeColumns($tableName, $schema);
                foreach ($description as $field) {
                    $localFields[$field->getName()] = $field;
                }

                foreach ($fields as $fieldName => $tableColumn) {
                    if ($dbAdapter === 'dbPostgresql') {
                        $schema = $connection->getDescriptor()['schema'];
                    }


                    if (!isset($localFields[$fieldName])) {
                        /**
                         * ADD COLUMN
                         */
                        $rawSql = $connection->getDialect()->addColumn($tableName, $tableColumn->getSchemaName(), $tableColumn);
                        $sql[] = '$this->' . $dbAdapter . '->query(\'' . $rawSql . '\');';
                    } else {

                        /**
                         * ALTER TABLE
                         */
                        $changed = false;

                        if ($localFields[$fieldName]->getType() != $tableColumn->getType()) {
                            // If we are on MySQL DB, and the current column in DB is INT(1)
                            // and current annotation is "boolean", we don't notify change
                            // because when we save a boolean column in MySQL it's converted to INT(1)
                            // It prevents executing useless DB updates on each run
                            if ($dbAdapter !== 'dbMysql' || $localFields[$fieldName]->getType() !== \Phalcon\Db\Column::TYPE_INTEGER
                                || $localFields[$fieldName]->getSize() !== 1 || $tableColumn->getType() !== \Phalcon\Db\Column::TYPE_BOOLEAN
                            ) {
                                $changed = true;
                            }
                        }

                        if ($tableColumn->isNotNull() != $localFields[$fieldName]->isNotNull()) {
                            $changed = true;
                        }

                        if ($tableColumn->getSize() && $tableColumn->getSize() != $localFields[$fieldName]->getSize()) {
                            $changed = true;
                        }

                        if ($changed == true) {
                            $existingForeignKeys = [];

                            // We check if there is a foreign key constraint
                            if ($dbAdapter === 'dbMysql') {
                                $results = $connection->query("SELECT TABLE_SCHEMA,TABLE_NAME,COLUMN_NAME,CONSTRAINT_NAME,REFERENCED_TABLE_SCHEMA,REFERENCED_TABLE_NAME,REFERENCED_COLUMN_NAME FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE WHERE REFERENCED_TABLE_SCHEMA = '" . $connection->getDescriptor()['dbname'] . "' AND REFERENCED_TABLE_NAME = '" . $tableName . "' AND REFERENCED_COLUMN_NAME = '" . $tableColumn->getName() . "'");
                                foreach ($results->fetchAll() as $r) {
                                    $rules = $connection->query('SELECT UPDATE_RULE, DELETE_RULE FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS WHERE CONSTRAINT_NAME="' . $r['CONSTRAINT_NAME'] . '" AND CONSTRAINT_SCHEMA ="' . $r['TABLE_SCHEMA'] . '"');
                                    $rules = $rules->fetch();
                                    $r['UPDATE_RULE'] = $rules['UPDATE_RULE'];
                                    $r['DELETE_RULE'] = $rules['DELETE_RULE'];

                                    /**
                                     * DROP FOREIGN KEY BECAUSE WE CHANGE THE CURRENT COLUMN
                                     */
                                    $rawSql = $connection->getDialect()->dropForeignKey($r['TABLE_NAME'], $r['TABLE_SCHEMA'], $r['CONSTRAINT_NAME']);
                                    $sql[] = '$this->' . $dbAdapter . '->query(\'' . $rawSql . '\');';
                                    $existingForeignKeys[] = $r;
                                }
                            } elseif ($dbAdapter === 'dbPostgresql') {
                                $sqlconstraint = $this->getPGSQLConstraint($tableName, $tableColumn->getName());
                                $results = $connection->query($sqlconstraint);
                                foreach ($results->fetchAll() as $r) {

                                    $r['UPDATE_RULE'] = $r['on_update'];
                                    $r['DELETE_RULE'] = $r['on_delete'];
                                    $r['TABLE_NAME'] = $r['table_name'];
                                    $r['TABLE_SCHEMA'] = $r['constraint_schema'];
                                    $r['CONSTRAINT_NAME'] = $r['constraint_name'];
                                    $r['REFERENCED_TABLE_SCHEMA'] = $r['constraint_schema'];
                                    $r['REFERENCED_TABLE_NAME'] = $r['references_table'];
                                    $r['REFERENCED_COLUMN_NAME'] = $r['references_field'];
                                    $r['COLUMN_NAME'] = $r['column_name'];

                                    /**
                                     * DROP FOREIGN KEY BECAUSE WE CHANGE THE CURRENT COLUMN
                                     */
                                    $rawSql = $connection->getDialect()->dropForeignKey($r['TABLE_NAME'], $r['TABLE_SCHEMA'], $r['CONSTRAINT_NAME']);
                                    $sql[] = '$this->' . $dbAdapter . '->query(\'' . $rawSql . '\');';
                                    $existingForeignKeys[] = $r;
                                }
                            }

                            /**
                             * ALTER TABLE
                             */
                            if ($dbAdapter === 'dbPostgresql') {
                                $rawSql = $connection->getDialect()->modifyColumn($tableName, $tableColumn->getSchemaName(), $tableColumn, $localFields[$fieldName]);
                            } else {
                                $rawSql = $connection->getDialect()->modifyColumn($tableName, $tableColumn->getSchemaName(), $tableColumn);
                            }
                            $sql[] = '$this->' . $dbAdapter . '->query(\'' . $rawSql . '\');';

                            if ($existingForeignKeys) {
                                foreach ($existingForeignKeys as $r) {
                                    /**
                                     * ADD FOREIGN KEY AFTER DROP ONE (TO CHANGE IT)
                                     */
                                    $rawSql = $connection->getDialect()->addForeignKey(
                                        $r['TABLE_NAME'],
                                        $r['TABLE_SCHEMA'],
                                        new Reference(
                                            $r['CONSTRAINT_NAME'],
                                            array(
                                                "referencedSchema" => $r['REFERENCED_TABLE_SCHEMA'],
                                                "referencedTable" => $r['REFERENCED_TABLE_NAME'],
                                                "columns" => array($r['COLUMN_NAME']),
                                                "referencedColumns" => array($r['REFERENCED_COLUMN_NAME']),
                                                'onUpdate' => $r['UPDATE_RULE'],
                                                'onDelete' => $r['DELETE_RULE']
                                            )
                                        ));
                                    $sql[] = '$this->' . $dbAdapter . '->query(\'' . $rawSql . '\');';
                                }
                            }
                        }
                    }
                }

                /**
                 * DROP COLUMN (and foreign key)
                 */
                foreach ($localFields as $fieldName => $localField) {
                    if (!isset($fields[$fieldName])) {
                        if ($dbAdapter === 'dbMysql') {
                            // We check if there is a foreign key constraint
                            $results = $connection->query("SELECT TABLE_SCHEMA,TABLE_NAME,COLUMN_NAME,CONSTRAINT_NAME,REFERENCED_TABLE_SCHEMA,REFERENCED_TABLE_NAME,REFERENCED_COLUMN_NAME FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE WHERE REFERENCED_TABLE_SCHEMA = '" . $schema . "' AND TABLE_NAME = '" . $tableName . "' AND COLUMN_NAME = '" . $fieldName . "'");
                            foreach ($results->fetchAll() as $r) {
                                $ignoreDropForeignKeys[] = $r['CONSTRAINT_NAME'];
                                $rawSql = $connection->getDialect()->dropForeignKey($r['TABLE_NAME'], $r['TABLE_SCHEMA'], $r['CONSTRAINT_NAME']);
                                $sql[] = '$this->' . $dbAdapter . '->query(\'' . $rawSql . '\');';
                            }
                        } elseif ($dbAdapter === 'dbPostgresql') {
                            $sqlconstraint = $this->getPGSQLConstraint($tableName, $fieldName);
                            $results = $connection->query($sqlconstraint);
                            foreach ($results->fetchAll() as $r) {
                                $ignoreDropForeignKeys[] = $r['CONSTRAINT_NAME'];
                                $rawSql = $connection->getDialect()->dropForeignKey($r['table_name'], $r['constraint_schema'], $r['constraint_name']);
                                $sql[] = '$this->' . $dbAdapter . '->query(\'' . $rawSql . '\');';
                            }
                        }
                        $rawSql = $connection->getDialect()->dropColumn($tableName, $schema, $fieldName);
                        $sql[] = '$this->' . $dbAdapter . '->query(\'' . $rawSql . '\');';
                    }
                }
            } else {
                /**
                 * CREATE TABLE IF NOT EXISTS
                 */
                $rawSql = $connection->getDialect()->createTable($tableName, $schema, $definition);
                if ($dbAdapter === 'dbPostgresql') {
                    $sqlInstructions = explode(';', $rawSql);
                    foreach ($sqlInstructions as $instruction) {
                        if ($instruction !== "" && strpos($instruction, '_pkey" ON') === false) {
                            $sql[] = '$this->' . $dbAdapter . '->query(\'' . $instruction . '\');';
                        }
                    }
                } else {
                    $sql[] = '$this->' . $dbAdapter . '->query(\'' . $rawSql . '\');';
                }

            }
        }

        /**
         * DROP FOREIGN KEY
         */
        if ($tableExists === true && ($dbAdapter === 'dbMysql' || $dbAdapter === 'dbPostgresql')) {
            $actualReferences = $connection->describeReferences($tableName, $schema);
            /* @var $actualReference \Phalcon\Db\Reference */
            foreach ($actualReferences as $actualReference) {
                $foreignKeyExists = false;

                for ($i = count($foreignKeys) - 1; $i >= 0; --$i) {
                    if ($dbAdapter === 'dbMysql') {
                        $rules = $connection->query('SELECT UPDATE_RULE, DELETE_RULE FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS WHERE CONSTRAINT_NAME="' . $actualReference->getName() . '" AND CONSTRAINT_SCHEMA ="' . $actualReference->getReferencedSchema() . '"');
                        $rules = $rules->fetch();

                        if ($tableName === $foreignKeys[$i]['table']
                            && $actualReference->getReferencedTable() === $foreignKeys[$i]['referencedTable']
                            && count(array_diff($actualReference->getColumns(), $foreignKeys[$i]['fields'])) === 0
                            && count(array_diff($actualReference->getReferencedColumns(), $foreignKeys[$i]['referencedFields'])) === 0
                            // TODO : réactiver cette ligne si Phalcon prend en compte la méthode : && $actualReference->getOnUpdate() === $foreignKeys[$i]['action']
                            && $rules['UPDATE_RULE'] === $foreignKeys[$i]['action']
                            // TODO : réactiver cette ligne si Phalcon prend en compte la méthode : && $actualReference->getOnDelete() === $foreignKeys[$i]['action']) {
                            && $rules['DELETE_RULE'] === $foreignKeys[$i]['action']
                        ) {
                            $foreignKeyExists = true;
                            array_splice($foreignKeys, $i, 1);
                            break;
                        }
                    } else {
                        if ($tableName === $foreignKeys[$i]['table']
                            && $actualReference->getReferencedTable() === $foreignKeys[$i]['referencedTable']
                            && count(array_diff($actualReference->getColumns(), $foreignKeys[$i]['fields'])) === 0
                            && count(array_diff($actualReference->getReferencedColumns(), $foreignKeys[$i]['referencedFields'])) === 0
                        ) {
                            $foreignKeyExists = true;
                            array_splice($foreignKeys, $i, 1);
                            break;
                        }
                    }
                }

                if (!$foreignKeyExists && !in_array($actualReference->getName(), $ignoreDropForeignKeys)) {
                    $rawSql = $connection->getDialect()->dropForeignKey(
                        $tableName,
                        $actualReference->getReferencedSchema(),
                        $actualReference->getName()
                    );
                    $sql[] = '$this->' . $dbAdapter . '->query(\'' . $rawSql . '\');';
                }
            }
        }

        /**
         * ADD FOREIGN KEY
         */
        if ($foreignKeys) {
            foreach ($foreignKeys as $foreignKey) {
                $rawSql = $connection->getDialect()->addForeignKey(
                    $tableName,
                    $connection->getDescriptor()['dbname'],
                    new Reference(
                        $foreignKey['name'],
                        array(
                            "referencedSchema" => $connection->getDescriptor()['dbname'],
                            "referencedTable" => $foreignKey['referencedTable'],
                            "columns" => $foreignKey['fields'],
                            "referencedColumns" => $foreignKey['referencedFields'],
                            'onUpdate' => $foreignKey['action'],
                            'onDelete' => $foreignKey['action']
                        )
                    ));
                $sql[] = '$this->' . $dbAdapter . '->query(\'' . $rawSql . '\');';
            }
        }

        /**
         * INDEXES
         */
        if (isset($definition['indexes'])) {
            if ($tableExists == true) {

                $indexes = array();
                foreach ($definition['indexes'] as $tableIndex) {
                    $indexes[$tableIndex->getName()] = $tableIndex;
                }

                if ($dbAdapter === 'dbPostgresql') {
                    $rawSql = $connection->getDialect()->modifyColumn($tableName, $tableColumn->getSchemaName(), $tableColumn, $localFields[$fieldName]);
                }

                $localIndexes = array();
                $actualIndexes = $connection->describeIndexes($tableName, $schema);
                foreach ($actualIndexes as $actualIndex) {
                    $deleted = true;

                    foreach ($definition['indexes'] as $tableIndex) {
                        // hack for encoging problem
                        $tableIndexName = $tableIndex->getName();
                        $actualIndexName = $actualIndex->getName();
                        if ($tableIndexName === $actualIndexName) {
                            $deleted = false;
                            $localIndexes[$actualIndex->getName()] = $actualIndex->getColumns();
                            break;
                        } elseif (substr($actualIndex->getName(), 0, 3) !== 'IDX' && ($dbAdapter !== 'dbCassandra') && ($dbAdapter !== 'dbPostgresql')) {
                            $deleted = false;
                            break;
                        }
                    }


                    if ($deleted) {
                        $rawSql = $connection->getDialect()->dropIndex($tableName, $tableColumn->getSchemaName(), $actualIndexName);
                        $sql[] = '$this->' . $dbAdapter . '->query(\'' . $rawSql . '\');';
                    }
                }

                foreach ($definition['indexes'] as $tableIndex) {
                    $tableIndexName = $tableIndex->getName();
                    if (!isset($localIndexes[$tableIndexName])) {
                        if ($tableIndexName == 'PRIMARY') {
                            $rawSql = $connection->getDialect()->addPrimaryKey($tableName, $tableColumn->getSchemaName(), $tableIndex);
                            $sql[] = '$this->' . $dbAdapter . '->query(\'' . $rawSql . '\');';
                        } else {
                            $rawSql = $connection->getDialect()->addIndex($tableName, $tableColumn->getSchemaName(), $tableIndex);
                            $sql[] = '$this->' . $dbAdapter . '->query(\'' . $rawSql . '\');';
                        }
                    } else {
                        $changed = false;
                        if (count($tableIndex->getColumns()) != count($localIndexes[$tableIndexName])) {
                            $changed = true;
                        } else {
                            foreach ($tableIndex->getColumns() as $columnName) {
                                if (!in_array($columnName, $localIndexes[$tableIndexName])) {
                                    $changed = true;
                                    break;
                                }
                            }
                        }
                        if ($changed == true) {
                            if ($tableIndex->getName() == 'PRIMARY') {
                                $rawSql = $connection->getDialect()->dropPrimaryKey($tableName, $tableColumn->getSchemaName());
                                $sql[] = '$this->' . $dbAdapter . '->query(\'' . $rawSql . '\');';

                                $rawSql = $connection->getDialect()->addPrimaryKey($tableName, $tableColumn->getSchemaName(), $tableIndex);
                                $sql[] = '$this->' . $dbAdapter . '->query(\'' . $rawSql . '\');';
                            }
                        }
                    }
                }
            }

        }

        return $sql;

    }
1322619
public static function dbConnect($connectionString) {
        ORM::configure(array(
            'connection_string' => $connectionString['driver'] . ':host=' . $connectionString['host'] . ';dbname=' . $connectionString['dbname'],
            'username' => $connectionString['username'],
            'password' => $connectionString['password'],
            'driver_options' => array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES ' . $connectionString['charset']),
            'logging' => get_config('debug', false)
        ));
    }
2807
public static function setDefaultDbo(AbstractDatabaseDriver $db = null)
    {
        self::$db = $db;

        if ($db) {
            $driver = $db->getName();

            self::$instances[$driver] = $db;
        }
    }
644127
public static function factory($adapterName, & $dbInfos, $connect = true)
    {
        if ($connect) {
            if ($dbInfos['port'][0] == '/') {
                $dbInfos['unix_socket'] = $dbInfos['port'];
                unset($dbInfos['host']);
                unset($dbInfos['port']);
            }

            // not used by Zend Framework
            unset($dbInfos['tables_prefix']);
            unset($dbInfos['adapter']);
            unset($dbInfos['schema']);
        }

        $className = self::getAdapterClassName($adapterName);

        // make sure not to pass any references otherwise they will modify $dbInfos
        $infos = array();
        foreach ($dbInfos as $key => $val) {
            $infos[$key] = $val;
        }

        $adapter   = new $className($infos);

        if ($connect) {
            $adapter->getConnection();

            Zend_Db_Table::setDefaultAdapter($adapter);
            // we don't want the connection information to appear in the logs
            $adapter->resetConfig();
        }

        return $adapter;
    }
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.");
    }
  }
169961
public function createDb($name, $dbType, $password, $dbUser = '')
    {
        $password = ($dbUser !== '') ? '' : $password;

        return $this->send('create_db', $name, $dbType, $password, $dbUser);
    }
668947
public static function getDatabaseConfig($dbConfig = null)
    {
        $config = Config::getInstance();

        if (is_null($dbConfig)) {
            $dbConfig = $config->database;
        }

        /**
         * Triggered before a database connection is established.
         *
         * This event can be used to change the settings used to establish a connection.
         *
         * @param array *$dbInfos Reference to an array containing database connection info,
         *                        including:
         *
         *                        - **host**: The host name or IP address to the MySQL database.
         *                        - **username**: The username to use when connecting to the
         *                                        database.
         *                        - **password**: The password to use when connecting to the
         *                                       database.
         *                        - **dbname**: The name of the Piwik MySQL database.
         *                        - **port**: The MySQL database port to use.
         *                        - **adapter**: either `'PDO\MYSQL'` or `'MYSQLI'`
         *                        - **type**: The MySQL engine to use, for instance 'InnoDB'
         */
        Piwik::postEvent('Db.getDatabaseConfig', array(&$dbConfig));

        $dbConfig['profiler'] = @$config->Debug['enable_sql_profiler'];

        return $dbConfig;
    }
1176307
void connectDBConn(DBConn dbConn) throws DBNotAvailableException, RuntimeException {
        // If we're using failover hosts, see if it's time to try primary hosts again.
        if (m_bUseSecondaryHosts &&
            (System.currentTimeMillis() - m_lastPrimaryHostCheckTimeMillis) > getParamInt("primary_host_recheck_millis", 60000)) {
            m_bUseSecondaryHosts = false;
        }
        
        // Try all primary hosts first if possible.
        DBNotAvailableException lastException = null;
        if (!m_bUseSecondaryHosts) {
            String[] dbHosts = getParamString("dbhost").split(",");
            for (int attempt = 1; !dbConn.isOpen() && attempt <= dbHosts.length; attempt++) {
                try {
                    dbConn.connect(chooseHost(dbHosts));
                } catch (DBNotAvailableException ex) {
                    lastException = ex;
                } catch (RuntimeException ex) {
                    throw ex;   // bad keyspace; abort connection attempts
                }
            }
            m_lastPrimaryHostCheckTimeMillis = System.currentTimeMillis();
        }
        
        // Try secondary hosts if needed and if configured.
        if (!dbConn.isOpen() && !Utils.isEmpty(getParamString("secondary_dbhost"))) {
            if (!m_bUseSecondaryHosts) {
                m_logger.info("All connections to 'dbhost' failed; trying 'secondary_dbhost'");
            }
            String[] dbHosts = getParamString("secondary_dbhost").split(",");
            for (int attempt = 1; !dbConn.isOpen() && attempt <= dbHosts.length; attempt++) {
                try {
                    dbConn.connect(chooseHost(dbHosts));
                } catch (DBNotAvailableException e) {
                    lastException = e;
                } catch (RuntimeException ex) {
                    throw ex;   // bad keyspace; abort connection attempts
                }
            }
            if (dbConn.isOpen()) {
                m_bUseSecondaryHosts = true; // stick with secondary hosts for now.
            }
        }
        
        if (!dbConn.isOpen()) {
            m_logger.error("All Thrift connection attempts failed.", lastException);
            throw lastException;
        }
    }
872712
private function connectAndCreate($server, $type, $username, $password, $database)
    {
        $conn = ADONewConnection($this->isPDO($type) ? 'pdo' : $type);
        $conn->SetFetchMode(ADODB_FETCH_BOTH);
        $conn = $this->setConnectTimeout($conn, $type);
        $connected = $conn->Connect($this->getDSN($server,$type,false),$username,$password,$database);
        $conn = $this->clearConnectTimeout($conn, $type);
        if ($connected) {
            $this->last_connect_error = false;
            $adapter = $this->getAdapter(strtolower($type));
            $stillok = $conn->Execute($adapter->createNamedDB($database));
            if (!$stillok) {
                $this->last_connect_error = $conn->ErrorMsg();
                $this->connections[$database] = false;
                return false;
            }
            $conn->Execute($adapter->useNamedDB($database));
            $conn->SelectDB($database);
            $this->connections[$database] = $conn;
            return true;
        } else {
            $this->last_connect_error = $conn->ErrorMsg();
            $this->connections[$database] = false;
            return false;
        }
    }
672398
public function connect() : void
    {
        $this->logger->info('Connecting to LDAP');
        // Connect to the LDAP server
        $handle = ldap_connect($this->configuration['server'], $this->configuration['port']);

        if (is_resource($handle)) {
            ldap_set_option($handle, LDAP_OPT_PROTOCOL_VERSION, 3);
            ldap_set_option($handle, LDAP_OPT_REFERRALS, 0);
            $this->logger->info('Connected to LDAP');
            $this->handle = $handle;
        } else {
            throw new DatabaseConnectionException('Unable to connect to LDAP');
        }
        $this->logger->debug('Connecting to database engine.');
        $this->bindToServer();
        $this->logger->debug('Connected to database engine.');
        $this->is_connected = true;
    }
403182
public function connect(\stdClass $params): QueryBuilderInterface
	{
		list($dsn, $dbtype, $params, $options) = $this->parseParams($params);

		$dbtype = ucfirst($dbtype);
		$driver = "\\Query\\Drivers\\{$dbtype}\\Driver";

		// Create the database connection
		$db =  ! empty($params->user)
			? new $driver($dsn, $params->user, $params->pass, $options)
			: new $driver($dsn, '', '', $options);

		// Set the table prefix, if it exists
		if (isset($params->prefix))
		{
			$db->setTablePrefix($params->prefix);
		}

		// Create Query Builder object
		$conn = new QueryBuilder($db, new QueryParser($db));


		// Save it for later
		if (isset($params->alias))
		{
			$this->connections[$params->alias] = $conn;
		}
		else
		{
			$this->connections[] = $conn;
		}

		return $conn;
	}
799233
function _connect($argDSN, $argUsername, $argPassword, $argDatabasename)
	{
		global $php_errormsg;

		if (!function_exists('db2_connect')) {
			ADOConnection::outp("Warning: The old ODBC based DB2 driver has been renamed 'odbc_db2'. This ADOdb driver calls PHP's native db2 extension which is not installed.");
			return null;
		}
		// This needs to be set before the connect().
		// Replaces the odbc_binmode() call that was in Execute()
		ini_set('ibm_db2.binmode', $this->binmode);

		if ($argDatabasename && empty($argDSN)) {

			if (stripos($argDatabasename,'UID=') && stripos($argDatabasename,'PWD=')) $this->_connectionID = db2_connect($argDatabasename,null,null);
			else $this->_connectionID = db2_connect($argDatabasename,$argUsername,$argPassword);
		} else {
			if ($argDatabasename) $schema = $argDatabasename;
			if (stripos($argDSN,'UID=') && stripos($argDSN,'PWD=')) $this->_connectionID = db2_connect($argDSN,null,null);
			else $this->_connectionID = db2_connect($argDSN,$argUsername,$argPassword);
		}
		if (isset($php_errormsg)) $php_errormsg = '';

		// For db2_connect(), there is an optional 4th arg.  If present, it must be
		// an array of valid options.  So far, we don't use them.

		$this->_errorMsg = @db2_conn_errormsg();
		if (isset($this->connectStmt)) $this->Execute($this->connectStmt);

		if ($this->_connectionID && isset($schema)) $this->Execute("SET SCHEMA=$schema");
		return $this->_connectionID != false;
	}
1153618
public function connect($sDbHost = '', $sDbUser = '', $sDbPass = '', $sDbName = '')
    {
        //  Close the connection if one is open
        if (!is_null($this->oDb)) {
            $this->oDb = null;
        }

        $sDbHost = !empty($sDbHost) ? $sDbHost : (defined('DEPLOY_DB_HOST') ? DEPLOY_DB_HOST : '');
        $sDbUser = !empty($sDbUser) ? $sDbUser : (defined('DEPLOY_DB_USERNAME') ? DEPLOY_DB_USERNAME : '');
        $sDbPass = !empty($sDbPass) ? $sDbPass : (defined('DEPLOY_DB_PASSWORD') ? DEPLOY_DB_PASSWORD : '');
        $sDbName = !empty($sDbName) ? $sDbName : (defined('DEPLOY_DB_DATABASE') ? DEPLOY_DB_DATABASE : '');

        try {

            $this->oDb = new \PDO(
                'mysql:host=' . $sDbHost . ';dbname=' . $sDbName . ';charset=utf8', $sDbUser, $sDbPass
            );

            $this->oDb->exec('set names utf8');
            $this->oDb->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);

        } catch (\Exception $e) {
            throw new ConnectionException(
                sprintf(self::ERR_MSG_CONNECTION_FAILED, $e->getCode(), $e->getMessage()),
                self::ERR_NUM_CONNECTION_FAILED
            );
        }
    }
648160
protected function buildDatabase(): DatabaseAdapter {
		$dbName = $this->determineDbName();
		$database = new PgsqlDatabase($dbName, $this->determineDbCharset($dbName), 
				$this->getPersistedMetaEntities($dbName), $this->determineDbAttrs($dbName));
		
		foreach ($database->getMetaEntities() as $metaEntity) {
			if (!$metaEntity instanceof Table) continue;
			
			$this->metaEntityBuilder->applyIndexesForTable($dbName, $metaEntity);
		}
		
		return $database;
	}