connect() public method

Establishes the connection with the database.
public connect ( ) : boolean
return boolean TRUE if the connection was successfully established, FALSE if the connection is already open.
 /**
  * @return Connection
  */
 public function getConnection()
 {
     if (false === $this->connection->ping()) {
         $this->connection->close();
         $this->connection->connect();
     }
     return $this->connection;
 }
Exemplo n.º 2
1
 protected function pingIt(Connection $con)
 {
     if ($con->ping() === false) {
         $con->close();
         $con->connect();
     }
     return $con;
 }
Exemplo n.º 3
0
 /**
  * Test if is connected
  *
  * @param bool $forceConnection
  * @return bool
  */
 public function isConnected($forceConnection = false)
 {
     if ($forceConnection) {
         $this->connection->connect();
     }
     return $this->connection->isConnected();
 }
Exemplo n.º 4
0
 /**
  * Connects to the database.
  *
  * @return boolean
  */
 public function connect()
 {
     if ($connected = $this->connection->connect()) {
         $this->events->dispatch(Events::postConnect, new Event\ConnectionEvent($this));
     }
     return $connected;
 }
Exemplo n.º 5
0
 /**
  * setup configuration for Doctrine Dbal.
  * 
  * @param array $db_config array config for override the default configuration.
  */
 public function setupConfigurationDbal(array $db_config = [])
 {
     $dbal_config = new Configuration();
     if (empty($db_config)) {
         //setup connection configuration.
         $config = new SystemConfig();
         $config->load('db');
         $db_params = $config->get('ALL', 'db');
         unset($config, $db_params['table_prefix']);
     } else {
         $db_params = $db_config;
         unset($db_params['table_prefix']);
     }
     $dbal_config->setSQLLogger(new \System\Libraries\Db\Logger());
     try {
         $this->Conn = DriverManager::getConnection($db_params, $dbal_config);
         $this->Conn->connect();
     } catch (\Doctrine\DBAL\DBALException $e) {
         http_response_code(500);
         echo $e->getMessage();
         exit;
     }
     $this->Conn->setFetchMode(\PDO::FETCH_OBJ);
     unset($dbal_config, $db_params);
 }
Exemplo n.º 6
0
 private function connectDatabase(OutputInterface $output)
 {
     $param = array();
     $param['host'] = $this->dialog->ask($output, '<question>Where is your database server? [localhost]</question> ', 'localhost');
     $param['user'] = $this->dialog->ask($output, '<question>What is your database username? [root]</question> ', 'root');
     $param['password'] = $this->dialog->ask($output, '<question>What is your database password?</question> ', '');
     $param['driver'] = 'pdo_mysql';
     // Save dbName for later use to create database
     $this->dbName = $this->dialog->ask($output, '<question>What is your database name? [BungaWire]</question> ', 'BungaWire');
     $output->writeln('');
     // Write empty line for easy read
     $config = new Configuration();
     $this->dbConnection = DriverManager::getConnection($param, $config);
     $this->dbConnection->connect();
     if ($this->dbConnection->isConnected() === false) {
         $output->writeln('Database connection failed, please check your setting');
         $output->writeln('You connection configuration is:');
         $output->writeln('host: ' . $param['host']);
         $output->writeln('user: '******'user']);
         $output->writeln('password: '******'password']);
         $output->writeln('Database Name: ' . $param['dbname']);
         $output->writeln('Driver: ' . $param['driver']);
         $output->writeln($this->dbConnection->errorInfo());
         $output->writeln('Please try again!');
         $this->connectDatabase($output);
     } else {
         $output->writeln('Database connected!');
     }
 }
 protected function setUp()
 {
     try {
         $this->con = DriverManager::getConnection(array('driver' => 'pdo_mysql', 'host' => 'localhost', 'user' => 'root', 'dbname' => 'testdb'));
         $this->con->connect();
     } catch (\Exception $e) {
         $this->markTestSkipped('Unable to connect to the database: ' . $e->getMessage());
     }
 }
Exemplo n.º 8
0
 /**
  * @return Job[]
  */
 public function getAll()
 {
     $this->conn->connect();
     $stmt = $this->conn->query("select * from {$this->table_name}");
     $stmt->setFetchMode(\PDO::FETCH_CLASS, '\\ebussola\\job\\job\\Job');
     $stmt->execute();
     $jobs = $stmt->fetchAll();
     $this->conn->close();
     return $jobs;
 }
 /**
  * Check Doctrine connection
  *
  * @return Result
  */
 public function check()
 {
     $result = new Result($this->label);
     try {
         $this->db->connect();
     } catch (\Exception $e) {
         $result->setSuccess(false);
         $result->setError($e->getMessage());
     }
     return $result;
 }
Exemplo n.º 10
0
 /**
  * Connect to the store.
  *
  * @throws StoreConnectionFailedException When could not connect to the store.
  */
 protected function connect()
 {
     if ($this->connected) {
         return;
     }
     try {
         $this->connection->connect();
     } catch (\Exception $e) {
         throw new StoreConnectionFailedException('DoctrineDBAL: ' . $e->getMessage(), $e->getCode(), $e);
     }
     $this->connected = true;
 }
Exemplo n.º 11
0
 /**
  * Check if the given table exists in a database
  *
  * @param string $tableName
  * @return bool TRUE if a table exists; otherwise, FALSE
  */
 public function isTableExist($tableName)
 {
     if (!empty($tableName)) {
         try {
             $this->connection->connect();
             return $this->connection->getSchemaManager()->tablesExist($tableName);
         } catch (\PDOException $e) {
         } catch (DBALException $e) {
         }
     }
     return false;
 }
Exemplo n.º 12
0
 protected function setUp()
 {
     if (!class_exists('Doctrine\\DBAL\\DriverManager')) {
         $this->markTestSkipped('The "Doctrine DBAL" library is not available');
     }
     try {
         $this->con = DriverManager::getConnection(array('driver' => 'pdo_mysql', 'host' => 'localhost', 'user' => 'root', 'dbname' => 'testdb'));
         $this->con->connect();
     } catch (\Exception $e) {
         $this->markTestSkipped('Unable to connect to the database: ' . $e->getMessage());
     }
 }
Exemplo n.º 13
0
 /**
  * Outputs the caller method name so that accidental queries can be noticed
  *
  * Using echo() is safe, since fixtures should be enabled on the command line while running PHPUnit only!
  *
  * @return bool
  */
 public function connect()
 {
     if ($this->usesFixtures() && $this->showFixtureWarnings) {
         echo ' [SQL CONNECT BY "' . $this->getFixtureCaller() . '"] ';
     }
     return parent::connect();
 }
Exemplo n.º 14
0
 /**
  * Explicitely opens the database connection. This is done to play nice
  * with DBAL's MasterSlaveConnection. Which, in some cases, connects to a
  * follower when fetching the executed migrations. If a follower is lagging
  * significantly behind that means the migrations system may see unexecuted
  * migrations that were actually executed earlier.
  *
  * @return bool The same value returned from the `connect` method
  */
 protected function connect()
 {
     if ($this->connection instanceof MasterSlaveConnection) {
         return $this->connection->connect('master');
     }
     return $this->connection->connect();
 }
Exemplo n.º 15
0
 public function connect()
 {
     $ret = parent::connect();
     if ($ret) {
         $params = $this->getParams();
         if (isset($params['portability'])) {
             if ($this->_platform->getName() === "oracle") {
                 $params['portability'] = $params['portability'] & self::PORTABILITY_ORACLE;
             } else {
                 if ($this->_platform->getName() === "postgresql") {
                     $params['portability'] = $params['portability'] & self::PORTABILITY_POSTGRESQL;
                 } else {
                     if ($this->_platform->getName() === "sqlite") {
                         $params['portability'] = $params['portability'] & self::PORTABILITY_SQLITE;
                     } else {
                         $params['portability'] = $params['portability'] & self::PORTABILITY_OTHERVENDORS;
                     }
                 }
             }
             $this->portability = $params['portability'];
         }
         if (isset($params['fetch_case']) && $this->portability & self::PORTABILITY_FIX_CASE) {
             if ($this->_conn instanceof \Doctrine\DBAL\Driver\PDOConnection) {
                 // make use of c-level support for case handling
                 $this->_conn->setAttribute(\PDO::ATTR_CASE, $params['fetch_case']);
             } else {
                 $this->case = $params['fetch_case'] == \PDO::CASE_LOWER ? CASE_LOWER : CASE_UPPER;
             }
         }
     }
     return $ret;
 }
Exemplo n.º 16
0
	public function connect() {
		try {
			return parent::connect();
		} catch (DBALException $e) {
			// throw a new exception to prevent leaking info from the stacktrace
			throw new DBALException('Failed to connect to the database: ' . $e->getMessage(), $e->getCode());
		}
	}
Exemplo n.º 17
0
 /**
  * @param Connection $connection
  *
  * @return bool
  */
 protected function checkDatabase(Connection $connection)
 {
     $result = false;
     try {
         $connection->connect();
         $result = $connection->isConnected() && $connection->getSchemaManager()->tablesExist([self::EVENT_TABLE_NAME]);
     } catch (\PDOException $e) {
     }
     return $result;
 }
Exemplo n.º 18
0
 /**
  * {@inheritdoc}
  */
 public function connect()
 {
     try {
         return parent::connect();
     } catch (DBALException $e) {
         if ($this->_eventManager->hasListeners('failConnect')) {
             $eventArgs = new FailedConnectionEvent($this, $e);
             $this->_eventManager->dispatchEvent('failConnect', $eventArgs);
         }
     }
 }
 public function connect()
 {
     // enable sharing connection across multiple instances
     $return = parent::connect();
     if (DoctrineDBALTestConnection::$_test_conn) {
         $this->_conn = DoctrineDBALTestConnection::$_test_conn;
     } else {
         DoctrineDBALTestConnection::$_test_conn = $this->_conn;
     }
     return $return;
 }
Exemplo n.º 20
0
 /**
  * Open the database connection.
  *
  * @return Connection
  * @throws \Doctrine\DBAL\DBALException
  */
 private function connect()
 {
     $connectionParams = array('driver' => $this->config->getDriver(), 'host' => $this->config->getHost(), 'user' => $this->config->getUser(), 'password' => $this->config->getPassword(), 'dbname' => $this->config->getDatabaseName(), 'charset' => $this->config->getCharset());
     $dbalConfig = new Configuration();
     $this->connection = DriverManager::getConnection($connectionParams, $dbalConfig);
     $this->connection->connect();
     $this->initPlatformAdjustment($this->connection);
     $this->platformAdjustment->initConnection();
     $this->platformAdjustment->registerCustomTypeMappings();
     return $this->connection;
 }
Exemplo n.º 21
0
 private static final function initializeDatabase()
 {
     if (!self::$dbReused) {
         self::runCommand('doctrine:database:drop', array('--force' => true));
         self::runCommand('doctrine:database:create');
         self::$conn->close();
         self::$conn->connect();
         foreach (self::$dbInitializer->getMigrationFiles() as $file) {
             self::runCommand('dbal:import', array('file' => $file));
         }
     }
 }
Exemplo n.º 22
0
 public function testConnectDispatchEvent()
 {
     $listenerMock = $this->getMock('ConnectDispatchEventListener', array('postConnect'));
     $listenerMock->expects($this->once())->method('postConnect');
     $eventManager = new EventManager();
     $eventManager->addEventListener(array(Events::postConnect), $listenerMock);
     $driverMock = $this->getMock('Doctrine\\DBAL\\Driver');
     $driverMock->expects($this->at(0))->method('connect');
     $platform = new Mocks\MockPlatform();
     $conn = new Connection(array('platform' => $platform), $driverMock, new Configuration(), $eventManager);
     $conn->connect();
 }
Exemplo n.º 23
0
 /**
  * Checks whether a database connection can be established and all given tables exist in the database.
  *
  * @param Connection           $connection
  * @param string[]|string|null $tables
  *
  * @return bool
  */
 public static function tablesExist(Connection $connection, $tables)
 {
     $result = false;
     if (!empty($tables)) {
         try {
             $connection->connect();
             $result = $connection->getSchemaManager()->tablesExist($tables);
         } catch (\PDOException $e) {
         } catch (DBALException $e) {
         }
     }
     return $result;
 }
 /**
  * Initial setup.
  */
 protected function setUp()
 {
     $this->db = \Doctrine\DBAL\DriverManager::getConnection(array('driver' => 'pdo_sqlite', 'memory' => true), new \Doctrine\DBAL\Configuration());
     $this->db->connect();
     $this->plugin = new Plugin($this->db);
     $this->logger = Phake::mock('\\Psr\\Log\\LoggerInterface');
     $this->plugin->setLogger($this->logger);
     $this->connection = Phake::mock('\\Phergie\\Irc\\ConnectionInterface');
     Phake::when($this->connection)->getNickname()->thenReturn('TestNick');
     Phake::when($this->connection)->getUsername()->thenReturn('TestUser');
     Phake::when($this->connection)->getServerHostname()->thenReturn('Test.Server');
     $this->queue = Phake::mock('\\Phergie\\Irc\\Bot\\React\\EventQueueInterface');
 }
 /**
  * @throws \Exception if an unexpected database error occurs
  */
 private function configuredDatabaseExists()
 {
     try {
         $this->db->connect();
     } catch (ConnectionException $e) {
         // @todo 1049 is MySQL's code for "database doesn't exist", refactor
         if ($e->getPrevious()->getCode() == 1049) {
             return false;
         }
         throw $e;
     }
     return true;
 }
Exemplo n.º 26
0
 /**
  * {@inheritDoc}
  */
 public function connect()
 {
     if ($this->isConnected()) {
         return false;
     }
     if ($this->hasPersistedConnection()) {
         $this->_conn = $this->getPersistedConnection();
         $this->setConnected(true);
     } else {
         parent::connect();
         $this->persistConnection($this->_conn);
     }
     return true;
 }
 /**
  * It attempts to reconnect if connection is non responsive. Failing to reconnect triggers a critical error.
  * If connection is responsive or successfully reconnected it rethrows, relying on the bus retries
  * to re-execute everything from the beginning.
  *
  * @param \Exception $e
  *
  * @return \Exception|CriticalErrorException
  */
 private function attemptToReconnectPresumedLostConnection(\Exception $e)
 {
     // presumably, any exception caught here is related to some connection error
     if (!$this->connection->ping()) {
         // if pinging fails, we try to reconnect
         try {
             $this->connection->close();
             $this->connection->connect();
         } catch (\Exception $e) {
             // if reconnecting fails, there is no way that the bus can continue to function
             return new CriticalErrorException("Database connection failed.", 0, $e);
         }
     }
     return $e;
 }
 /**
  * {@inheritDoc}
  */
 public function connect()
 {
     if ($this->isConnected()) {
         return false;
     }
     if ($this->hasPersistedConnection()) {
         $this->_conn = $this->getPersistedConnection();
         $this->setConnected(true);
     } else {
         parent::connect();
         $this->setPersistedConnection($this->_conn);
         $this->_conn->exec('SET SESSION wait_timeout=2147483');
     }
     return true;
 }
 /**
  * Closes connection if open, opens a unbuffered connection.
  *
  * @param Connection $connection
  *
  * @throws InvalidArgumentException
  */
 public static function unbufferConnection(Connection $connection)
 {
     /** @var PDOConnection $wrappedConnection */
     $wrappedConnection = $connection->getWrappedConnection();
     if (!$wrappedConnection instanceof PDOConnection) {
         throw new InvalidArgumentException('unbufferConection can only be used with pdo_mysql Doctrine driver.');
     }
     if ($wrappedConnection->getAttribute(PDO::ATTR_DRIVER_NAME) != 'mysql') {
         throw new InvalidArgumentException('unbufferConection can only be used with PDO mysql driver, got "' . $wrappedConnection->getAttribute(PDO::ATTR_DRIVER_NAME) . '" instead.');
     }
     if ($connection->isConnected()) {
         $connection->close();
     }
     $connection->getWrappedConnection()->setAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, false);
     $connection->connect();
 }
Exemplo n.º 30
0
 /**
  * Checks if a database connection can be established.
  *
  * @param string $name The database name
  *
  * @return bool True if a database connection can be established
  */
 public function canConnectToDatabase($name)
 {
     if (null === $this->connection) {
         return false;
     }
     try {
         $this->connection->connect();
     } catch (ConnectionException $e) {
         return false;
     }
     $quotedName = $this->connection->quoteIdentifier($name);
     try {
         $this->connection->query('use ' . $quotedName);
     } catch (DBALException $e) {
         return false;
     }
     return true;
 }