Connect to external database.

@return ADOConnection
@throws moodle_exception
358831
function db_init() {
        if ($this->is_configured() === false) {
            throw new moodle_exception('auth_dbcantconnect', 'auth_db');
        }

        // Connect to the external database (forcing new connection).
        $authdb = ADONewConnection($this->config->type);
        if (!empty($this->config->debugauthdb)) {
            $authdb->debug = true;
            ob_start(); //Start output buffer to allow later use of the page headers.
        }
        $authdb->Connect($this->config->host, $this->config->user, $this->config->pass, $this->config->name, true);
        $authdb->SetFetchMode(ADODB_FETCH_ASSOC);
        if (!empty($this->config->setupsql)) {
            $authdb->Execute($this->config->setupsql);
        }

        return $authdb;
    }
592563
public function connect()
    {
        parent::connect();

        $this->connection->setAttribute(\PDO::ATTR_EMULATE_PREPARES, true);

        return $this;
    }
793292
protected function db_init() {
        global $CFG;

        require_once($CFG->libdir.'/adodb/adodb.inc.php');

        // Connect to the external database (forcing new connection).
        $extdb = ADONewConnection($this->get_config('dbtype'));
        if ($this->get_config('debugdb')) {
            $extdb->debug = true;
            ob_start(); // Start output buffer to allow later use of the page headers.
        }

        // The dbtype my contain the new connection URL, so make sure we are not connected yet.
        if (!$extdb->IsConnected()) {
            $result = $extdb->Connect($this->get_config('dbhost'), $this->get_config('dbuser'), $this->get_config('dbpass'), $this->get_config('dbname'), true);
            if (!$result) {
                return null;
            }
        }

        $extdb->SetFetchMode(ADODB_FETCH_ASSOC);
        if ($this->get_config('dbsetupsql')) {
            $extdb->Execute($this->get_config('dbsetupsql'));
        }
        return $extdb;
    }
1200074
public function connect()
  {
    try {
      $this->cnx = new SQLitePDO($this->fileName);
      $this->cnx->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
      return true;
    } catch (\Exception $e) {
      return false;
    }
  }
259890
public function connect(): self
    {
        $this->logger->debug('connect to ldap server ['.$this->uri.']', [
            'category' => get_class($this),
        ]);

        if (null === $this->binddn) {
            $this->logger->warning('no binddn set for ldap connection, you should avoid anonymous bind', [
                'category' => get_class($this),
            ]);
        }

        if (false === $this->tls && 'ldaps' !== substr($this->uri, 0, 5)) {
            $this->logger->warning('neither tls nor ldaps enabled for ldap connection, it is strongly reccommended to encrypt ldap connections', [
                'category' => get_class($this),
            ]);
        }

        $this->connection = ldap_connect($this->uri);

        foreach ($this->options as $opt => $value) {
            ldap_set_option($this->connection, constant($opt), $value);
        }

        if (true === $this->tls) {
            ldap_start_tls($this->connection);
        }

        if ($this->connection) {
            if (null !== $this->binddn) {
                $bind = ldap_bind($this->connection, $this->binddn, $this->bindpw);

                if ($bind) {
                    $this->logger->info('bind to ldap server ['.$this->uri.'] with binddn ['.$this->binddn.'] was succesful', [
                        'category' => get_class($this),
                    ]);

                    return $this;
                }

                throw new Exception('failed bind to ldap server, error: '.ldap_error($this->connection));
            }
        } else {
            throw new Exception('failed connect to ldap server '.$this->uri);
        }

        return $this;
    }
1048822
public function connect()
    {
        try {
            $this->_connection = new PDO(
                $this->_type .":host=". $this->_host .";dbname=". $this->_database .";port=". $this->_port,
                $this->_username,
                $this->_password
            );
        } catch(PDOException $e) {
            $code    = $e->getCode();
            $message = $e->getMessage();

            throw new ConnectionFailed($code, $message);
        }
    }
734709
public static function connect()
    {   
        self::getEnv();
        return new PDO(self::$driver.':host='.self::$host.';dbname='.self::$dbname, self::$user, self::$pass);
    }
568719
public function _connect()
    {
        if ( !function_exists( 'oci_connect' ) )
            throw new eZClusterHandlerDBNoDatabaseException( "PECL oci8 extension (http://pecl.php.net/package/oci8) is required to use Oracle clustering functionality." );

        // 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 )
        {
            $siteINI = eZINI::instance( 'site.ini' );
            $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" );

            self::$dbparams['persistent_connection'] = $fileINI->hasVariable( 'eZDFSClusteringSettings', 'DBPersistentConnection' ) ? ( $fileINI->variable( 'eZDFSClusteringSettings', 'DBPersistentConnection' ) == 'enabled' ) : false;
        }

        $maxTries = self::$dbparams['max_connect_tries'];
        $tries = 0;
        eZPerfLogger::accumulatorStart( 'oracle_cluster_connect', 'Oracle Cluster', 'Cluster database connection' );
        while ( $tries < $maxTries )
        {
            if ( self::$dbparams['persistent_connection'] )
            {
                if ( $this->db = oci_pconnect( self::$dbparams['user'], self::$dbparams['pass'], self::$dbparams['dbname'] ) )
                    break;
            }
            else
            {
                if ( $this->db = oci_connect( self::$dbparams['user'], self::$dbparams['pass'], self::$dbparams['dbname'] ) )
                    break;
            }
            ++$tries;
        }
        eZPerfLogger::accumulatorStop( 'oracle_cluster_connect' );
        if ( !$this->db )
            throw new eZClusterHandlerDBNoConnectionException( self::$dbparams['dbname'], self::$dbparams['user'], self::$dbparams['pass'] );

        // DFS setup
        if ( $this->dfsbackend === null )
        {
            $this->dfsbackend = new eZDFSFileHandlerTracing50DFSBackend();
        }
    }
1011185
public function connect() {
        $adapter = Zend_Db_Table::getDefaultAdapter();
        if (!$adapter) {
            Garp_Cli::errorOut('No database adapter found');
            return false;
        }
        $config = $adapter->getConfig();
        $params = array(
            '-u' . escapeshellarg($config['username']),
            '-p' . escapeshellarg($config['password']),
            '-h' . escapeshellarg($config['host']),
            ' ' . escapeshellarg($config['dbname'])
        );
        $cmd = 'mysql ' . implode(' ', $params);
        $process = proc_open($cmd, array(0 => STDIN, 1 => STDOUT, 2 => STDERR), $pipes);
        $proc_status = proc_get_status($process);
        $exit_code = proc_close($process);
        return ($proc_status["running"] ? $exit_code : $proc_status["exitcode"] ) == 0;
    }
307554
public function connect()
    {
        $config = $this->getConfig();
        if(isset($config['database']['database'])) {
            $conn = $this->instanceConnector();
            $host = $config['database']['hostname'];
            $user = $config['database']['username'];
            $pass = $config['database']['password'];
            if ($conn->connect($host, $user, $pass)) {
                $this->connection = $conn;
                $this->createCache();
                return true;
            }
            $err = $conn->getLastError();
            throw new \Exception(sprintf('Can not establish connection to database! {host=%s, user=%s, database=%s} Error: %s',
                        $config['database']['hostname'], $config['database']['username'], $config['database']['database'], $err));
        }

        return false;

//        if (!$this->connection) {
//
//            if ($conn->connect()
//            ) {
//                if ($conn->select_database($config['database']['database'])) {
//                    $this->connection = $conn;
//                    self::$selected = true;
//                    $this->createCache();
////
////                    if (!defined("GL_INSTALL") || !GL_INSTALL) {
////                        $this->checkDatabaseStructure();
////                    }
//                    return true;
//                }
//                return false;
//            } else {
//                $err =$conn->getLastError();
//                throw new \Exception(sprintf('Can not establish connection to database! {host=%s, user=%s, database=%s} Error: %s',
//                    $config['database']['hostname'], $config['database']['username'], $config['database']['database'], $err));
//            }
//        }
//        return true;
    }
1180652
protected function _connect()
    {
        /**
         * if we already have a PDO object, no need to re-connect.
         */
        if ($this->_connection) {
            return;
        }

        parent::_connect();

        $retval = $this->_connection->exec('PRAGMA full_column_names=0');
        if ($retval === false) {
            $error = $this->_connection->errorInfo();
            /** @see Zend_Db_Adapter_Exception */
            // require_once 'Zend/Db/Adapter/Exception.php';
            throw new Zend_Db_Adapter_Exception($error[2]);
        }

        $retval = $this->_connection->exec('PRAGMA short_column_names=1');
        if ($retval === false) {
            $error = $this->_connection->errorInfo();
            /** @see Zend_Db_Adapter_Exception */
            // require_once 'Zend/Db/Adapter/Exception.php';
            throw new Zend_Db_Adapter_Exception($error[2]);
        }
    }
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;
    }
1013428
public function connect() {
    // Check that the SQLite3 extension is installed.
    if (!class_exists('SQLite3')) {
      throw new Exceptions\UnableToConnectException(
          'SQLite3 PHP extension is not available. It probably has not '.
          'been installed. Please install and configure it in order to use '.
          'SQLite3.'
      );
    }
    $filename = $this->config['SQLite3']['filename'];
    $busyTimeout = $this->config['SQLite3']['busy_timeout'];
    $openFlags = $this->config['SQLite3']['open_flags'];
    $encryptionKey = $this->config['SQLite3']['encryption_key'];
    // Connecting
    if (!$this->connected) {
      $this->link = new SQLite3($filename, $openFlags, $encryptionKey);
      if ($this->link) {
        $this->connected = true;
        $this->link->busyTimeout($busyTimeout);
        // Set database and connection options.
        $this->link->exec("PRAGMA encoding = \"UTF-8\";");
        $this->link->exec("PRAGMA foreign_keys = 1;");
        $this->link->exec("PRAGMA case_sensitive_like = 1;");
        // Create the preg_match and regexp functions.
        // TODO(hperrin): Add more of these functions to get rid of post-query checks.
        $this->link->createFunction('preg_match', 'preg_match', 2, SQLITE3_DETERMINISTIC);
        $this->link->createFunction('regexp', function ($pattern, $subject) {
          return !!$this->posixRegexMatch($pattern, $subject);
        }, 2, SQLITE3_DETERMINISTIC);
      } else {
        $this->connected = false;
        if ($filename === ':memory:') {
          throw new Exceptions\NotConfiguredException();
        } else {
          throw new Exceptions\UnableToConnectException('Could not connect.');
        }
      }
    }
    return $this->connected;
  }
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;
    }
57805
public function connect() {
        if (!$this->pdo) {
            try {
                $this->pdo = new PDO($this->dsn, $this->username, $this->password, $this->params);
            } catch (\PDOException $e) {
                throw $e;
            }
        }
        return $this->pdo;
    }
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();
    }
1033200
public function connect(): DriverInterface
    {
        try {
            $connection = new PDO(
                $this->getDsn(),
                $this->getParam('username'),
                $this->getParam('password')
            );

            // We allow to print the errors whenever there is one
            $connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

            $this->setInstance($connection);

        } catch (SQLException $e) {
            // __construct
        }

        return $this;
    }