Connects to the database if needed.

@return  void  Returns void if the database connected successfully.

@since   1.0
@throws  \RuntimeException
510295
public function connect()
	{
		if ($this->connection)
		{
			return;
		}

		// Make sure the PDO extension for PHP is installed and enabled.
		if (!static::isSupported())
		{
			throw new UnsupportedAdapterException('PDO Extension is not available.', 1);
		}

		// Find the correct PDO DSN Format to use:
		switch ($this->options['driver'])
		{
			case 'cubrid':
				$this->options['port'] = isset($this->options['port']) ? $this->options['port'] : 33000;

				$format = 'cubrid:host=#HOST#;port=#PORT#;dbname=#DBNAME#';

				$replace = array('#HOST#', '#PORT#', '#DBNAME#');
				$with    = array($this->options['host'], $this->options['port'], $this->options['database']);

				break;

			case 'dblib':
				$this->options['port'] = isset($this->options['port']) ? $this->options['port'] : 1433;

				$format = 'dblib:host=#HOST#;port=#PORT#;dbname=#DBNAME#';

				$replace = array('#HOST#', '#PORT#', '#DBNAME#');
				$with    = array($this->options['host'], $this->options['port'], $this->options['database']);

				break;

			case 'firebird':
				$this->options['port'] = isset($this->options['port']) ? $this->options['port'] : 3050;

				$format = 'firebird:dbname=#DBNAME#';

				$replace = array('#DBNAME#');
				$with    = array($this->options['database']);

				break;

			case 'ibm':
				$this->options['port'] = isset($this->options['port']) ? $this->options['port'] : 56789;

				if (!empty($this->options['dsn']))
				{
					$format = 'ibm:DSN=#DSN#';

					$replace = array('#DSN#');
					$with    = array($this->options['dsn']);
				}
				else
				{
					$format = 'ibm:hostname=#HOST#;port=#PORT#;database=#DBNAME#';

					$replace = array('#HOST#', '#PORT#', '#DBNAME#');
					$with    = array($this->options['host'], $this->options['port'], $this->options['database']);
				}

				break;

			case 'informix':
				$this->options['port']     = isset($this->options['port']) ? $this->options['port'] : 1526;
				$this->options['protocol'] = isset($this->options['protocol']) ? $this->options['protocol'] : 'onsoctcp';

				if (!empty($this->options['dsn']))
				{
					$format = 'informix:DSN=#DSN#';

					$replace = array('#DSN#');
					$with    = array($this->options['dsn']);
				}
				else
				{
					$format = 'informix:host=#HOST#;service=#PORT#;database=#DBNAME#;server=#SERVER#;protocol=#PROTOCOL#';

					$replace = array('#HOST#', '#PORT#', '#DBNAME#', '#SERVER#', '#PROTOCOL#');
					$with    = array(
						$this->options['host'],
						$this->options['port'],
						$this->options['database'],
						$this->options['server'],
						$this->options['protocol'],
					);
				}

				break;

			case 'mssql':
				$this->options['port'] = isset($this->options['port']) ? $this->options['port'] : 1433;

				$format = 'mssql:host=#HOST#;port=#PORT#;dbname=#DBNAME#';

				$replace = array('#HOST#', '#PORT#', '#DBNAME#');
				$with    = array($this->options['host'], $this->options['port'], $this->options['database']);

				break;

			case 'mysql':
				$this->options['port'] = isset($this->options['port']) ? $this->options['port'] : 3306;

				$format = 'mysql:host=#HOST#;port=#PORT#;dbname=#DBNAME#;charset=#CHARSET#';

				$replace = array('#HOST#', '#PORT#', '#DBNAME#', '#CHARSET#');
				$with    = array($this->options['host'], $this->options['port'], $this->options['database'], $this->options['charset']);

				break;

			case 'oci':
				$this->options['port']    = isset($this->options['port']) ? $this->options['port'] : 1521;
				$this->options['charset'] = isset($this->options['charset']) ? $this->options['charset'] : 'AL32UTF8';

				if (!empty($this->options['dsn']))
				{
					$format = 'oci:dbname=#DSN#';

					$replace = array('#DSN#');
					$with    = array($this->options['dsn']);
				}
				else
				{
					$format = 'oci:dbname=//#HOST#:#PORT#/#DBNAME#';

					$replace = array('#HOST#', '#PORT#', '#DBNAME#');
					$with    = array($this->options['host'], $this->options['port'], $this->options['database']);
				}

				$format .= ';charset=' . $this->options['charset'];

				break;

			case 'odbc':
				$format = 'odbc:DSN=#DSN#;UID:#USER#;PWD=#PASSWORD#';

				$replace = array('#DSN#', '#USER#', '#PASSWORD#');
				$with    = array($this->options['dsn'], $this->options['user'], $this->options['password']);

				break;

			case 'pgsql':
				$this->options['port'] = isset($this->options['port']) ? $this->options['port'] : 5432;

				$format = 'pgsql:host=#HOST#;port=#PORT#;dbname=#DBNAME#';

				$replace = array('#HOST#', '#PORT#', '#DBNAME#');
				$with    = array($this->options['host'], $this->options['port'], $this->options['database']);

				break;

			case 'sqlite':
				if (isset($this->options['version']) && $this->options['version'] == 2)
				{
					$format = 'sqlite2:#DBNAME#';
				}
				else
				{
					$format = 'sqlite:#DBNAME#';
				}

				$replace = array('#DBNAME#');
				$with    = array($this->options['database']);

				break;

			case 'sybase':
				$this->options['port'] = isset($this->options['port']) ? $this->options['port'] : 1433;

				$format = 'mssql:host=#HOST#;port=#PORT#;dbname=#DBNAME#';

				$replace = array('#HOST#', '#PORT#', '#DBNAME#');
				$with    = array($this->options['host'], $this->options['port'], $this->options['database']);

				break;

			default:
				throw new UnsupportedAdapterException('The ' . $this->options['driver'] . ' driver is not supported.');
		}

		// Create the connection string:
		$connectionString = str_replace($replace, $with, $format);

		try
		{
			$this->connection = new \PDO(
				$connectionString,
				$this->options['user'],
				$this->options['password'],
				$this->options['driverOptions']
			);
		}
		catch (\PDOException $e)
		{
			$message = 'Could not connect to PDO: ' . $e->getMessage();

			$this->log(Log\LogLevel::ERROR, $message);

			throw new ConnectionFailureException($message, $e->getCode(), $e);
		}
	}
1218427
public function start()
    {
        if (!session_id() || !$this->isActive()) {
            $file = $line = null;
            if (headers_sent($file, $line)) {
                throw new \RuntimeException(sprintf('Unable to start session, output started at %s:%s', $file, $line));
            }
            session_start();
        }

        if ($this->namespace) {
            if (!isset($_SESSION[$this->namespace])) {
                $_SESSION[$this->namespace] = array();
            }
            $this->data = &$_SESSION[$this->namespace];
        } else {
            $this->data = &$_SESSION;
        }
    }
600040
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'];

        // prepare connection string
        $connectionString = sprintf("host=%s dbname=%s", $host, $name);
        if ($port)     $connectionString .= " port={$port}";
        if ($username) $connectionString .= " user={$username}";
        if ($password) $connectionString .= " password='". addcslashes($password, "'\\") ."'";
        $options = $this->config['options'] ?? [];
        if (null !== ($opt = Util::arrayPick($options, 'connect_timeout'))) {
            $connectionString .= " connect_timeout={$opt}";
        }
        if ($opt = Util::arrayPick($options, 'sslmode')) {
            $connectionString .= " sslmode={$opt}";
        }
        if ($opt = Util::arrayPick($options, 'service')) {
            $connectionString .= " service={$opt}";
        }
        if ($opt = $this->config['timezone']) $connectionStringOptions[] = "--timezone=\'{$opt}\'";
        if ($opt = $this->config['charset'])  $connectionStringOptions[] = "--client_encoding=\'{$opt}\'";
        if (isset($connectionStringOptions)) {
            $connectionString .= " options='". join(' ', $connectionStringOptions) ."'";
        }

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

        $resource =@ pg_connect($connectionString);
        $resourceStatus = pg_connection_status($resource);
        if ($resourceStatus === false || $resourceStatus === PGSQL_CONNECTION_BAD) {
            $resource =@ pg_connect($connectionString, PGSQL_CONNECT_FORCE_NEW); // re-try
            $resourceStatus = pg_connection_status($resource);
        }

        if (!$resource || $resourceStatus !== PGSQL_CONNECTION_OK) {
            $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()));

        // 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, character_maximum_length FROM information_schema.columns WHERE table_schema = 'public'", null, -1, 1);
                    if ($result->count()) {
                        $map = [];
                        foreach ($result->items() as $item) {
                            $length = null;
                            if ($item->data_type == 'bit') { // for only bools
                                $length = (int) $item->character_maximum_length;
                            } elseif (substr($item->data_type, 0, 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,
                                /* nullable */ ($item->is_nullable == 'YES')
                            ];
                        }

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

            // set map
            $this->mapper->setMap($map);
        }
    }
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]);
        }
    }
28892
public function run()
	{
		// Login to the db
		$this->printTaskInfo('Connecting to db server - <info>mysql://'.$this->user.':'.$this->pass.'@'.$this->host.'</info>');
		$db = new mysqli($this->host, $this->user, $this->pass);
		if ($db->connect_errno)
		{
			throw new RuntimeException
			(
				'Failed to connect to MySQL: ('.$db->connect_errno.') '.
				$db->connect_error
			);
		}

		// Create the db
		$query = 'CREATE DATABASE IF NOT EXISTS `'.$this->name.'`';
		$this->printTaskInfo('Running query - <info>'.$query.'</info>');
		if (!$db->query($query))
		{
			throw new RuntimeException
			(
				'Failed to create database: ('.$db->errorno.') '.
				$db->error
			);
		}

		// Do we want to drop all the tables as well
		if ($this->dropTables)
		{
			$this->printTaskInfo('Cleaning database of all data!');

			// Select db
			if (!$db->select_db($this->name))
			{
				throw new RuntimeException
				(
					'Failed to select database: ('.$db->errorno.') '.
					$db->error
				);
			}

			// Make sure we don't get foreign key errors
			$query = 'SET foreign_key_checks = 0';
			$this->printTaskInfo('Running query - <info>'.$query.'</info>');
			if (!$db->query($query))
			{
				throw new RuntimeException
				(
					'Query failed - '.$query.': ('.$db->errorno.') '.
					$db->error
				);
			}

			// Drop all our local data
			if ($result = $db->query("SHOW TABLES"))
			{
				while($row = $result->fetch_array(MYSQLI_NUM))
				{
					$query = 'DROP TABLE IF EXISTS '.$row[0];
					$this->printTaskInfo('Running query - <info>'.$query.'</info>');
					if (!$db->query($query))
					{
						throw new RuntimeException
						(
							'Failed to drop table - '.$row[0].': ('.$db->errorno.') '.
							$db->error
						);
					}
				}
			}

			// Put the foreign key checks back on
			$query = 'SET foreign_key_checks = 1';
			$this->printTaskInfo('Running query - <info>'.$query.'</info>');
			if(!$db->query($query))
			{
				throw new RuntimeException
				(
					'Query failed - '.$query.': ('.$db->errorno.') '.
					$db->error
				);
			}

			// Close connection to db
			$db->close();
		}

		// If we get to here assume everything worked
		return Result::success($this);
	}
1280080
public function connect() {
		//check if connection is already opened
		if ($this->connection instanceof \mysqli)
			return $this->connection;
		
		//get connection values
		$database = $this->config['database'];
		$host     = array_key_exists('host', $this->config) ? $this->config['host'] : ini_get("mysqli.default_host");
		$user     = array_key_exists('user', $this->config) ? $this->config['user'] : ini_get("mysqli.default_user");
		$password = array_key_exists('password', $this->config) ? $this->config['password'] : ini_get("mysqli.default_pw");
		$port     = array_key_exists('port', $this->config) ? $this->config['port'] : ini_get("mysqli.default_port");
		$socket   = array_key_exists('socket', $this->config) ? $this->config['socket'] : ini_get("mysqli.default_socket");
		
		//open connection
		$mysqli = @mysqli_connect($host, $user, $password, $database, $port, $socket);
		
		if (!($mysqli instanceof \mysqli))
			throw new MySQLConnectionException(mysqli_connect_error() . '(' . mysqli_connect_errno() . ')');
		
		//set autocommit
		$mysqli->autocommit($this->config['autocommit']);
		
		//set charset
		if (array_key_exists('charset', $this->config))
			$mysqli->set_charset($this->config['charset']);
		
		//store open connection
		return $this->connection = $mysqli;
	}
992718
public function execute()
	{
		$this->connect();

		if (!is_resource($this->connection))
		{
			$this->log(
				Log\LogLevel::ERROR,
				'Database query failed (error #{code}): {message}',
				array('code' => $this->errorNum, 'message' => $this->errorMsg)
			);
			throw new \RuntimeException($this->errorMsg, $this->errorNum);
		}

		// Take a local copy so that we don't modify the original query and cause issues later
		$sql = $this->replacePrefix((string) $this->sql);

		if ($this->limit > 0 || $this->offset > 0)
		{
			$sql = $this->limit($sql, $this->limit, $this->offset);
		}

		// Increment the query counter.
		$this->count++;

		// If debugging is enabled then let's log the query.
		if ($this->debug)
		{
			// Add the query to the object queue.
			$this->log(
				Log\LogLevel::DEBUG,
				'{sql}',
				array('sql' => $sql, 'category' => 'databasequery', 'trace' => debug_backtrace())
			);
		}

		// Reset the error values.
		$this->errorNum = 0;
		$this->errorMsg = '';

		// SQLSrv_num_rows requires a static or keyset cursor.
		if (strncmp(ltrim(strtoupper($sql)), 'SELECT', strlen('SELECT')) == 0)
		{
			$array = array('Scrollable' => SQLSRV_CURSOR_KEYSET);
		}
		else
		{
			$array = array();
		}

		// Execute the query. Error suppression is used here to prevent warnings/notices that the connection has been lost.
		$this->cursor = @sqlsrv_query($this->connection, $sql, array(), $array);

		// If an error occurred handle it.
		if (!$this->cursor)
		{
			// Check if the server was disconnected.
			if (!$this->connected())
			{
				try
				{
					// Attempt to reconnect.
					$this->connection = null;
					$this->connect();
				}
				catch (\RuntimeException $e)
				// If connect fails, ignore that exception and throw the normal exception.
				{
					// Get the error number and message.
					$errors = sqlsrv_errors();
					$this->errorNum = $errors[0]['SQLSTATE'];
					$this->errorMsg = $errors[0]['message'] . 'SQL=' . $sql;

					// Throw the normal query exception.
					$this->log(
						Log\LogLevel::ERROR,
						'Database query failed (error #{code}): {message}',
						array('code' => $this->errorNum, 'message' => $this->errorMsg)
					);
					throw new \RuntimeException($this->errorMsg, $this->errorNum);
				}

				// Since we were able to reconnect, run the query again.
				return $this->execute();
			}
			else
			// The server was not disconnected.
			{
				// Get the error number and message.
				$errors = sqlsrv_errors();
				$this->errorNum = $errors[0]['SQLSTATE'];
				$this->errorMsg = $errors[0]['message'] . 'SQL=' . $sql;

				// Throw the normal query exception.
				$this->log(
					Log\LogLevel::ERROR,
					'Database query failed (error #{code}): {message}',
					array('code' => $this->errorNum, 'message' => $this->errorMsg)
				);
				throw new \RuntimeException($this->errorMsg, $this->errorNum);
			}
		}

		return $this->cursor;
	}
43534
public function connect()
	{
		if ($this->_connection)
		{
			return;
		}

		// Extract the connection parameters, adding required variabels
		extract($this->_config['connection'] + array(
			'dsn'        => '',
			'username'   => null,
			'password'   => null,
			'persistent' => false,
			'compress'   => false,
		));

		// determine db type
		$_dsn_find_collon = strpos($dsn, ':');
		$this->_db_type = $_dsn_find_collon ? substr($dsn, 0, $_dsn_find_collon) : null;

		// Force PDO to use exceptions for all errors
		$attrs = array(\PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION);

		if ( ! empty($persistent))
		{
			// Make the connection persistent
			$attrs[\PDO::ATTR_PERSISTENT] = true;
		}

		if (in_array(strtolower($this->_db_type), array('mysql', 'mysqli')) and $compress)
		{
			// Use client compression with mysql or mysqli (doesn't work with mysqlnd)
			$attrs[\PDO::MYSQL_ATTR_COMPRESS] = true;
		}

		// add the charset to the DSN if needed
		if ( ! empty($this->_config['charset']) and strpos($dsn, ';charset=') === false and strtolower($this->_db_type) != 'sqlite')
		{
			$dsn .= ';charset='.$this->_config['charset'];
		}

		try
		{
			// Create a new PDO connection
			$this->_connection = new \PDO($dsn, $username, $password, $attrs);
		}
		catch (\PDOException $e)
		{
			// and convert the exception in a database exception
			if ( ! is_numeric($error_code = $e->getCode()))
			{
				if ($this->_connection)
				{
					$error_code = $this->_connection->errorinfo();
					$error_code = $error_code[1];
				}
				else
				{
					$error_code = 0;
				}
			}
			throw new \Database_Exception(str_replace($password, str_repeat('*', 10), $e->getMessage()), $error_code, $e);
		}

		if ( ! empty($this->_config['charset']))
		{
			// Set the character set
			$this->set_charset($this->_config['charset']);
		}
	}
1258683
public function connect()
    {
        $arrParams = [
            'mysql:host='.$this->host,
            'dbname='.$this->database,
            'charset='.$this->charset,
        ];
        
        $this->db = PdoSingleton::getInstance()->getConnection($arrParams, $this->username, $this->password);
    }
1019416
public function connect()
	{
		if ($this->ssl)
		{
			$this->connection = ftp_ssl_connect($this->getHost(), $this->getPort(), $this->getTimeout());
		}
		else
		{
			$this->connection = ftp_connect($this->getHost(), $this->getPort(), $this->getTimeout());
		}

		if (!$this->connection)
		{
			throw new RuntimeException(sprintf('Could not connect to host: %s, port: %s', $this->getHost(), $this->getPort()));
		}

		$this->login();
		$this->setConnectionPassiveMode();
		$this->setConnectionRoot();
	}
794932
public function connect()
	{
		//check if there is a valid service instance
		if ( ! $this->validService()) 
		{

			//put this in try...catch block for better error handling
			try{
				
				//make a connection attempt
				$this->service = new \MySQLi($this->host,$this->username,$this->password,$this->database,$this->port);

				//check is the connection attempt returned an error
				if ($this->service->connect_error) 
				{
					//throw exception
					throw new MySQLException("Unable to connect to Database service with the provided settings");

				}

				//set the connection variable to true
				$this->connected = true;

			}

			//diplay error message
			catch(MySQLException $MySQLExceptionObject){

				//display error message
				$MySQLExceptionObject->errorShow();

			}
			
		}

		//return this connection instance
		return $this;

	}
1071129
public function select($database)
	{
		$this->connect();

		if (!$database)
		{
			return false;
		}

		if (!mysqli_select_db($this->connection, $database))
		{
			throw new \RuntimeException('Could not connect to database.');
		}

		return true;
	}
665372
private function connect()
    {
        $headers = [];
        if ($this->lastId) {
            $headers['Last-Event-ID'] = $this->lastId;
        }

        $this->response = $this->client->request('GET', $this->url, [
            'stream' => true,
            'headers' => $headers,
        ]);

        if ($this->response->getStatusCode() == 204) {
            throw new RuntimeException('Server forbid connection retry by responding 204 status code.');
        }
    }
793249
public function connect()
    {
        if (!is_null($this->connection)) {
            return $this->connection;
        }

        $this->connection = $this->socket->open();

        $this->select($this->database);

        return $this->connection;
    }
1028565
public function connect() {
        if (!class_exists('SQLite3')) throw new RuntimeException('Undefined class \SQLite3, sqlite3 extension is not available');

        try {                                                                   // available flags:
            $flags  = SQLITE3_OPEN_READWRITE;                                   // SQLITE3_OPEN_CREATE
            $sqlite = new \SQLite3($this->file, $flags);                        // SQLITE3_OPEN_READONLY
        }                                                                       // SQLITE3_OPEN_READWRITE
        catch (\Exception $ex) {
            if (!$ex instanceof IRosasurferException)
                $ex = new DatabaseException($ex->getMessage(), $ex->getCode(), $ex);
            $file = $this->file;
            $what = $where = null;
            if (file_exists($file)) {
                $what = 'open';
                if (is_dir($file=realpath($file)))
                    $where = ' (directory)';
            }
            else {
                $what = ($flags & SQLITE3_OPEN_CREATE) ? 'create':'find';
                isRelativePath($file) && $where=' in "'.getcwd().'"';
            }
            throw $ex->addMessage('Cannot '.$what.' database file "'.$file.'"'.$where);
        }

        $this->sqlite = $sqlite;
        $this->setConnectionOptions();
        return $this;
    }
867946
public function connect()
	{
		if ($this->connection)
		{
			return;
		}

		// Build the connection configuration array.
		$config = array(
			'Database' => $this->options['database'],
			'uid' => $this->options['user'],
			'pwd' => $this->options['password'],
			'CharacterSet' => 'UTF-8',
			'ReturnDatesAsStrings' => true);

		// Make sure the SQLSRV extension for PHP is installed and enabled.
		if (!static::isSupported())
		{
			throw new \RuntimeException('PHP extension sqlsrv_connect is not available.');
		}

		// Attempt to connect to the server.
		if (!($this->connection = @ sqlsrv_connect($this->options['host'], $config)))
		{
			throw new \RuntimeException('Database sqlsrv_connect failed');
		}

		// Make sure that DB warnings are not returned as errors.
		sqlsrv_configure('WarningsReturnAsErrors', 0);

		// If auto-select is enabled select the given database.
		if ($this->options['select'] && !empty($this->options['database']))
		{
			$this->select($this->options['database']);
		}
	}
883406
public function connect(): void
    {
        try {
            $this->tryConnect();
        } catch (\PDOException $firstException) {
            $this->pdo = null;

            // todo: implement backup connections
            throw new AdapterException($firstException->getMessage(), (int) $firstException->getCode(), $firstException);
        }
    }