/** * This function returns the appropriate connection from the pool. When there are * multiple connections created from the same data source, the last opened connection * will be returned when $new is set to "FALSE." * * @access public * @param mixed $config the data source configurations * @param boolean $new whether to create a new connection * @return DB_Connection_Driver the appropriate connection * @throws Throwable_Database_Exception indicates that no new connections * can be added */ public function get_connection($config = 'default', $new = FALSE) { $data_source = DB_DataSource::instance($config); if (isset($this->pool[$data_source->id]) and !empty($this->pool[$data_source->id])) { if ($new) { foreach ($this->pool[$data_source->id] as $connection) { if (!$connection->is_connected()) { $connection->open(); return $connection; } } } else { $connection = end($this->pool[$data_source->id]); do { if ($connection->is_connected()) { reset($this->pool[$data_source->id]); return $connection; } } while ($connection = prev($this->pool[$data_source->id])); $connection = end($this->pool[$data_source->id]); reset($this->pool[$data_source->id]); $connection->open(); return $connection; } } if ($this->count() >= $this->settings['max_size']) { throw new Throwable_Database_Exception('Message: Failed to create new connection. Reason: Exceeded maximum number of connections that may be held in the pool.', array(':source' => $data_source, ':new' => $new)); } $connection = DB_Connection_Driver::factory($data_source); $connection->open(); $connection_id = $connection->__hashCode(); $this->pool[$data_source->id][$connection_id] = $connection; $this->lookup[$connection_id] = $data_source->id; return $connection; }