DriverManager.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435
  1. <?php
  2. namespace Doctrine\DBAL;
  3. use Doctrine\Common\EventManager;
  4. use Doctrine\DBAL\Driver\DrizzlePDOMySql\Driver as DrizzlePDOMySQLDriver;
  5. use Doctrine\DBAL\Driver\IBMDB2\DB2Driver;
  6. use Doctrine\DBAL\Driver\Mysqli\Driver as MySQLiDriver;
  7. use Doctrine\DBAL\Driver\OCI8\Driver as OCI8Driver;
  8. use Doctrine\DBAL\Driver\PDOMySql\Driver as PDOMySQLDriver;
  9. use Doctrine\DBAL\Driver\PDOOracle\Driver as PDOOCIDriver;
  10. use Doctrine\DBAL\Driver\PDOPgSql\Driver as PDOPgSQLDriver;
  11. use Doctrine\DBAL\Driver\PDOSqlite\Driver as PDOSQLiteDriver;
  12. use Doctrine\DBAL\Driver\PDOSqlsrv\Driver as PDOSQLSrvDriver;
  13. use Doctrine\DBAL\Driver\SQLAnywhere\Driver as SQLAnywhereDriver;
  14. use Doctrine\DBAL\Driver\SQLSrv\Driver as SQLSrvDriver;
  15. use PDO;
  16. use function array_keys;
  17. use function array_map;
  18. use function array_merge;
  19. use function class_implements;
  20. use function in_array;
  21. use function is_subclass_of;
  22. use function parse_str;
  23. use function parse_url;
  24. use function preg_replace;
  25. use function str_replace;
  26. use function strpos;
  27. use function substr;
  28. /**
  29. * Factory for creating Doctrine\DBAL\Connection instances.
  30. */
  31. final class DriverManager
  32. {
  33. /**
  34. * List of supported drivers and their mappings to the driver classes.
  35. *
  36. * To add your own driver use the 'driverClass' parameter to
  37. * {@link DriverManager::getConnection()}.
  38. *
  39. * @var string[]
  40. */
  41. private static $_driverMap = [
  42. 'pdo_mysql' => PDOMySQLDriver::class,
  43. 'pdo_sqlite' => PDOSQLiteDriver::class,
  44. 'pdo_pgsql' => PDOPgSQLDriver::class,
  45. 'pdo_oci' => PDOOCIDriver::class,
  46. 'oci8' => OCI8Driver::class,
  47. 'ibm_db2' => DB2Driver::class,
  48. 'pdo_sqlsrv' => PDOSQLSrvDriver::class,
  49. 'mysqli' => MySQLiDriver::class,
  50. 'drizzle_pdo_mysql' => DrizzlePDOMySQLDriver::class,
  51. 'sqlanywhere' => SQLAnywhereDriver::class,
  52. 'sqlsrv' => SQLSrvDriver::class,
  53. ];
  54. /**
  55. * List of URL schemes from a database URL and their mappings to driver.
  56. *
  57. * @var string[]
  58. */
  59. private static $driverSchemeAliases = [
  60. 'db2' => 'ibm_db2',
  61. 'mssql' => 'pdo_sqlsrv',
  62. 'mysql' => 'pdo_mysql',
  63. 'mysql2' => 'pdo_mysql', // Amazon RDS, for some weird reason
  64. 'postgres' => 'pdo_pgsql',
  65. 'postgresql' => 'pdo_pgsql',
  66. 'pgsql' => 'pdo_pgsql',
  67. 'sqlite' => 'pdo_sqlite',
  68. 'sqlite3' => 'pdo_sqlite',
  69. ];
  70. /**
  71. * Private constructor. This class cannot be instantiated.
  72. */
  73. private function __construct()
  74. {
  75. }
  76. /**
  77. * Creates a connection object based on the specified parameters.
  78. * This method returns a Doctrine\DBAL\Connection which wraps the underlying
  79. * driver connection.
  80. *
  81. * $params must contain at least one of the following.
  82. *
  83. * Either 'driver' with one of the following values:
  84. *
  85. * pdo_mysql
  86. * pdo_sqlite
  87. * pdo_pgsql
  88. * pdo_oci (unstable)
  89. * pdo_sqlsrv
  90. * pdo_sqlsrv
  91. * mysqli
  92. * sqlanywhere
  93. * sqlsrv
  94. * ibm_db2 (unstable)
  95. * drizzle_pdo_mysql
  96. *
  97. * OR 'driverClass' that contains the full class name (with namespace) of the
  98. * driver class to instantiate.
  99. *
  100. * Other (optional) parameters:
  101. *
  102. * <b>user (string)</b>:
  103. * The username to use when connecting.
  104. *
  105. * <b>password (string)</b>:
  106. * The password to use when connecting.
  107. *
  108. * <b>driverOptions (array)</b>:
  109. * Any additional driver-specific options for the driver. These are just passed
  110. * through to the driver.
  111. *
  112. * <b>pdo</b>:
  113. * You can pass an existing PDO instance through this parameter. The PDO
  114. * instance will be wrapped in a Doctrine\DBAL\Connection.
  115. *
  116. * <b>wrapperClass</b>:
  117. * You may specify a custom wrapper class through the 'wrapperClass'
  118. * parameter but this class MUST inherit from Doctrine\DBAL\Connection.
  119. *
  120. * <b>driverClass</b>:
  121. * The driver class to use.
  122. *
  123. * @param mixed[] $params The parameters.
  124. * @param Configuration|null $config The configuration to use.
  125. * @param EventManager|null $eventManager The event manager to use.
  126. *
  127. * @throws DBALException
  128. */
  129. public static function getConnection(
  130. array $params,
  131. ?Configuration $config = null,
  132. ?EventManager $eventManager = null
  133. ) : Connection {
  134. // create default config and event manager, if not set
  135. if (! $config) {
  136. $config = new Configuration();
  137. }
  138. if (! $eventManager) {
  139. $eventManager = new EventManager();
  140. }
  141. $params = self::parseDatabaseUrl($params);
  142. // URL support for MasterSlaveConnection
  143. if (isset($params['master'])) {
  144. $params['master'] = self::parseDatabaseUrl($params['master']);
  145. }
  146. if (isset($params['slaves'])) {
  147. foreach ($params['slaves'] as $key => $slaveParams) {
  148. $params['slaves'][$key] = self::parseDatabaseUrl($slaveParams);
  149. }
  150. }
  151. // URL support for PoolingShardConnection
  152. if (isset($params['global'])) {
  153. $params['global'] = self::parseDatabaseUrl($params['global']);
  154. }
  155. if (isset($params['shards'])) {
  156. foreach ($params['shards'] as $key => $shardParams) {
  157. $params['shards'][$key] = self::parseDatabaseUrl($shardParams);
  158. }
  159. }
  160. // check for existing pdo object
  161. if (isset($params['pdo']) && ! $params['pdo'] instanceof PDO) {
  162. throw DBALException::invalidPdoInstance();
  163. } elseif (isset($params['pdo'])) {
  164. $params['pdo']->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  165. $params['driver'] = 'pdo_' . $params['pdo']->getAttribute(PDO::ATTR_DRIVER_NAME);
  166. } else {
  167. self::_checkParams($params);
  168. }
  169. $className = $params['driverClass'] ?? self::$_driverMap[$params['driver']];
  170. $driver = new $className();
  171. $wrapperClass = Connection::class;
  172. if (isset($params['wrapperClass'])) {
  173. if (! is_subclass_of($params['wrapperClass'], $wrapperClass)) {
  174. throw DBALException::invalidWrapperClass($params['wrapperClass']);
  175. }
  176. $wrapperClass = $params['wrapperClass'];
  177. }
  178. return new $wrapperClass($params, $driver, $config, $eventManager);
  179. }
  180. /**
  181. * Returns the list of supported drivers.
  182. *
  183. * @return string[]
  184. */
  185. public static function getAvailableDrivers() : array
  186. {
  187. return array_keys(self::$_driverMap);
  188. }
  189. /**
  190. * Checks the list of parameters.
  191. *
  192. * @param mixed[] $params The list of parameters.
  193. *
  194. * @throws DBALException
  195. */
  196. private static function _checkParams(array $params) : void
  197. {
  198. // check existence of mandatory parameters
  199. // driver
  200. if (! isset($params['driver']) && ! isset($params['driverClass'])) {
  201. throw DBALException::driverRequired();
  202. }
  203. // check validity of parameters
  204. // driver
  205. if (isset($params['driver']) && ! isset(self::$_driverMap[$params['driver']])) {
  206. throw DBALException::unknownDriver($params['driver'], array_keys(self::$_driverMap));
  207. }
  208. if (isset($params['driverClass']) && ! in_array(Driver::class, class_implements($params['driverClass'], true))) {
  209. throw DBALException::invalidDriverClass($params['driverClass']);
  210. }
  211. }
  212. /**
  213. * Normalizes the given connection URL path.
  214. *
  215. * @return string The normalized connection URL path
  216. */
  217. private static function normalizeDatabaseUrlPath(string $urlPath) : string
  218. {
  219. // Trim leading slash from URL path.
  220. return substr($urlPath, 1);
  221. }
  222. /**
  223. * Extracts parts from a database URL, if present, and returns an
  224. * updated list of parameters.
  225. *
  226. * @param mixed[] $params The list of parameters.
  227. *
  228. * @return mixed[] A modified list of parameters with info from a database
  229. * URL extracted into indidivual parameter parts.
  230. *
  231. * @throws DBALException
  232. */
  233. private static function parseDatabaseUrl(array $params) : array
  234. {
  235. if (! isset($params['url'])) {
  236. return $params;
  237. }
  238. // (pdo_)?sqlite3?:///... => (pdo_)?sqlite3?://localhost/... or else the URL will be invalid
  239. $url = preg_replace('#^((?:pdo_)?sqlite3?):///#', '$1://localhost/', $params['url']);
  240. $url = parse_url($url);
  241. if ($url === false) {
  242. throw new DBALException('Malformed parameter "url".');
  243. }
  244. $url = array_map('rawurldecode', $url);
  245. // If we have a connection URL, we have to unset the default PDO instance connection parameter (if any)
  246. // as we cannot merge connection details from the URL into the PDO instance (URL takes precedence).
  247. unset($params['pdo']);
  248. $params = self::parseDatabaseUrlScheme($url, $params);
  249. if (isset($url['host'])) {
  250. $params['host'] = $url['host'];
  251. }
  252. if (isset($url['port'])) {
  253. $params['port'] = $url['port'];
  254. }
  255. if (isset($url['user'])) {
  256. $params['user'] = $url['user'];
  257. }
  258. if (isset($url['pass'])) {
  259. $params['password'] = $url['pass'];
  260. }
  261. $params = self::parseDatabaseUrlPath($url, $params);
  262. $params = self::parseDatabaseUrlQuery($url, $params);
  263. return $params;
  264. }
  265. /**
  266. * Parses the given connection URL and resolves the given connection parameters.
  267. *
  268. * Assumes that the connection URL scheme is already parsed and resolved into the given connection parameters
  269. * via {@link parseDatabaseUrlScheme}.
  270. *
  271. * @see parseDatabaseUrlScheme
  272. *
  273. * @param mixed[] $url The URL parts to evaluate.
  274. * @param mixed[] $params The connection parameters to resolve.
  275. *
  276. * @return mixed[] The resolved connection parameters.
  277. */
  278. private static function parseDatabaseUrlPath(array $url, array $params) : array
  279. {
  280. if (! isset($url['path'])) {
  281. return $params;
  282. }
  283. $url['path'] = self::normalizeDatabaseUrlPath($url['path']);
  284. // If we do not have a known DBAL driver, we do not know any connection URL path semantics to evaluate
  285. // and therefore treat the path as regular DBAL connection URL path.
  286. if (! isset($params['driver'])) {
  287. return self::parseRegularDatabaseUrlPath($url, $params);
  288. }
  289. if (strpos($params['driver'], 'sqlite') !== false) {
  290. return self::parseSqliteDatabaseUrlPath($url, $params);
  291. }
  292. return self::parseRegularDatabaseUrlPath($url, $params);
  293. }
  294. /**
  295. * Parses the query part of the given connection URL and resolves the given connection parameters.
  296. *
  297. * @param mixed[] $url The connection URL parts to evaluate.
  298. * @param mixed[] $params The connection parameters to resolve.
  299. *
  300. * @return mixed[] The resolved connection parameters.
  301. */
  302. private static function parseDatabaseUrlQuery(array $url, array $params) : array
  303. {
  304. if (! isset($url['query'])) {
  305. return $params;
  306. }
  307. $query = [];
  308. parse_str($url['query'], $query); // simply ingest query as extra params, e.g. charset or sslmode
  309. return array_merge($params, $query); // parse_str wipes existing array elements
  310. }
  311. /**
  312. * Parses the given regular connection URL and resolves the given connection parameters.
  313. *
  314. * Assumes that the "path" URL part is already normalized via {@link normalizeDatabaseUrlPath}.
  315. *
  316. * @see normalizeDatabaseUrlPath
  317. *
  318. * @param mixed[] $url The regular connection URL parts to evaluate.
  319. * @param mixed[] $params The connection parameters to resolve.
  320. *
  321. * @return mixed[] The resolved connection parameters.
  322. */
  323. private static function parseRegularDatabaseUrlPath(array $url, array $params) : array
  324. {
  325. $params['dbname'] = $url['path'];
  326. return $params;
  327. }
  328. /**
  329. * Parses the given SQLite connection URL and resolves the given connection parameters.
  330. *
  331. * Assumes that the "path" URL part is already normalized via {@link normalizeDatabaseUrlPath}.
  332. *
  333. * @see normalizeDatabaseUrlPath
  334. *
  335. * @param mixed[] $url The SQLite connection URL parts to evaluate.
  336. * @param mixed[] $params The connection parameters to resolve.
  337. *
  338. * @return mixed[] The resolved connection parameters.
  339. */
  340. private static function parseSqliteDatabaseUrlPath(array $url, array $params) : array
  341. {
  342. if ($url['path'] === ':memory:') {
  343. $params['memory'] = true;
  344. return $params;
  345. }
  346. $params['path'] = $url['path']; // pdo_sqlite driver uses 'path' instead of 'dbname' key
  347. return $params;
  348. }
  349. /**
  350. * Parses the scheme part from given connection URL and resolves the given connection parameters.
  351. *
  352. * @param mixed[] $url The connection URL parts to evaluate.
  353. * @param mixed[] $params The connection parameters to resolve.
  354. *
  355. * @return mixed[] The resolved connection parameters.
  356. *
  357. * @throws DBALException If parsing failed or resolution is not possible.
  358. */
  359. private static function parseDatabaseUrlScheme(array $url, array $params) : array
  360. {
  361. if (isset($url['scheme'])) {
  362. // The requested driver from the URL scheme takes precedence
  363. // over the default custom driver from the connection parameters (if any).
  364. unset($params['driverClass']);
  365. // URL schemes must not contain underscores, but dashes are ok
  366. $driver = str_replace('-', '_', $url['scheme']);
  367. // The requested driver from the URL scheme takes precedence over the
  368. // default driver from the connection parameters. If the driver is
  369. // an alias (e.g. "postgres"), map it to the actual name ("pdo-pgsql").
  370. // Otherwise, let checkParams decide later if the driver exists.
  371. $params['driver'] = self::$driverSchemeAliases[$driver] ?? $driver;
  372. return $params;
  373. }
  374. // If a schemeless connection URL is given, we require a default driver or default custom driver
  375. // as connection parameter.
  376. if (! isset($params['driverClass']) && ! isset($params['driver'])) {
  377. throw DBALException::driverRequired($params['url']);
  378. }
  379. return $params;
  380. }
  381. }