Connection.php 30KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249
  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 hte 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 \Exception $e
  606. * @param string $query
  607. * @param array $bindings
  608. * @param \Closure $callback
  609. * @return mixed
  610. * @throws \Exception
  611. */
  612. protected function handleQueryException($e, $query, $bindings, Closure $callback)
  613. {
  614. if ($this->transactions >= 1) {
  615. throw $e;
  616. }
  617. return $this->tryAgainIfCausedByLostConnection(
  618. $e, $query, $bindings, $callback
  619. );
  620. }
  621. /**
  622. * Handle a query exception that occurred during query execution.
  623. *
  624. * @param \Illuminate\Database\QueryException $e
  625. * @param string $query
  626. * @param array $bindings
  627. * @param \Closure $callback
  628. * @return mixed
  629. *
  630. * @throws \Illuminate\Database\QueryException
  631. */
  632. protected function tryAgainIfCausedByLostConnection(QueryException $e, $query, $bindings, Closure $callback)
  633. {
  634. if ($this->causedByLostConnection($e->getPrevious())) {
  635. $this->reconnect();
  636. return $this->runQueryCallback($query, $bindings, $callback);
  637. }
  638. throw $e;
  639. }
  640. /**
  641. * Reconnect to the database.
  642. *
  643. * @return void
  644. *
  645. * @throws \LogicException
  646. */
  647. public function reconnect()
  648. {
  649. if (is_callable($this->reconnector)) {
  650. return call_user_func($this->reconnector, $this);
  651. }
  652. throw new LogicException('Lost connection and no reconnector available.');
  653. }
  654. /**
  655. * Reconnect to the database if a PDO connection is missing.
  656. *
  657. * @return void
  658. */
  659. protected function reconnectIfMissingConnection()
  660. {
  661. if (is_null($this->pdo)) {
  662. $this->reconnect();
  663. }
  664. }
  665. /**
  666. * Disconnect from the underlying PDO connection.
  667. *
  668. * @return void
  669. */
  670. public function disconnect()
  671. {
  672. $this->setPdo(null)->setReadPdo(null);
  673. }
  674. /**
  675. * Register a database query listener with the connection.
  676. *
  677. * @param \Closure $callback
  678. * @return void
  679. */
  680. public function listen(Closure $callback)
  681. {
  682. if (isset($this->events)) {
  683. $this->events->listen(Events\QueryExecuted::class, $callback);
  684. }
  685. }
  686. /**
  687. * Fire an event for this connection.
  688. *
  689. * @param string $event
  690. * @return array|null
  691. */
  692. protected function fireConnectionEvent($event)
  693. {
  694. if (! isset($this->events)) {
  695. return;
  696. }
  697. switch ($event) {
  698. case 'beganTransaction':
  699. return $this->events->dispatch(new Events\TransactionBeginning($this));
  700. case 'committed':
  701. return $this->events->dispatch(new Events\TransactionCommitted($this));
  702. case 'rollingBack':
  703. return $this->events->dispatch(new Events\TransactionRolledBack($this));
  704. }
  705. }
  706. /**
  707. * Fire the given event if possible.
  708. *
  709. * @param mixed $event
  710. * @return void
  711. */
  712. protected function event($event)
  713. {
  714. if (isset($this->events)) {
  715. $this->events->dispatch($event);
  716. }
  717. }
  718. /**
  719. * Get a new raw query expression.
  720. *
  721. * @param mixed $value
  722. * @return \Illuminate\Database\Query\Expression
  723. */
  724. public function raw($value)
  725. {
  726. return new Expression($value);
  727. }
  728. /**
  729. * Indicate if any records have been modified.
  730. *
  731. * @param bool $value
  732. * @return void
  733. */
  734. public function recordsHaveBeenModified($value = true)
  735. {
  736. if (! $this->recordsModified) {
  737. $this->recordsModified = $value;
  738. }
  739. }
  740. /**
  741. * Is Doctrine available?
  742. *
  743. * @return bool
  744. */
  745. public function isDoctrineAvailable()
  746. {
  747. return class_exists('Doctrine\DBAL\Connection');
  748. }
  749. /**
  750. * Get a Doctrine Schema Column instance.
  751. *
  752. * @param string $table
  753. * @param string $column
  754. * @return \Doctrine\DBAL\Schema\Column
  755. */
  756. public function getDoctrineColumn($table, $column)
  757. {
  758. $schema = $this->getDoctrineSchemaManager();
  759. return $schema->listTableDetails($table)->getColumn($column);
  760. }
  761. /**
  762. * Get the Doctrine DBAL schema manager for the connection.
  763. *
  764. * @return \Doctrine\DBAL\Schema\AbstractSchemaManager
  765. */
  766. public function getDoctrineSchemaManager()
  767. {
  768. return $this->getDoctrineDriver()->getSchemaManager($this->getDoctrineConnection());
  769. }
  770. /**
  771. * Get the Doctrine DBAL database connection instance.
  772. *
  773. * @return \Doctrine\DBAL\Connection
  774. */
  775. public function getDoctrineConnection()
  776. {
  777. if (is_null($this->doctrineConnection)) {
  778. $driver = $this->getDoctrineDriver();
  779. $this->doctrineConnection = new DoctrineConnection([
  780. 'pdo' => $this->getPdo(),
  781. 'dbname' => $this->getConfig('database'),
  782. 'driver' => $driver->getName(),
  783. ], $driver);
  784. }
  785. return $this->doctrineConnection;
  786. }
  787. /**
  788. * Get the current PDO connection.
  789. *
  790. * @return \PDO
  791. */
  792. public function getPdo()
  793. {
  794. if ($this->pdo instanceof Closure) {
  795. return $this->pdo = call_user_func($this->pdo);
  796. }
  797. return $this->pdo;
  798. }
  799. /**
  800. * Get the current PDO connection used for reading.
  801. *
  802. * @return \PDO
  803. */
  804. public function getReadPdo()
  805. {
  806. if ($this->transactions > 0) {
  807. return $this->getPdo();
  808. }
  809. if ($this->getConfig('sticky') && $this->recordsModified) {
  810. return $this->getPdo();
  811. }
  812. if ($this->readPdo instanceof Closure) {
  813. return $this->readPdo = call_user_func($this->readPdo);
  814. }
  815. return $this->readPdo ?: $this->getPdo();
  816. }
  817. /**
  818. * Set the PDO connection.
  819. *
  820. * @param \PDO|\Closure|null $pdo
  821. * @return $this
  822. */
  823. public function setPdo($pdo)
  824. {
  825. $this->transactions = 0;
  826. $this->pdo = $pdo;
  827. return $this;
  828. }
  829. /**
  830. * Set the PDO connection used for reading.
  831. *
  832. * @param \PDO|\Closure|null $pdo
  833. * @return $this
  834. */
  835. public function setReadPdo($pdo)
  836. {
  837. $this->readPdo = $pdo;
  838. return $this;
  839. }
  840. /**
  841. * Set the reconnect instance on the connection.
  842. *
  843. * @param callable $reconnector
  844. * @return $this
  845. */
  846. public function setReconnector(callable $reconnector)
  847. {
  848. $this->reconnector = $reconnector;
  849. return $this;
  850. }
  851. /**
  852. * Get the database connection name.
  853. *
  854. * @return string|null
  855. */
  856. public function getName()
  857. {
  858. return $this->getConfig('name');
  859. }
  860. /**
  861. * Get an option from the configuration options.
  862. *
  863. * @param string|null $option
  864. * @return mixed
  865. */
  866. public function getConfig($option = null)
  867. {
  868. return Arr::get($this->config, $option);
  869. }
  870. /**
  871. * Get the PDO driver name.
  872. *
  873. * @return string
  874. */
  875. public function getDriverName()
  876. {
  877. return $this->getConfig('driver');
  878. }
  879. /**
  880. * Get the query grammar used by the connection.
  881. *
  882. * @return \Illuminate\Database\Query\Grammars\Grammar
  883. */
  884. public function getQueryGrammar()
  885. {
  886. return $this->queryGrammar;
  887. }
  888. /**
  889. * Set the query grammar used by the connection.
  890. *
  891. * @param \Illuminate\Database\Query\Grammars\Grammar $grammar
  892. * @return void
  893. */
  894. public function setQueryGrammar(Query\Grammars\Grammar $grammar)
  895. {
  896. $this->queryGrammar = $grammar;
  897. }
  898. /**
  899. * Get the schema grammar used by the connection.
  900. *
  901. * @return \Illuminate\Database\Schema\Grammars\Grammar
  902. */
  903. public function getSchemaGrammar()
  904. {
  905. return $this->schemaGrammar;
  906. }
  907. /**
  908. * Set the schema grammar used by the connection.
  909. *
  910. * @param \Illuminate\Database\Schema\Grammars\Grammar $grammar
  911. * @return void
  912. */
  913. public function setSchemaGrammar(Schema\Grammars\Grammar $grammar)
  914. {
  915. $this->schemaGrammar = $grammar;
  916. }
  917. /**
  918. * Get the query post processor used by the connection.
  919. *
  920. * @return \Illuminate\Database\Query\Processors\Processor
  921. */
  922. public function getPostProcessor()
  923. {
  924. return $this->postProcessor;
  925. }
  926. /**
  927. * Set the query post processor used by the connection.
  928. *
  929. * @param \Illuminate\Database\Query\Processors\Processor $processor
  930. * @return void
  931. */
  932. public function setPostProcessor(Processor $processor)
  933. {
  934. $this->postProcessor = $processor;
  935. }
  936. /**
  937. * Get the event dispatcher used by the connection.
  938. *
  939. * @return \Illuminate\Contracts\Events\Dispatcher
  940. */
  941. public function getEventDispatcher()
  942. {
  943. return $this->events;
  944. }
  945. /**
  946. * Set the event dispatcher instance on the connection.
  947. *
  948. * @param \Illuminate\Contracts\Events\Dispatcher $events
  949. * @return void
  950. */
  951. public function setEventDispatcher(Dispatcher $events)
  952. {
  953. $this->events = $events;
  954. }
  955. /**
  956. * Unset the event dispatcher for this connection.
  957. *
  958. * @return void
  959. */
  960. public function unsetEventDispatcher()
  961. {
  962. $this->events = null;
  963. }
  964. /**
  965. * Determine if the connection in a "dry run".
  966. *
  967. * @return bool
  968. */
  969. public function pretending()
  970. {
  971. return $this->pretending === true;
  972. }
  973. /**
  974. * Get the connection query log.
  975. *
  976. * @return array
  977. */
  978. public function getQueryLog()
  979. {
  980. return $this->queryLog;
  981. }
  982. /**
  983. * Clear the query log.
  984. *
  985. * @return void
  986. */
  987. public function flushQueryLog()
  988. {
  989. $this->queryLog = [];
  990. }
  991. /**
  992. * Enable the query log on the connection.
  993. *
  994. * @return void
  995. */
  996. public function enableQueryLog()
  997. {
  998. $this->loggingQueries = true;
  999. }
  1000. /**
  1001. * Disable the query log on the connection.
  1002. *
  1003. * @return void
  1004. */
  1005. public function disableQueryLog()
  1006. {
  1007. $this->loggingQueries = false;
  1008. }
  1009. /**
  1010. * Determine whether we're logging queries.
  1011. *
  1012. * @return bool
  1013. */
  1014. public function logging()
  1015. {
  1016. return $this->loggingQueries;
  1017. }
  1018. /**
  1019. * Get the name of the connected database.
  1020. *
  1021. * @return string
  1022. */
  1023. public function getDatabaseName()
  1024. {
  1025. return $this->database;
  1026. }
  1027. /**
  1028. * Set the name of the connected database.
  1029. *
  1030. * @param string $database
  1031. * @return string
  1032. */
  1033. public function setDatabaseName($database)
  1034. {
  1035. $this->database = $database;
  1036. }
  1037. /**
  1038. * Get the table prefix for the connection.
  1039. *
  1040. * @return string
  1041. */
  1042. public function getTablePrefix()
  1043. {
  1044. return $this->tablePrefix;
  1045. }
  1046. /**
  1047. * Set the table prefix in use by the connection.
  1048. *
  1049. * @param string $prefix
  1050. * @return void
  1051. */
  1052. public function setTablePrefix($prefix)
  1053. {
  1054. $this->tablePrefix = $prefix;
  1055. $this->getQueryGrammar()->setTablePrefix($prefix);
  1056. }
  1057. /**
  1058. * Set the table prefix and return the grammar.
  1059. *
  1060. * @param \Illuminate\Database\Grammar $grammar
  1061. * @return \Illuminate\Database\Grammar
  1062. */
  1063. public function withTablePrefix(Grammar $grammar)
  1064. {
  1065. $grammar->setTablePrefix($this->tablePrefix);
  1066. return $grammar;
  1067. }
  1068. /**
  1069. * Register a connection resolver.
  1070. *
  1071. * @param string $driver
  1072. * @param \Closure $callback
  1073. * @return void
  1074. */
  1075. public static function resolverFor($driver, Closure $callback)
  1076. {
  1077. static::$resolvers[$driver] = $callback;
  1078. }
  1079. /**
  1080. * Get the connection resolver for the given driver.
  1081. *
  1082. * @param string $driver
  1083. * @return mixed
  1084. */
  1085. public static function getResolver($driver)
  1086. {
  1087. return static::$resolvers[$driver] ?? null;
  1088. }
  1089. }