DatabaseManager.php 9.5 KB

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