Connection.php 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476
  1. <?php
  2. namespace Illuminate\Database;
  3. use Closure;
  4. use DateTimeInterface;
  5. use Doctrine\DBAL\Connection as DoctrineConnection;
  6. use Doctrine\DBAL\Types\Type;
  7. use Exception;
  8. use Illuminate\Contracts\Events\Dispatcher;
  9. use Illuminate\Database\Events\QueryExecuted;
  10. use Illuminate\Database\Events\StatementPrepared;
  11. use Illuminate\Database\Events\TransactionBeginning;
  12. use Illuminate\Database\Events\TransactionCommitted;
  13. use Illuminate\Database\Events\TransactionRolledBack;
  14. use Illuminate\Database\Query\Builder as QueryBuilder;
  15. use Illuminate\Database\Query\Expression;
  16. use Illuminate\Database\Query\Grammars\Grammar as QueryGrammar;
  17. use Illuminate\Database\Query\Processors\Processor;
  18. use Illuminate\Database\Schema\Builder as SchemaBuilder;
  19. use Illuminate\Support\Arr;
  20. use LogicException;
  21. use PDO;
  22. use PDOStatement;
  23. use RuntimeException;
  24. class Connection implements ConnectionInterface
  25. {
  26. use DetectsConcurrencyErrors,
  27. DetectsLostConnections,
  28. Concerns\ManagesTransactions;
  29. /**
  30. * The active PDO connection.
  31. *
  32. * @var \PDO|\Closure
  33. */
  34. protected $pdo;
  35. /**
  36. * The active PDO connection used for reads.
  37. *
  38. * @var \PDO|\Closure
  39. */
  40. protected $readPdo;
  41. /**
  42. * The name of the connected database.
  43. *
  44. * @var string
  45. */
  46. protected $database;
  47. /**
  48. * The type of the connection.
  49. *
  50. * @var string|null
  51. */
  52. protected $readWriteType;
  53. /**
  54. * The table prefix for the connection.
  55. *
  56. * @var string
  57. */
  58. protected $tablePrefix = '';
  59. /**
  60. * The database connection configuration options.
  61. *
  62. * @var array
  63. */
  64. protected $config = [];
  65. /**
  66. * The reconnector instance for the connection.
  67. *
  68. * @var callable
  69. */
  70. protected $reconnector;
  71. /**
  72. * The query grammar implementation.
  73. *
  74. * @var \Illuminate\Database\Query\Grammars\Grammar
  75. */
  76. protected $queryGrammar;
  77. /**
  78. * The schema grammar implementation.
  79. *
  80. * @var \Illuminate\Database\Schema\Grammars\Grammar
  81. */
  82. protected $schemaGrammar;
  83. /**
  84. * The query post processor implementation.
  85. *
  86. * @var \Illuminate\Database\Query\Processors\Processor
  87. */
  88. protected $postProcessor;
  89. /**
  90. * The event dispatcher instance.
  91. *
  92. * @var \Illuminate\Contracts\Events\Dispatcher
  93. */
  94. protected $events;
  95. /**
  96. * The default fetch mode of the connection.
  97. *
  98. * @var int
  99. */
  100. protected $fetchMode = PDO::FETCH_OBJ;
  101. /**
  102. * The number of active transactions.
  103. *
  104. * @var int
  105. */
  106. protected $transactions = 0;
  107. /**
  108. * The transaction manager instance.
  109. *
  110. * @var \Illuminate\Database\DatabaseTransactionsManager
  111. */
  112. protected $transactionsManager;
  113. /**
  114. * Indicates if changes have been made to the database.
  115. *
  116. * @var bool
  117. */
  118. protected $recordsModified = false;
  119. /**
  120. * Indicates if the connection should use the "write" PDO connection.
  121. *
  122. * @var bool
  123. */
  124. protected $readOnWriteConnection = false;
  125. /**
  126. * All of the queries run against the connection.
  127. *
  128. * @var array
  129. */
  130. protected $queryLog = [];
  131. /**
  132. * Indicates whether queries are being logged.
  133. *
  134. * @var bool
  135. */
  136. protected $loggingQueries = false;
  137. /**
  138. * Indicates if the connection is in a "dry run".
  139. *
  140. * @var bool
  141. */
  142. protected $pretending = false;
  143. /**
  144. * All of the callbacks that should be invoked before a query is executed.
  145. *
  146. * @var array
  147. */
  148. protected $beforeExecutingCallbacks = [];
  149. /**
  150. * The instance of Doctrine connection.
  151. *
  152. * @var \Doctrine\DBAL\Connection
  153. */
  154. protected $doctrineConnection;
  155. /**
  156. * Type mappings that should be registered with new Doctrine connections.
  157. *
  158. * @var array
  159. */
  160. protected $doctrineTypeMappings = [];
  161. /**
  162. * The connection resolvers.
  163. *
  164. * @var array
  165. */
  166. protected static $resolvers = [];
  167. /**
  168. * Create a new database connection instance.
  169. *
  170. * @param \PDO|\Closure $pdo
  171. * @param string $database
  172. * @param string $tablePrefix
  173. * @param array $config
  174. * @return void
  175. */
  176. public function __construct($pdo, $database = '', $tablePrefix = '', array $config = [])
  177. {
  178. $this->pdo = $pdo;
  179. // First we will setup the default properties. We keep track of the DB
  180. // name we are connected to since it is needed when some reflective
  181. // type commands are run such as checking whether a table exists.
  182. $this->database = $database;
  183. $this->tablePrefix = $tablePrefix;
  184. $this->config = $config;
  185. // We need to initialize a query grammar and the query post processors
  186. // which are both very important parts of the database abstractions
  187. // so we initialize these to their default values while starting.
  188. $this->useDefaultQueryGrammar();
  189. $this->useDefaultPostProcessor();
  190. }
  191. /**
  192. * Set the query grammar to the default implementation.
  193. *
  194. * @return void
  195. */
  196. public function useDefaultQueryGrammar()
  197. {
  198. $this->queryGrammar = $this->getDefaultQueryGrammar();
  199. }
  200. /**
  201. * Get the default query grammar instance.
  202. *
  203. * @return \Illuminate\Database\Query\Grammars\Grammar
  204. */
  205. protected function getDefaultQueryGrammar()
  206. {
  207. return new QueryGrammar;
  208. }
  209. /**
  210. * Set the schema grammar to the default implementation.
  211. *
  212. * @return void
  213. */
  214. public function useDefaultSchemaGrammar()
  215. {
  216. $this->schemaGrammar = $this->getDefaultSchemaGrammar();
  217. }
  218. /**
  219. * Get the default schema grammar instance.
  220. *
  221. * @return \Illuminate\Database\Schema\Grammars\Grammar
  222. */
  223. protected function getDefaultSchemaGrammar()
  224. {
  225. //
  226. }
  227. /**
  228. * Set the query post processor to the default implementation.
  229. *
  230. * @return void
  231. */
  232. public function useDefaultPostProcessor()
  233. {
  234. $this->postProcessor = $this->getDefaultPostProcessor();
  235. }
  236. /**
  237. * Get the default post processor instance.
  238. *
  239. * @return \Illuminate\Database\Query\Processors\Processor
  240. */
  241. protected function getDefaultPostProcessor()
  242. {
  243. return new Processor;
  244. }
  245. /**
  246. * Get a schema builder instance for the connection.
  247. *
  248. * @return \Illuminate\Database\Schema\Builder
  249. */
  250. public function getSchemaBuilder()
  251. {
  252. if (is_null($this->schemaGrammar)) {
  253. $this->useDefaultSchemaGrammar();
  254. }
  255. return new SchemaBuilder($this);
  256. }
  257. /**
  258. * Begin a fluent query against a database table.
  259. *
  260. * @param \Closure|\Illuminate\Database\Query\Builder|string $table
  261. * @param string|null $as
  262. * @return \Illuminate\Database\Query\Builder
  263. */
  264. public function table($table, $as = null)
  265. {
  266. return $this->query()->from($table, $as);
  267. }
  268. /**
  269. * Get a new query builder instance.
  270. *
  271. * @return \Illuminate\Database\Query\Builder
  272. */
  273. public function query()
  274. {
  275. return new QueryBuilder(
  276. $this, $this->getQueryGrammar(), $this->getPostProcessor()
  277. );
  278. }
  279. /**
  280. * Run a select statement and return a single result.
  281. *
  282. * @param string $query
  283. * @param array $bindings
  284. * @param bool $useReadPdo
  285. * @return mixed
  286. */
  287. public function selectOne($query, $bindings = [], $useReadPdo = true)
  288. {
  289. $records = $this->select($query, $bindings, $useReadPdo);
  290. return array_shift($records);
  291. }
  292. /**
  293. * Run a select statement against the database.
  294. *
  295. * @param string $query
  296. * @param array $bindings
  297. * @return array
  298. */
  299. public function selectFromWriteConnection($query, $bindings = [])
  300. {
  301. return $this->select($query, $bindings, false);
  302. }
  303. /**
  304. * Run a select statement against the database.
  305. *
  306. * @param string $query
  307. * @param array $bindings
  308. * @param bool $useReadPdo
  309. * @return array
  310. */
  311. public function select($query, $bindings = [], $useReadPdo = true)
  312. {
  313. return $this->run($query, $bindings, function ($query, $bindings) use ($useReadPdo) {
  314. if ($this->pretending()) {
  315. return [];
  316. }
  317. // For select statements, we'll simply execute the query and return an array
  318. // of the database result set. Each element in the array will be a single
  319. // row from the database table, and will either be an array or objects.
  320. $statement = $this->prepared(
  321. $this->getPdoForSelect($useReadPdo)->prepare($query)
  322. );
  323. $this->bindValues($statement, $this->prepareBindings($bindings));
  324. $statement->execute();
  325. return $statement->fetchAll();
  326. });
  327. }
  328. /**
  329. * Run a select statement against the database and returns a generator.
  330. *
  331. * @param string $query
  332. * @param array $bindings
  333. * @param bool $useReadPdo
  334. * @return \Generator
  335. */
  336. public function cursor($query, $bindings = [], $useReadPdo = true)
  337. {
  338. $statement = $this->run($query, $bindings, function ($query, $bindings) use ($useReadPdo) {
  339. if ($this->pretending()) {
  340. return [];
  341. }
  342. // First we will create a statement for the query. Then, we will set the fetch
  343. // mode and prepare the bindings for the query. Once that's done we will be
  344. // ready to execute the query against the database and return the cursor.
  345. $statement = $this->prepared($this->getPdoForSelect($useReadPdo)
  346. ->prepare($query));
  347. $this->bindValues(
  348. $statement, $this->prepareBindings($bindings)
  349. );
  350. // Next, we'll execute the query against the database and return the statement
  351. // so we can return the cursor. The cursor will use a PHP generator to give
  352. // back one row at a time without using a bunch of memory to render them.
  353. $statement->execute();
  354. return $statement;
  355. });
  356. while ($record = $statement->fetch()) {
  357. yield $record;
  358. }
  359. }
  360. /**
  361. * Configure the PDO prepared statement.
  362. *
  363. * @param \PDOStatement $statement
  364. * @return \PDOStatement
  365. */
  366. protected function prepared(PDOStatement $statement)
  367. {
  368. $statement->setFetchMode($this->fetchMode);
  369. $this->event(new StatementPrepared(
  370. $this, $statement
  371. ));
  372. return $statement;
  373. }
  374. /**
  375. * Get the PDO connection to use for a select query.
  376. *
  377. * @param bool $useReadPdo
  378. * @return \PDO
  379. */
  380. protected function getPdoForSelect($useReadPdo = true)
  381. {
  382. return $useReadPdo ? $this->getReadPdo() : $this->getPdo();
  383. }
  384. /**
  385. * Run an insert statement against the database.
  386. *
  387. * @param string $query
  388. * @param array $bindings
  389. * @return bool
  390. */
  391. public function insert($query, $bindings = [])
  392. {
  393. return $this->statement($query, $bindings);
  394. }
  395. /**
  396. * Run an update statement against the database.
  397. *
  398. * @param string $query
  399. * @param array $bindings
  400. * @return int
  401. */
  402. public function update($query, $bindings = [])
  403. {
  404. return $this->affectingStatement($query, $bindings);
  405. }
  406. /**
  407. * Run a delete statement against the database.
  408. *
  409. * @param string $query
  410. * @param array $bindings
  411. * @return int
  412. */
  413. public function delete($query, $bindings = [])
  414. {
  415. return $this->affectingStatement($query, $bindings);
  416. }
  417. /**
  418. * Execute an SQL statement and return the boolean result.
  419. *
  420. * @param string $query
  421. * @param array $bindings
  422. * @return bool
  423. */
  424. public function statement($query, $bindings = [])
  425. {
  426. return $this->run($query, $bindings, function ($query, $bindings) {
  427. if ($this->pretending()) {
  428. return true;
  429. }
  430. $statement = $this->getPdo()->prepare($query);
  431. $this->bindValues($statement, $this->prepareBindings($bindings));
  432. $this->recordsHaveBeenModified();
  433. return $statement->execute();
  434. });
  435. }
  436. /**
  437. * Run an SQL statement and get the number of rows affected.
  438. *
  439. * @param string $query
  440. * @param array $bindings
  441. * @return int
  442. */
  443. public function affectingStatement($query, $bindings = [])
  444. {
  445. return $this->run($query, $bindings, function ($query, $bindings) {
  446. if ($this->pretending()) {
  447. return 0;
  448. }
  449. // For update or delete statements, we want to get the number of rows affected
  450. // by the statement and return that back to the developer. We'll first need
  451. // to execute the statement and then we'll use PDO to fetch the affected.
  452. $statement = $this->getPdo()->prepare($query);
  453. $this->bindValues($statement, $this->prepareBindings($bindings));
  454. $statement->execute();
  455. $this->recordsHaveBeenModified(
  456. ($count = $statement->rowCount()) > 0
  457. );
  458. return $count;
  459. });
  460. }
  461. /**
  462. * Run a raw, unprepared query against the PDO connection.
  463. *
  464. * @param string $query
  465. * @return bool
  466. */
  467. public function unprepared($query)
  468. {
  469. return $this->run($query, [], function ($query) {
  470. if ($this->pretending()) {
  471. return true;
  472. }
  473. $this->recordsHaveBeenModified(
  474. $change = $this->getPdo()->exec($query) !== false
  475. );
  476. return $change;
  477. });
  478. }
  479. /**
  480. * Execute the given callback in "dry run" mode.
  481. *
  482. * @param \Closure $callback
  483. * @return array
  484. */
  485. public function pretend(Closure $callback)
  486. {
  487. return $this->withFreshQueryLog(function () use ($callback) {
  488. $this->pretending = true;
  489. // Basically to make the database connection "pretend", we will just return
  490. // the default values for all the query methods, then we will return an
  491. // array of queries that were "executed" within the Closure callback.
  492. $callback($this);
  493. $this->pretending = false;
  494. return $this->queryLog;
  495. });
  496. }
  497. /**
  498. * Execute the given callback in "dry run" mode.
  499. *
  500. * @param \Closure $callback
  501. * @return array
  502. */
  503. protected function withFreshQueryLog($callback)
  504. {
  505. $loggingQueries = $this->loggingQueries;
  506. // First we will back up the value of the logging queries property and then
  507. // we'll be ready to run callbacks. This query log will also get cleared
  508. // so we will have a new log of all the queries that are executed now.
  509. $this->enableQueryLog();
  510. $this->queryLog = [];
  511. // Now we'll execute this callback and capture the result. Once it has been
  512. // executed we will restore the value of query logging and give back the
  513. // value of the callback so the original callers can have the results.
  514. $result = $callback();
  515. $this->loggingQueries = $loggingQueries;
  516. return $result;
  517. }
  518. /**
  519. * Bind values to their parameters in the given statement.
  520. *
  521. * @param \PDOStatement $statement
  522. * @param array $bindings
  523. * @return void
  524. */
  525. public function bindValues($statement, $bindings)
  526. {
  527. foreach ($bindings as $key => $value) {
  528. $statement->bindValue(
  529. is_string($key) ? $key : $key + 1,
  530. $value,
  531. is_int($value) ? PDO::PARAM_INT : PDO::PARAM_STR
  532. );
  533. }
  534. }
  535. /**
  536. * Prepare the query bindings for execution.
  537. *
  538. * @param array $bindings
  539. * @return array
  540. */
  541. public function prepareBindings(array $bindings)
  542. {
  543. $grammar = $this->getQueryGrammar();
  544. foreach ($bindings as $key => $value) {
  545. // We need to transform all instances of DateTimeInterface into the actual
  546. // date string. Each query grammar maintains its own date string format
  547. // so we'll just ask the grammar for the format to get from the date.
  548. if ($value instanceof DateTimeInterface) {
  549. $bindings[$key] = $value->format($grammar->getDateFormat());
  550. } elseif (is_bool($value)) {
  551. $bindings[$key] = (int) $value;
  552. }
  553. }
  554. return $bindings;
  555. }
  556. /**
  557. * Run a SQL statement and log its execution context.
  558. *
  559. * @param string $query
  560. * @param array $bindings
  561. * @param \Closure $callback
  562. * @return mixed
  563. *
  564. * @throws \Illuminate\Database\QueryException
  565. */
  566. protected function run($query, $bindings, Closure $callback)
  567. {
  568. foreach ($this->beforeExecutingCallbacks as $beforeExecutingCallback) {
  569. $beforeExecutingCallback($query, $bindings, $this);
  570. }
  571. $this->reconnectIfMissingConnection();
  572. $start = microtime(true);
  573. // Here we will run this query. If an exception occurs we'll determine if it was
  574. // caused by a connection that has been lost. If that is the cause, we'll try
  575. // to re-establish connection and re-run the query with a fresh connection.
  576. try {
  577. $result = $this->runQueryCallback($query, $bindings, $callback);
  578. } catch (QueryException $e) {
  579. $result = $this->handleQueryException(
  580. $e, $query, $bindings, $callback
  581. );
  582. }
  583. // Once we have run the query we will calculate the time that it took to run and
  584. // then log the query, bindings, and execution time so we will report them on
  585. // the event that the developer needs them. We'll log time in milliseconds.
  586. $this->logQuery(
  587. $query, $bindings, $this->getElapsedTime($start)
  588. );
  589. return $result;
  590. }
  591. /**
  592. * Run a SQL statement.
  593. *
  594. * @param string $query
  595. * @param array $bindings
  596. * @param \Closure $callback
  597. * @return mixed
  598. *
  599. * @throws \Illuminate\Database\QueryException
  600. */
  601. protected function runQueryCallback($query, $bindings, Closure $callback)
  602. {
  603. // To execute the statement, we'll simply call the callback, which will actually
  604. // run the SQL against the PDO connection. Then we can calculate the time it
  605. // took to execute and log the query SQL, bindings and time in our memory.
  606. try {
  607. return $callback($query, $bindings);
  608. }
  609. // If an exception occurs when attempting to run a query, we'll format the error
  610. // message to include the bindings with SQL, which will make this exception a
  611. // lot more helpful to the developer instead of just the database's errors.
  612. catch (Exception $e) {
  613. throw new QueryException(
  614. $query, $this->prepareBindings($bindings), $e
  615. );
  616. }
  617. }
  618. /**
  619. * Log a query in the connection's query log.
  620. *
  621. * @param string $query
  622. * @param array $bindings
  623. * @param float|null $time
  624. * @return void
  625. */
  626. public function logQuery($query, $bindings, $time = null)
  627. {
  628. $this->event(new QueryExecuted($query, $bindings, $time, $this));
  629. if ($this->loggingQueries) {
  630. $this->queryLog[] = compact('query', 'bindings', 'time');
  631. }
  632. }
  633. /**
  634. * Get the elapsed time since a given starting point.
  635. *
  636. * @param int $start
  637. * @return float
  638. */
  639. protected function getElapsedTime($start)
  640. {
  641. return round((microtime(true) - $start) * 1000, 2);
  642. }
  643. /**
  644. * Handle a query exception.
  645. *
  646. * @param \Illuminate\Database\QueryException $e
  647. * @param string $query
  648. * @param array $bindings
  649. * @param \Closure $callback
  650. * @return mixed
  651. *
  652. * @throws \Illuminate\Database\QueryException
  653. */
  654. protected function handleQueryException(QueryException $e, $query, $bindings, Closure $callback)
  655. {
  656. if ($this->transactions >= 1) {
  657. throw $e;
  658. }
  659. return $this->tryAgainIfCausedByLostConnection(
  660. $e, $query, $bindings, $callback
  661. );
  662. }
  663. /**
  664. * Handle a query exception that occurred during query execution.
  665. *
  666. * @param \Illuminate\Database\QueryException $e
  667. * @param string $query
  668. * @param array $bindings
  669. * @param \Closure $callback
  670. * @return mixed
  671. *
  672. * @throws \Illuminate\Database\QueryException
  673. */
  674. protected function tryAgainIfCausedByLostConnection(QueryException $e, $query, $bindings, Closure $callback)
  675. {
  676. if ($this->causedByLostConnection($e->getPrevious())) {
  677. $this->reconnect();
  678. return $this->runQueryCallback($query, $bindings, $callback);
  679. }
  680. throw $e;
  681. }
  682. /**
  683. * Reconnect to the database.
  684. *
  685. * @return void
  686. *
  687. * @throws \LogicException
  688. */
  689. public function reconnect()
  690. {
  691. if (is_callable($this->reconnector)) {
  692. $this->doctrineConnection = null;
  693. return call_user_func($this->reconnector, $this);
  694. }
  695. throw new LogicException('Lost connection and no reconnector available.');
  696. }
  697. /**
  698. * Reconnect to the database if a PDO connection is missing.
  699. *
  700. * @return void
  701. */
  702. protected function reconnectIfMissingConnection()
  703. {
  704. if (is_null($this->pdo)) {
  705. $this->reconnect();
  706. }
  707. }
  708. /**
  709. * Disconnect from the underlying PDO connection.
  710. *
  711. * @return void
  712. */
  713. public function disconnect()
  714. {
  715. $this->setPdo(null)->setReadPdo(null);
  716. $this->doctrineConnection = null;
  717. }
  718. /**
  719. * Register a hook to be run just before a database query is executed.
  720. *
  721. * @param \Closure $callback
  722. * @return $this
  723. */
  724. public function beforeExecuting(Closure $callback)
  725. {
  726. $this->beforeExecutingCallbacks[] = $callback;
  727. return $this;
  728. }
  729. /**
  730. * Register a database query listener with the connection.
  731. *
  732. * @param \Closure $callback
  733. * @return void
  734. */
  735. public function listen(Closure $callback)
  736. {
  737. if (isset($this->events)) {
  738. $this->events->listen(Events\QueryExecuted::class, $callback);
  739. }
  740. }
  741. /**
  742. * Fire an event for this connection.
  743. *
  744. * @param string $event
  745. * @return array|null
  746. */
  747. protected function fireConnectionEvent($event)
  748. {
  749. if (! isset($this->events)) {
  750. return;
  751. }
  752. switch ($event) {
  753. case 'beganTransaction':
  754. return $this->events->dispatch(new TransactionBeginning($this));
  755. case 'committed':
  756. return $this->events->dispatch(new TransactionCommitted($this));
  757. case 'rollingBack':
  758. return $this->events->dispatch(new TransactionRolledBack($this));
  759. }
  760. }
  761. /**
  762. * Fire the given event if possible.
  763. *
  764. * @param mixed $event
  765. * @return void
  766. */
  767. protected function event($event)
  768. {
  769. if (isset($this->events)) {
  770. $this->events->dispatch($event);
  771. }
  772. }
  773. /**
  774. * Get a new raw query expression.
  775. *
  776. * @param mixed $value
  777. * @return \Illuminate\Database\Query\Expression
  778. */
  779. public function raw($value)
  780. {
  781. return new Expression($value);
  782. }
  783. /**
  784. * Determine if the database connection has modified any database records.
  785. *
  786. * @return bool
  787. */
  788. public function hasModifiedRecords()
  789. {
  790. return $this->recordsModified;
  791. }
  792. /**
  793. * Indicate if any records have been modified.
  794. *
  795. * @param bool $value
  796. * @return void
  797. */
  798. public function recordsHaveBeenModified($value = true)
  799. {
  800. if (! $this->recordsModified) {
  801. $this->recordsModified = $value;
  802. }
  803. }
  804. /**
  805. * Set the record modification state.
  806. *
  807. * @param bool $value
  808. * @return $this
  809. */
  810. public function setRecordModificationState(bool $value)
  811. {
  812. $this->recordsModified = $value;
  813. return $this;
  814. }
  815. /**
  816. * Reset the record modification state.
  817. *
  818. * @return void
  819. */
  820. public function forgetRecordModificationState()
  821. {
  822. $this->recordsModified = false;
  823. }
  824. /**
  825. * Indicate that the connection should use the write PDO connection for reads.
  826. *
  827. * @param bool $value
  828. * @return $this
  829. */
  830. public function useWriteConnectionWhenReading($value = true)
  831. {
  832. $this->readOnWriteConnection = $value;
  833. return $this;
  834. }
  835. /**
  836. * Is Doctrine available?
  837. *
  838. * @return bool
  839. */
  840. public function isDoctrineAvailable()
  841. {
  842. return class_exists('Doctrine\DBAL\Connection');
  843. }
  844. /**
  845. * Get a Doctrine Schema Column instance.
  846. *
  847. * @param string $table
  848. * @param string $column
  849. * @return \Doctrine\DBAL\Schema\Column
  850. */
  851. public function getDoctrineColumn($table, $column)
  852. {
  853. $schema = $this->getDoctrineSchemaManager();
  854. return $schema->listTableDetails($table)->getColumn($column);
  855. }
  856. /**
  857. * Get the Doctrine DBAL schema manager for the connection.
  858. *
  859. * @return \Doctrine\DBAL\Schema\AbstractSchemaManager
  860. */
  861. public function getDoctrineSchemaManager()
  862. {
  863. $connection = $this->getDoctrineConnection();
  864. // Doctrine v2 expects one parameter while v3 expects two. 2nd will be ignored on v2...
  865. return $this->getDoctrineDriver()->getSchemaManager(
  866. $connection,
  867. $connection->getDatabasePlatform()
  868. );
  869. }
  870. /**
  871. * Get the Doctrine DBAL database connection instance.
  872. *
  873. * @return \Doctrine\DBAL\Connection
  874. */
  875. public function getDoctrineConnection()
  876. {
  877. if (is_null($this->doctrineConnection)) {
  878. $driver = $this->getDoctrineDriver();
  879. $this->doctrineConnection = new DoctrineConnection(array_filter([
  880. 'pdo' => $this->getPdo(),
  881. 'dbname' => $this->getDatabaseName(),
  882. 'driver' => method_exists($driver, 'getName') ? $driver->getName() : null,
  883. 'serverVersion' => $this->getConfig('server_version'),
  884. ]), $driver);
  885. foreach ($this->doctrineTypeMappings as $name => $type) {
  886. $this->doctrineConnection
  887. ->getDatabasePlatform()
  888. ->registerDoctrineTypeMapping($type, $name);
  889. }
  890. }
  891. return $this->doctrineConnection;
  892. }
  893. /**
  894. * Register a custom Doctrine mapping type.
  895. *
  896. * @param string $class
  897. * @param string $name
  898. * @param string $type
  899. * @return void
  900. *
  901. * @throws \Doctrine\DBAL\DBALException
  902. * @throws \RuntimeException
  903. */
  904. public function registerDoctrineType(string $class, string $name, string $type): void
  905. {
  906. if (! $this->isDoctrineAvailable()) {
  907. throw new RuntimeException(
  908. 'Registering a custom Doctrine type requires Doctrine DBAL (doctrine/dbal).'
  909. );
  910. }
  911. if (! Type::hasType($name)) {
  912. Type::addType($name, $class);
  913. }
  914. $this->doctrineTypeMappings[$name] = $type;
  915. }
  916. /**
  917. * Get the current PDO connection.
  918. *
  919. * @return \PDO
  920. */
  921. public function getPdo()
  922. {
  923. if ($this->pdo instanceof Closure) {
  924. return $this->pdo = call_user_func($this->pdo);
  925. }
  926. return $this->pdo;
  927. }
  928. /**
  929. * Get the current PDO connection parameter without executing any reconnect logic.
  930. *
  931. * @return \PDO|\Closure|null
  932. */
  933. public function getRawPdo()
  934. {
  935. return $this->pdo;
  936. }
  937. /**
  938. * Get the current PDO connection used for reading.
  939. *
  940. * @return \PDO
  941. */
  942. public function getReadPdo()
  943. {
  944. if ($this->transactions > 0) {
  945. return $this->getPdo();
  946. }
  947. if ($this->readOnWriteConnection ||
  948. ($this->recordsModified && $this->getConfig('sticky'))) {
  949. return $this->getPdo();
  950. }
  951. if ($this->readPdo instanceof Closure) {
  952. return $this->readPdo = call_user_func($this->readPdo);
  953. }
  954. return $this->readPdo ?: $this->getPdo();
  955. }
  956. /**
  957. * Get the current read PDO connection parameter without executing any reconnect logic.
  958. *
  959. * @return \PDO|\Closure|null
  960. */
  961. public function getRawReadPdo()
  962. {
  963. return $this->readPdo;
  964. }
  965. /**
  966. * Set the PDO connection.
  967. *
  968. * @param \PDO|\Closure|null $pdo
  969. * @return $this
  970. */
  971. public function setPdo($pdo)
  972. {
  973. $this->transactions = 0;
  974. $this->pdo = $pdo;
  975. return $this;
  976. }
  977. /**
  978. * Set the PDO connection used for reading.
  979. *
  980. * @param \PDO|\Closure|null $pdo
  981. * @return $this
  982. */
  983. public function setReadPdo($pdo)
  984. {
  985. $this->readPdo = $pdo;
  986. return $this;
  987. }
  988. /**
  989. * Set the reconnect instance on the connection.
  990. *
  991. * @param callable $reconnector
  992. * @return $this
  993. */
  994. public function setReconnector(callable $reconnector)
  995. {
  996. $this->reconnector = $reconnector;
  997. return $this;
  998. }
  999. /**
  1000. * Get the database connection name.
  1001. *
  1002. * @return string|null
  1003. */
  1004. public function getName()
  1005. {
  1006. return $this->getConfig('name');
  1007. }
  1008. /**
  1009. * Get the database connection full name.
  1010. *
  1011. * @return string|null
  1012. */
  1013. public function getNameWithReadWriteType()
  1014. {
  1015. return $this->getName().($this->readWriteType ? '::'.$this->readWriteType : '');
  1016. }
  1017. /**
  1018. * Get an option from the configuration options.
  1019. *
  1020. * @param string|null $option
  1021. * @return mixed
  1022. */
  1023. public function getConfig($option = null)
  1024. {
  1025. return Arr::get($this->config, $option);
  1026. }
  1027. /**
  1028. * Get the PDO driver name.
  1029. *
  1030. * @return string
  1031. */
  1032. public function getDriverName()
  1033. {
  1034. return $this->getConfig('driver');
  1035. }
  1036. /**
  1037. * Get the query grammar used by the connection.
  1038. *
  1039. * @return \Illuminate\Database\Query\Grammars\Grammar
  1040. */
  1041. public function getQueryGrammar()
  1042. {
  1043. return $this->queryGrammar;
  1044. }
  1045. /**
  1046. * Set the query grammar used by the connection.
  1047. *
  1048. * @param \Illuminate\Database\Query\Grammars\Grammar $grammar
  1049. * @return $this
  1050. */
  1051. public function setQueryGrammar(Query\Grammars\Grammar $grammar)
  1052. {
  1053. $this->queryGrammar = $grammar;
  1054. return $this;
  1055. }
  1056. /**
  1057. * Get the schema grammar used by the connection.
  1058. *
  1059. * @return \Illuminate\Database\Schema\Grammars\Grammar
  1060. */
  1061. public function getSchemaGrammar()
  1062. {
  1063. return $this->schemaGrammar;
  1064. }
  1065. /**
  1066. * Set the schema grammar used by the connection.
  1067. *
  1068. * @param \Illuminate\Database\Schema\Grammars\Grammar $grammar
  1069. * @return $this
  1070. */
  1071. public function setSchemaGrammar(Schema\Grammars\Grammar $grammar)
  1072. {
  1073. $this->schemaGrammar = $grammar;
  1074. return $this;
  1075. }
  1076. /**
  1077. * Get the query post processor used by the connection.
  1078. *
  1079. * @return \Illuminate\Database\Query\Processors\Processor
  1080. */
  1081. public function getPostProcessor()
  1082. {
  1083. return $this->postProcessor;
  1084. }
  1085. /**
  1086. * Set the query post processor used by the connection.
  1087. *
  1088. * @param \Illuminate\Database\Query\Processors\Processor $processor
  1089. * @return $this
  1090. */
  1091. public function setPostProcessor(Processor $processor)
  1092. {
  1093. $this->postProcessor = $processor;
  1094. return $this;
  1095. }
  1096. /**
  1097. * Get the event dispatcher used by the connection.
  1098. *
  1099. * @return \Illuminate\Contracts\Events\Dispatcher
  1100. */
  1101. public function getEventDispatcher()
  1102. {
  1103. return $this->events;
  1104. }
  1105. /**
  1106. * Set the event dispatcher instance on the connection.
  1107. *
  1108. * @param \Illuminate\Contracts\Events\Dispatcher $events
  1109. * @return $this
  1110. */
  1111. public function setEventDispatcher(Dispatcher $events)
  1112. {
  1113. $this->events = $events;
  1114. return $this;
  1115. }
  1116. /**
  1117. * Unset the event dispatcher for this connection.
  1118. *
  1119. * @return void
  1120. */
  1121. public function unsetEventDispatcher()
  1122. {
  1123. $this->events = null;
  1124. }
  1125. /**
  1126. * Set the transaction manager instance on the connection.
  1127. *
  1128. * @param \Illuminate\Database\DatabaseTransactionsManager $manager
  1129. * @return $this
  1130. */
  1131. public function setTransactionManager($manager)
  1132. {
  1133. $this->transactionsManager = $manager;
  1134. return $this;
  1135. }
  1136. /**
  1137. * Unset the transaction manager for this connection.
  1138. *
  1139. * @return void
  1140. */
  1141. public function unsetTransactionManager()
  1142. {
  1143. $this->transactionsManager = null;
  1144. }
  1145. /**
  1146. * Determine if the connection is in a "dry run".
  1147. *
  1148. * @return bool
  1149. */
  1150. public function pretending()
  1151. {
  1152. return $this->pretending === true;
  1153. }
  1154. /**
  1155. * Get the connection query log.
  1156. *
  1157. * @return array
  1158. */
  1159. public function getQueryLog()
  1160. {
  1161. return $this->queryLog;
  1162. }
  1163. /**
  1164. * Clear the query log.
  1165. *
  1166. * @return void
  1167. */
  1168. public function flushQueryLog()
  1169. {
  1170. $this->queryLog = [];
  1171. }
  1172. /**
  1173. * Enable the query log on the connection.
  1174. *
  1175. * @return void
  1176. */
  1177. public function enableQueryLog()
  1178. {
  1179. $this->loggingQueries = true;
  1180. }
  1181. /**
  1182. * Disable the query log on the connection.
  1183. *
  1184. * @return void
  1185. */
  1186. public function disableQueryLog()
  1187. {
  1188. $this->loggingQueries = false;
  1189. }
  1190. /**
  1191. * Determine whether we're logging queries.
  1192. *
  1193. * @return bool
  1194. */
  1195. public function logging()
  1196. {
  1197. return $this->loggingQueries;
  1198. }
  1199. /**
  1200. * Get the name of the connected database.
  1201. *
  1202. * @return string
  1203. */
  1204. public function getDatabaseName()
  1205. {
  1206. return $this->database;
  1207. }
  1208. /**
  1209. * Set the name of the connected database.
  1210. *
  1211. * @param string $database
  1212. * @return $this
  1213. */
  1214. public function setDatabaseName($database)
  1215. {
  1216. $this->database = $database;
  1217. return $this;
  1218. }
  1219. /**
  1220. * Set the read / write type of the connection.
  1221. *
  1222. * @param string|null $readWriteType
  1223. * @return $this
  1224. */
  1225. public function setReadWriteType($readWriteType)
  1226. {
  1227. $this->readWriteType = $readWriteType;
  1228. return $this;
  1229. }
  1230. /**
  1231. * Get the table prefix for the connection.
  1232. *
  1233. * @return string
  1234. */
  1235. public function getTablePrefix()
  1236. {
  1237. return $this->tablePrefix;
  1238. }
  1239. /**
  1240. * Set the table prefix in use by the connection.
  1241. *
  1242. * @param string $prefix
  1243. * @return $this
  1244. */
  1245. public function setTablePrefix($prefix)
  1246. {
  1247. $this->tablePrefix = $prefix;
  1248. $this->getQueryGrammar()->setTablePrefix($prefix);
  1249. return $this;
  1250. }
  1251. /**
  1252. * Set the table prefix and return the grammar.
  1253. *
  1254. * @param \Illuminate\Database\Grammar $grammar
  1255. * @return \Illuminate\Database\Grammar
  1256. */
  1257. public function withTablePrefix(Grammar $grammar)
  1258. {
  1259. $grammar->setTablePrefix($this->tablePrefix);
  1260. return $grammar;
  1261. }
  1262. /**
  1263. * Register a connection resolver.
  1264. *
  1265. * @param string $driver
  1266. * @param \Closure $callback
  1267. * @return void
  1268. */
  1269. public static function resolverFor($driver, Closure $callback)
  1270. {
  1271. static::$resolvers[$driver] = $callback;
  1272. }
  1273. /**
  1274. * Get the connection resolver for the given driver.
  1275. *
  1276. * @param string $driver
  1277. * @return mixed
  1278. */
  1279. public static function getResolver($driver)
  1280. {
  1281. return static::$resolvers[$driver] ?? null;
  1282. }
  1283. }