Connects to the configured PDO database and adds/updates table schema if required

@return Result
@api
2051
public function setup(): Result
    {
        $result = new Result();
        try {
            $this->connect();
            $connection = DriverManager::getConnection(['pdo' => $this->databaseHandle]);
        } catch (Exception | FilesException |DBALException $exception) {
            $result->addError(new Error($exception->getMessage(), $exception->getCode(), [], 'Connection failed'));
            return $result;
        }

        try {
            $tablesExist = $connection->getSchemaManager()->tablesExist([$this->cacheTableName, $this->tagsTableName]);
        } /** @noinspection PhpRedundantCatchClauseInspection */ catch (DBALException $exception) {
            $result->addError(new Error($exception->getMessage(), $exception->getCode(), [], 'Connection failed'));
            return $result;
        }
        if ($tablesExist) {
            $result->addNotice(new Notice('Tables "%s" and "%s" (already exists)', null, [$this->cacheTableName, $this->tagsTableName]));
        } else {
            $result->addNotice(new Notice('Creating database tables "%s" & "%s"...', null, [$this->cacheTableName, $this->tagsTableName]));
        }

        $fromSchema = $connection->getSchemaManager()->createSchema();
        $schemaDiff = (new Comparator())->compare($fromSchema, $this->getCacheTablesSchema());

        try {
            $statements = $schemaDiff->toSaveSql($connection->getDatabasePlatform());
        } catch (DBALException $exception) {
            $result->addError(new Error($exception->getMessage(), $exception->getCode(), [], 'Connection failed'));
            return $result;
        }
        if ($statements === []) {
            $result->addNotice(new Notice('Table schema is up to date, no migration required'));
            return $result;
        }
        $connection->beginTransaction();
        try {
            foreach ($statements as $statement) {
                $result->addNotice(new Notice('<info>++</info> %s', null, [$statement]));
                $connection->exec($statement);
            }
            $connection->commit();
        } catch (\Exception $exception) {
            try {
                $connection->rollBack();
            } catch (\Exception $exception) {
            }
            $result->addError(new Error('Exception while trying to setup PdoBackend: %s', $exception->getCode(), [$exception->getMessage()]));
        }
        return $result;
    }
487520
private function connect()
    {
        $dsn = "{$this->credentials->getDriver()}:host={$this->credentials->getHost()}";

        try {
            $pdo = new \PDO($dsn, $this->credentials->getUsername(), $this->credentials->getPassword());
        } catch (\PDOException $e) {
            throw new \RuntimeException('Failed to connect to database.', 0, $e);
        }

        $this->pdo = $pdo;

        if (null !== $this->credentials->getCharset()) {
            $this->setCharset($this->credentials->getCharset());
        }

        if (null !== $this->credentials->getDatabase()) {
            $this->selectDatabase($this->credentials->getDatabase());
        }
    }
698573
public function connect()
    {
        $dsn = "sqlite:{$this->_file}";
        try {
            $class = $this->_handlerClass;
            $this->_handler = new $class($dsn);
            $this->_handler->setAttribute(
                PDO::ATTR_ERRMODE,
                PDO::ERRMODE_EXCEPTION
            );
            $this->_connected = true;
        } catch (\Exception $exp) {
            throw new ServiceException(
                "An error occurred when trying to connect to database " .
                "service. Error: {$exp->getMessage()}"
            );
        }
        return $this;
    }
419801
public function getConnection()
    {
        if ($this->connection === null) {
            $this->connection = new PDO(
                'mysql:dbname=' . $this->database . ';host=' . $this->host,
                $this->username,
                $this->password,
                array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
        }

        return $this->connection;
    }
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;
    }
731385
public function connect() : bool
    {
        try {
            $connection_string = 'sqlsrv:SERVER=' . $this->configuration['server'] . ';DATABASE=' . $this->configuration['dbname'];
            if (isset($this->configuration['encrypt']) && true === $this->configuration['encrypt']) {
                $connection_string .= ';ENCRYPT=1';
            }
            $this->logger->debug('Connecting to database engine.');
            $this->dbconn = new PDO($connection_string, $this->configuration['username'],
                $this->configuration['password']);
            $this->dbconn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            $this->logger->debug('Connected to database engine.');
            $this->is_connected = true;
        } catch (\Exception $e) {
            throw new DatabaseConnectionException('MSSQL Connection to <strong>' . $this->configuration['server'] . '</strong> failed!<br>' . $e->getMessage());
        }
        return true;
    }
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']);
		}
	}
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;
        }
    }
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');
        }
    }
672852
public function createDatabase()
    {
        try {
            $dsn = 'mysql:host=' . $this->host . ';';
            $options = [\PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES UTF8'];
            $connect = new \PDO($dsn, $this->user, $this->pass, $options);
            $connect->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);

            $command = $connect->prepare("CREATE DATABASE {$this->database}");
            $command->execute();

        } catch (\PDOException $e) {
            return false;
        }
    }
792416
public function connectTo($schema) {
		$info = clone $this->getInfo();
		$info->setSchema($schema);
		return new DatabaseConnection($info);
	}
287799
public function connection()
    {
        if (!is_object($this->db)) {
            $this->db = new \FaaPz\PDO\Database(
                $this->database['driver'] . ':host=' . $this->database['host'] . ';port=' . $this->database['port'] . ';dbname=' . $this->database['database'] . ';charset=' . $this->database['charset'] . ';collation=' . $this->database['collation'] . ';prefix=' . $this->database['prefix'],
                $this->database['username'],
                $this->database['password'],
                $this->database['options']
            );
            $this->db->setAttribute(\PDO::ATTR_DEFAULT_FETCH_MODE, \PDO::FETCH_OBJ);
        }

        return $this;
    }
788002
public function connect()
    {
        try {
            // Make string containing database settings
            $database = 'sqlsrv:Server=' . $this->host . ';Database=' . $this->database;

            // Make connection.
            $conn = new \PDO($database, $this->username, $this->password);

            // Set attributes from parameters
            $conn->setAttribute(\PDO::ATTR_DEFAULT_FETCH_MODE, $this->fetch);
            $conn->setAttribute(\PDO::ATTR_ERRMODE, $this->error);

            return $conn;
        } catch (\PDOException $ex) {
            throw new \InvalidArgumentException('Error! Cannot connect to database ' . $ex->getMessage());
        }
    }
527397
public function connect() : object
    {
        if ($this->pdo) {
            return $this;
        }

        if (!isset($this->options["dsn"])) {
            throw new Exception("You can not connect, missing dsn.");
        }

        try {
            $this->pdo = new \PDO(
                $this->options["dsn"],
                $this->options["username"],
                $this->options["password"],
                $this->options["driver_options"]
            );
            $this->pdo->setAttribute(\PDO::ATTR_DEFAULT_FETCH_MODE, $this->options['fetch_mode']);
            $this->pdo->setAttribute(\PDO::ATTR_EMULATE_PREPARES, $this->options['emulate_prepares']);
        } catch (\PDOException $e) {
            if ($this->options["debug_connect"]) {
                throw $e;
            }
            throw new Exception("Could not connect to database, hiding connection details.");
        }

        return $this;
    }
1163073
public function connection()
    {
        // Build of the mysql dsn
        if (isset($this->config['socket']) && !is_null($this->config['socket']) && !empty($this->config['socket'])) {
            $hostname = $this->config['socket'];
        } else {
            $hostname = $this->config['hostname'];
        }

        $port = '';

        if ($hostname !== 'localhost' || $hostname == '127.0.0.1') {
            if (isset($this->config['port']) && !is_null($this->config['port']) && !empty($this->config['port'])) {
                $port = ':'.$this->config['port'];
            } else {
                $port = ':'.self::PORT;
            }
        }

        // Formatting connection parameters
        $host  = "mysql:host=".$hostname.$port;

        $database = "dbname=".$this->config['database'];

        $username = $this->config["username"];

        $password = $this->config["password"];

        // Configuration extra PDO side
        $options = [
            PDO::ATTR_DEFAULT_FETCH_MODE => isset($this->config['fetch']) ? $this->config['fetch'] : $this->fetch,
            PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
            PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES " . Str::upper($this->config["charset"]),
            PDO::ATTR_ORACLE_NULLS => PDO::NULL_EMPTY_STRING
        ];

        $this->pdo = new PDO($host.';'.$database, $username, $password, $options);
    }
831429
public function connect()
    {
        if (self::$profiling) {
            $timer = $this->initProfiler();
        }

        // Make sure MySQL returns all matched rows on update queries including
        // rows that actually didn't have to be updated because the values didn't
        // change. This matches common behaviour among other database systems.
        // See #6296 why this is important in tracker
        $this->mysqlOptions[PDO::MYSQL_ATTR_FOUND_ROWS] = true;
        $this->mysqlOptions[PDO::ATTR_ERRMODE] = PDO::ERRMODE_EXCEPTION;
        


        $this->connection = @new PDO($this->dsn, $this->username, $this->password, $this->mysqlOptions);

        // we may want to setAttribute(PDO::ATTR_TIMEOUT ) to a few seconds (default is 60) in case the DB is locked
        // the matomo.php would stay waiting for the database... bad!
        // we delete the password from this object "just in case" it could be printed
        $this->password = '';

        /*
         * Lazy initialization via MYSQL_ATTR_INIT_COMMAND depends
         * on mysqlnd support, PHP version, and OS.
         * see ZF-7428 and http://bugs.php.net/bug.php?id=47224
         */
        if (!empty($this->charset)) {
            $sql = "SET NAMES '" . $this->charset . "'";
            $this->connection->exec($sql);
        }

        if (self::$profiling && isset($timer)) {
            $this->recordQueryProfile('connect', $timer);
        }
    }
1013525
public function Connection() {
      $this->_IsPersistent = GetValue(PDO::ATTR_PERSISTENT, $this->ConnectionOptions, FALSE);
      if(!is_object($this->_Connection)) {
         try {
            $this->_Connection = new PDO(strtolower($this->Engine) . ':' . $this->Dsn, $this->User, $this->Password, $this->ConnectionOptions);
            $this->_Connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, 0);
            
            if($this->ConnectionOptions[1002])
               $this->Query($this->ConnectionOptions[1002]);
            
            // We only throw exceptions during connect
            $this->_Connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_SILENT);
         } catch (Exception $ex) {
            $Timeout = FALSE;
            if ($ex->getCode() == '2002' && preg_match('/Operation timed out/i', $ex->getMessage()))
               $Timeout = TRUE;
            if ($ex->getCode() == '2003' && preg_match("/Can't connect to MySQL/i", $ex->getMessage()))
               $Timeout = TRUE;
                    
            if ($Timeout)
               throw new Exception(ErrorMessage('Timeout while connecting to the database', $this->ClassName, 'Connection', $ex->getMessage()), 504);
            
            trigger_error(ErrorMessage('An error occurred while attempting to connect to the database', $this->ClassName, 'Connection', $ex->getMessage()), E_USER_ERROR);
         }
      }
      
      return $this->_Connection;
   }