DatabaseManager.php 13 KB

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