DatabaseManager.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444
  1. <?php
  2. namespace Illuminate\Database;
  3. use Doctrine\DBAL\Types\Type;
  4. use Illuminate\Database\Connectors\ConnectionFactory;
  5. use Illuminate\Support\Arr;
  6. use Illuminate\Support\ConfigurationUrlParser;
  7. use Illuminate\Support\Str;
  8. use InvalidArgumentException;
  9. use PDO;
  10. use RuntimeException;
  11. /**
  12. * @mixin \Illuminate\Database\Connection
  13. */
  14. class DatabaseManager implements ConnectionResolverInterface
  15. {
  16. /**
  17. * The application instance.
  18. *
  19. * @var \Illuminate\Contracts\Foundation\Application
  20. */
  21. protected $app;
  22. /**
  23. * The database connection factory instance.
  24. *
  25. * @var \Illuminate\Database\Connectors\ConnectionFactory
  26. */
  27. protected $factory;
  28. /**
  29. * The active connection instances.
  30. *
  31. * @var array
  32. */
  33. protected $connections = [];
  34. /**
  35. * The custom connection resolvers.
  36. *
  37. * @var array
  38. */
  39. protected $extensions = [];
  40. /**
  41. * The callback to be executed to reconnect to a database.
  42. *
  43. * @var callable
  44. */
  45. protected $reconnector;
  46. /**
  47. * The custom Doctrine column types.
  48. *
  49. * @var array
  50. */
  51. protected $doctrineTypes = [];
  52. /**
  53. * Create a new database manager instance.
  54. *
  55. * @param \Illuminate\Contracts\Foundation\Application $app
  56. * @param \Illuminate\Database\Connectors\ConnectionFactory $factory
  57. * @return void
  58. */
  59. public function __construct($app, ConnectionFactory $factory)
  60. {
  61. $this->app = $app;
  62. $this->factory = $factory;
  63. $this->reconnector = function ($connection) {
  64. $this->reconnect($connection->getNameWithReadWriteType());
  65. };
  66. }
  67. /**
  68. * Get a database connection instance.
  69. *
  70. * @param string|null $name
  71. * @return \Illuminate\Database\Connection
  72. */
  73. public function connection($name = null)
  74. {
  75. [$database, $type] = $this->parseConnectionName($name);
  76. $name = $name ?: $database;
  77. // If we haven't created this connection, we'll create it based on the config
  78. // provided in the application. Once we've created the connections we will
  79. // set the "fetch mode" for PDO which determines the query return types.
  80. if (! isset($this->connections[$name])) {
  81. $this->connections[$name] = $this->configure(
  82. $this->makeConnection($database), $type
  83. );
  84. }
  85. return $this->connections[$name];
  86. }
  87. /**
  88. * Parse the connection into an array of the name and read / write type.
  89. *
  90. * @param string $name
  91. * @return array
  92. */
  93. protected function parseConnectionName($name)
  94. {
  95. $name = $name ?: $this->getDefaultConnection();
  96. return Str::endsWith($name, ['::read', '::write'])
  97. ? explode('::', $name, 2) : [$name, null];
  98. }
  99. /**
  100. * Make the database connection instance.
  101. *
  102. * @param string $name
  103. * @return \Illuminate\Database\Connection
  104. */
  105. protected function makeConnection($name)
  106. {
  107. $config = $this->configuration($name);
  108. // First we will check by the connection name to see if an extension has been
  109. // registered specifically for that connection. If it has we will call the
  110. // Closure and pass it the config allowing it to resolve the connection.
  111. if (isset($this->extensions[$name])) {
  112. return call_user_func($this->extensions[$name], $config, $name);
  113. }
  114. // Next we will check to see if an extension has been registered for a driver
  115. // and will call the Closure if so, which allows us to have a more generic
  116. // resolver for the drivers themselves which applies to all connections.
  117. if (isset($this->extensions[$driver = $config['driver']])) {
  118. return call_user_func($this->extensions[$driver], $config, $name);
  119. }
  120. return $this->factory->make($config, $name);
  121. }
  122. /**
  123. * Get the configuration for a connection.
  124. *
  125. * @param string $name
  126. * @return array
  127. *
  128. * @throws \InvalidArgumentException
  129. */
  130. protected function configuration($name)
  131. {
  132. $name = $name ?: $this->getDefaultConnection();
  133. // To get the database connection configuration, we will just pull each of the
  134. // connection configurations and get the configurations for the given name.
  135. // If the configuration doesn't exist, we'll throw an exception and bail.
  136. $connections = $this->app['config']['database.connections'];
  137. if (is_null($config = Arr::get($connections, $name))) {
  138. throw new InvalidArgumentException("Database connection [{$name}] not configured.");
  139. }
  140. return (new ConfigurationUrlParser)
  141. ->parseConfiguration($config);
  142. }
  143. /**
  144. * Prepare the database connection instance.
  145. *
  146. * @param \Illuminate\Database\Connection $connection
  147. * @param string $type
  148. * @return \Illuminate\Database\Connection
  149. */
  150. protected function configure(Connection $connection, $type)
  151. {
  152. $connection = $this->setPdoForType($connection, $type)->setReadWriteType($type);
  153. // First we'll set the fetch mode and a few other dependencies of the database
  154. // connection. This method basically just configures and prepares it to get
  155. // used by the application. Once we're finished we'll return it back out.
  156. if ($this->app->bound('events')) {
  157. $connection->setEventDispatcher($this->app['events']);
  158. }
  159. if ($this->app->bound('db.transactions')) {
  160. $connection->setTransactionManager($this->app['db.transactions']);
  161. }
  162. // Here we'll set a reconnector callback. This reconnector can be any callable
  163. // so we will set a Closure to reconnect from this manager with the name of
  164. // the connection, which will allow us to reconnect from the connections.
  165. $connection->setReconnector($this->reconnector);
  166. $this->registerConfiguredDoctrineTypes($connection);
  167. return $connection;
  168. }
  169. /**
  170. * Prepare the read / write mode for database connection instance.
  171. *
  172. * @param \Illuminate\Database\Connection $connection
  173. * @param string|null $type
  174. * @return \Illuminate\Database\Connection
  175. */
  176. protected function setPdoForType(Connection $connection, $type = null)
  177. {
  178. if ($type === 'read') {
  179. $connection->setPdo($connection->getReadPdo());
  180. } elseif ($type === 'write') {
  181. $connection->setReadPdo($connection->getPdo());
  182. }
  183. return $connection;
  184. }
  185. /**
  186. * Register custom Doctrine types with the connection.
  187. *
  188. * @param \Illuminate\Database\Connection $connection
  189. * @return void
  190. */
  191. protected function registerConfiguredDoctrineTypes(Connection $connection): void
  192. {
  193. foreach ($this->app['config']->get('database.dbal.types', []) as $name => $class) {
  194. $this->registerDoctrineType($class, $name, $name);
  195. }
  196. foreach ($this->doctrineTypes as $name => [$type, $class]) {
  197. $connection->registerDoctrineType($class, $name, $type);
  198. }
  199. }
  200. /**
  201. * Register a custom Doctrine type.
  202. *
  203. * @param string $class
  204. * @param string $name
  205. * @param string $type
  206. * @return void
  207. *
  208. * @throws \Doctrine\DBAL\DBALException
  209. * @throws \RuntimeException
  210. */
  211. public function registerDoctrineType(string $class, string $name, string $type): void
  212. {
  213. if (! class_exists('Doctrine\DBAL\Connection')) {
  214. throw new RuntimeException(
  215. 'Registering a custom Doctrine type requires Doctrine DBAL (doctrine/dbal).'
  216. );
  217. }
  218. if (! Type::hasType($name)) {
  219. Type::addType($name, $class);
  220. }
  221. $this->doctrineTypes[$name] = [$type, $class];
  222. }
  223. /**
  224. * Disconnect from the given database and remove from local cache.
  225. *
  226. * @param string|null $name
  227. * @return void
  228. */
  229. public function purge($name = null)
  230. {
  231. $name = $name ?: $this->getDefaultConnection();
  232. $this->disconnect($name);
  233. unset($this->connections[$name]);
  234. }
  235. /**
  236. * Disconnect from the given database.
  237. *
  238. * @param string|null $name
  239. * @return void
  240. */
  241. public function disconnect($name = null)
  242. {
  243. if (isset($this->connections[$name = $name ?: $this->getDefaultConnection()])) {
  244. $this->connections[$name]->disconnect();
  245. }
  246. }
  247. /**
  248. * Reconnect to the given database.
  249. *
  250. * @param string|null $name
  251. * @return \Illuminate\Database\Connection
  252. */
  253. public function reconnect($name = null)
  254. {
  255. $this->disconnect($name = $name ?: $this->getDefaultConnection());
  256. if (! isset($this->connections[$name])) {
  257. return $this->connection($name);
  258. }
  259. return $this->refreshPdoConnections($name);
  260. }
  261. /**
  262. * Set the default database connection for the callback execution.
  263. *
  264. * @param string $name
  265. * @param callable $callback
  266. * @return mixed
  267. */
  268. public function usingConnection($name, callable $callback)
  269. {
  270. $previousName = $this->getDefaultConnection();
  271. $this->setDefaultConnection($name);
  272. return tap($callback(), function () use ($previousName) {
  273. $this->setDefaultConnection($previousName);
  274. });
  275. }
  276. /**
  277. * Refresh the PDO connections on a given connection.
  278. *
  279. * @param string $name
  280. * @return \Illuminate\Database\Connection
  281. */
  282. protected function refreshPdoConnections($name)
  283. {
  284. [$database, $type] = $this->parseConnectionName($name);
  285. $fresh = $this->configure(
  286. $this->makeConnection($database), $type
  287. );
  288. return $this->connections[$name]
  289. ->setPdo($fresh->getRawPdo())
  290. ->setReadPdo($fresh->getRawReadPdo());
  291. }
  292. /**
  293. * Get the default connection name.
  294. *
  295. * @return string
  296. */
  297. public function getDefaultConnection()
  298. {
  299. return $this->app['config']['database.default'];
  300. }
  301. /**
  302. * Set the default connection name.
  303. *
  304. * @param string $name
  305. * @return void
  306. */
  307. public function setDefaultConnection($name)
  308. {
  309. $this->app['config']['database.default'] = $name;
  310. }
  311. /**
  312. * Get all of the support drivers.
  313. *
  314. * @return array
  315. */
  316. public function supportedDrivers()
  317. {
  318. return ['mysql', 'pgsql', 'sqlite', 'sqlsrv'];
  319. }
  320. /**
  321. * Get all of the drivers that are actually available.
  322. *
  323. * @return array
  324. */
  325. public function availableDrivers()
  326. {
  327. return array_intersect(
  328. $this->supportedDrivers(),
  329. str_replace('dblib', 'sqlsrv', PDO::getAvailableDrivers())
  330. );
  331. }
  332. /**
  333. * Register an extension connection resolver.
  334. *
  335. * @param string $name
  336. * @param callable $resolver
  337. * @return void
  338. */
  339. public function extend($name, callable $resolver)
  340. {
  341. $this->extensions[$name] = $resolver;
  342. }
  343. /**
  344. * Return all of the created connections.
  345. *
  346. * @return array
  347. */
  348. public function getConnections()
  349. {
  350. return $this->connections;
  351. }
  352. /**
  353. * Set the database reconnector callback.
  354. *
  355. * @param callable $reconnector
  356. * @return void
  357. */
  358. public function setReconnector(callable $reconnector)
  359. {
  360. $this->reconnector = $reconnector;
  361. }
  362. /**
  363. * Set the application instance used by the manager.
  364. *
  365. * @param \Illuminate\Contracts\Foundation\Application $app
  366. * @return $this
  367. */
  368. public function setApplication($app)
  369. {
  370. $this->app = $app;
  371. return $this;
  372. }
  373. /**
  374. * Dynamically pass methods to the default connection.
  375. *
  376. * @param string $method
  377. * @param array $parameters
  378. * @return mixed
  379. */
  380. public function __call($method, $parameters)
  381. {
  382. return $this->connection()->$method(...$parameters);
  383. }
  384. }