Connection.php 31 KB

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