|
| 1 | +<?php |
| 2 | + |
| 3 | +/** |
| 4 | + * This file is licensed under MIT License. |
| 5 | + * |
| 6 | + * Copyright (c) 2025-present WebFiori Framework |
| 7 | + * |
| 8 | + * For more information on the license, please visit: |
| 9 | + * https://github.com/WebFiori/.github/blob/main/LICENSE |
| 10 | + * |
| 11 | + */ |
| 12 | +namespace WebFiori\Database; |
| 13 | + |
| 14 | +use WebFiori\Database\MySql\MySQLConnection; |
| 15 | +use WebFiori\Database\MsSql\MSSQLConnection; |
| 16 | + |
| 17 | +/** |
| 18 | + * A connection pool that manages database connection lifecycle. |
| 19 | + * |
| 20 | + * The pool reuses idle connections instead of creating new ones, |
| 21 | + * preventing "Too many connections" errors and reducing overhead |
| 22 | + * from repeated connection handshakes. |
| 23 | + * |
| 24 | + * Usage: |
| 25 | + * ```php |
| 26 | + * $pool = ConnectionPool::getInstance(); |
| 27 | + * $conn = $pool->acquire($connectionInfo); |
| 28 | + * // ... use connection ... |
| 29 | + * $pool->release($conn); |
| 30 | + * ``` |
| 31 | + * |
| 32 | + * @author Ibrahim |
| 33 | + */ |
| 34 | +class ConnectionPool { |
| 35 | + private static ?ConnectionPool $instance = null; |
| 36 | + |
| 37 | + /** @var array<string, Connection[]> */ |
| 38 | + private array $idle = []; |
| 39 | + |
| 40 | + /** @var array<string, Connection[]> */ |
| 41 | + private array $active = []; |
| 42 | + |
| 43 | + private int $maxPerKey = 10; |
| 44 | + private int $maxTotal = 100; |
| 45 | + |
| 46 | + private function __construct() { |
| 47 | + } |
| 48 | + |
| 49 | + /** |
| 50 | + * Returns the singleton pool instance. |
| 51 | + * |
| 52 | + * @return ConnectionPool |
| 53 | + */ |
| 54 | + public static function getInstance(): self { |
| 55 | + if (self::$instance === null) { |
| 56 | + self::$instance = new self(); |
| 57 | + } |
| 58 | + return self::$instance; |
| 59 | + } |
| 60 | + |
| 61 | + /** |
| 62 | + * Acquire a connection for the given connection info. |
| 63 | + * |
| 64 | + * If an idle connection exists for the same host/port/db/user combination, |
| 65 | + * it will be reused. Otherwise, a new connection is created. |
| 66 | + * |
| 67 | + * @param ConnectionInfo $info Connection parameters. |
| 68 | + * |
| 69 | + * @return Connection A ready-to-use database connection. |
| 70 | + * |
| 71 | + * @throws DatabaseException If the pool is exhausted or connection fails. |
| 72 | + */ |
| 73 | + public function acquire(ConnectionInfo $info): Connection { |
| 74 | + $key = $this->buildKey($info); |
| 75 | + |
| 76 | + // Try to reuse an idle connection |
| 77 | + while (!empty($this->idle[$key])) { |
| 78 | + $conn = array_pop($this->idle[$key]); |
| 79 | + |
| 80 | + if ($conn->isAlive()) { |
| 81 | + $this->active[$key][] = $conn; |
| 82 | + return $conn; |
| 83 | + } |
| 84 | + |
| 85 | + // Dead connection, discard |
| 86 | + $conn->close(); |
| 87 | + } |
| 88 | + |
| 89 | + // Check total limit |
| 90 | + if ($this->getActiveCount() >= $this->maxTotal) { |
| 91 | + throw new DatabaseException( |
| 92 | + "Connection pool exhausted (max: {$this->maxTotal})" |
| 93 | + ); |
| 94 | + } |
| 95 | + |
| 96 | + // Create new connection |
| 97 | + $conn = $this->createConnection($info); |
| 98 | + $this->active[$key][] = $conn; |
| 99 | + return $conn; |
| 100 | + } |
| 101 | + |
| 102 | + /** |
| 103 | + * Release a connection back to the pool for reuse. |
| 104 | + * |
| 105 | + * @param Connection $conn The connection to release. |
| 106 | + */ |
| 107 | + public function release(Connection $conn): void { |
| 108 | + $key = $this->buildKey($conn->getConnectionInfo()); |
| 109 | + |
| 110 | + // Remove from active |
| 111 | + if (isset($this->active[$key])) { |
| 112 | + $index = array_search($conn, $this->active[$key], true); |
| 113 | + |
| 114 | + if ($index !== false) { |
| 115 | + unset($this->active[$key][$index]); |
| 116 | + $this->active[$key] = array_values($this->active[$key]); |
| 117 | + } |
| 118 | + } |
| 119 | + |
| 120 | + // Return to idle if under per-key limit |
| 121 | + $idleCount = count($this->idle[$key] ?? []); |
| 122 | + |
| 123 | + if ($idleCount < $this->maxPerKey && $conn->isAlive()) { |
| 124 | + $this->idle[$key][] = $conn; |
| 125 | + } else { |
| 126 | + $conn->close(); |
| 127 | + } |
| 128 | + } |
| 129 | + |
| 130 | + /** |
| 131 | + * Close all connections (idle and active) and drain the pool. |
| 132 | + */ |
| 133 | + public function closeAll(): void { |
| 134 | + foreach ($this->idle as $connections) { |
| 135 | + foreach ($connections as $conn) { |
| 136 | + $conn->close(); |
| 137 | + } |
| 138 | + } |
| 139 | + |
| 140 | + foreach ($this->active as $connections) { |
| 141 | + foreach ($connections as $conn) { |
| 142 | + $conn->close(); |
| 143 | + } |
| 144 | + } |
| 145 | + |
| 146 | + $this->idle = []; |
| 147 | + $this->active = []; |
| 148 | + } |
| 149 | + |
| 150 | + /** |
| 151 | + * Set the maximum number of connections per unique key (host+port+db+user). |
| 152 | + * |
| 153 | + * @param int $max Maximum idle connections per key. |
| 154 | + */ |
| 155 | + public function setMaxPerKey(int $max): void { |
| 156 | + if ($max > 0) { |
| 157 | + $this->maxPerKey = $max; |
| 158 | + } |
| 159 | + } |
| 160 | + |
| 161 | + /** |
| 162 | + * Set the maximum total number of active connections across all keys. |
| 163 | + * |
| 164 | + * @param int $max Maximum total active connections. |
| 165 | + */ |
| 166 | + public function setMaxTotal(int $max): void { |
| 167 | + if ($max > 0) { |
| 168 | + $this->maxTotal = $max; |
| 169 | + } |
| 170 | + } |
| 171 | + |
| 172 | + /** |
| 173 | + * Returns the maximum number of idle connections per key. |
| 174 | + * |
| 175 | + * @return int |
| 176 | + */ |
| 177 | + public function getMaxPerKey(): int { |
| 178 | + return $this->maxPerKey; |
| 179 | + } |
| 180 | + |
| 181 | + /** |
| 182 | + * Returns the maximum total active connections allowed. |
| 183 | + * |
| 184 | + * @return int |
| 185 | + */ |
| 186 | + public function getMaxTotal(): int { |
| 187 | + return $this->maxTotal; |
| 188 | + } |
| 189 | + |
| 190 | + /** |
| 191 | + * Returns the number of currently active (in-use) connections. |
| 192 | + * |
| 193 | + * @return int |
| 194 | + */ |
| 195 | + public function getActiveCount(): int { |
| 196 | + $count = 0; |
| 197 | + |
| 198 | + foreach ($this->active as $connections) { |
| 199 | + $count += count($connections); |
| 200 | + } |
| 201 | + |
| 202 | + return $count; |
| 203 | + } |
| 204 | + |
| 205 | + /** |
| 206 | + * Returns the number of currently idle (available) connections. |
| 207 | + * |
| 208 | + * @return int |
| 209 | + */ |
| 210 | + public function getIdleCount(): int { |
| 211 | + $count = 0; |
| 212 | + |
| 213 | + foreach ($this->idle as $connections) { |
| 214 | + $count += count($connections); |
| 215 | + } |
| 216 | + |
| 217 | + return $count; |
| 218 | + } |
| 219 | + |
| 220 | + /** |
| 221 | + * Reset the pool singleton. Closes all connections and destroys the instance. |
| 222 | + * Primarily useful for testing. |
| 223 | + */ |
| 224 | + public static function reset(): void { |
| 225 | + if (self::$instance !== null) { |
| 226 | + self::$instance->closeAll(); |
| 227 | + } |
| 228 | + self::$instance = null; |
| 229 | + } |
| 230 | + |
| 231 | + private function buildKey(ConnectionInfo $info): string { |
| 232 | + return $info->getHost() . ':' . $info->getPort() . '/' |
| 233 | + . $info->getDBName() . '@' . $info->getUsername(); |
| 234 | + } |
| 235 | + |
| 236 | + private function createConnection(ConnectionInfo $info): Connection { |
| 237 | + $driver = $info->getDatabaseType(); |
| 238 | + |
| 239 | + return match ($driver) { |
| 240 | + 'mysql' => new MySQLConnection($info), |
| 241 | + 'mssql' => new MSSQLConnection($info), |
| 242 | + default => throw new DatabaseException("Unsupported driver: $driver"), |
| 243 | + }; |
| 244 | + } |
| 245 | +} |
0 commit comments