You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

Connection.php 31KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263
  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 \Exception $e
  606. * @param string $query
  607. * @param array $bindings
  608. * @param \Closure $callback
  609. * @return mixed
  610. *
  611. * @throws \Exception
  612. */
  613. protected function handleQueryException($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([
  782. 'pdo' => $this->getPdo(),
  783. 'dbname' => $this->getConfig('database'),
  784. 'driver' => $driver->getName(),
  785. ], $driver);
  786. }
  787. return $this->doctrineConnection;
  788. }
  789. /**
  790. * Get the current PDO connection.
  791. *
  792. * @return \PDO
  793. */
  794. public function getPdo()
  795. {
  796. if ($this->pdo instanceof Closure) {
  797. return $this->pdo = call_user_func($this->pdo);
  798. }
  799. return $this->pdo;
  800. }
  801. /**
  802. * Get the current PDO connection used for reading.
  803. *
  804. * @return \PDO
  805. */
  806. public function getReadPdo()
  807. {
  808. if ($this->transactions > 0) {
  809. return $this->getPdo();
  810. }
  811. if ($this->recordsModified && $this->getConfig('sticky')) {
  812. return $this->getPdo();
  813. }
  814. if ($this->readPdo instanceof Closure) {
  815. return $this->readPdo = call_user_func($this->readPdo);
  816. }
  817. return $this->readPdo ?: $this->getPdo();
  818. }
  819. /**
  820. * Set the PDO connection.
  821. *
  822. * @param \PDO|\Closure|null $pdo
  823. * @return $this
  824. */
  825. public function setPdo($pdo)
  826. {
  827. $this->transactions = 0;
  828. $this->pdo = $pdo;
  829. return $this;
  830. }
  831. /**
  832. * Set the PDO connection used for reading.
  833. *
  834. * @param \PDO|\Closure|null $pdo
  835. * @return $this
  836. */
  837. public function setReadPdo($pdo)
  838. {
  839. $this->readPdo = $pdo;
  840. return $this;
  841. }
  842. /**
  843. * Set the reconnect instance on the connection.
  844. *
  845. * @param callable $reconnector
  846. * @return $this
  847. */
  848. public function setReconnector(callable $reconnector)
  849. {
  850. $this->reconnector = $reconnector;
  851. return $this;
  852. }
  853. /**
  854. * Get the database connection name.
  855. *
  856. * @return string|null
  857. */
  858. public function getName()
  859. {
  860. return $this->getConfig('name');
  861. }
  862. /**
  863. * Get an option from the configuration options.
  864. *
  865. * @param string|null $option
  866. * @return mixed
  867. */
  868. public function getConfig($option = null)
  869. {
  870. return Arr::get($this->config, $option);
  871. }
  872. /**
  873. * Get the PDO driver name.
  874. *
  875. * @return string
  876. */
  877. public function getDriverName()
  878. {
  879. return $this->getConfig('driver');
  880. }
  881. /**
  882. * Get the query grammar used by the connection.
  883. *
  884. * @return \Illuminate\Database\Query\Grammars\Grammar
  885. */
  886. public function getQueryGrammar()
  887. {
  888. return $this->queryGrammar;
  889. }
  890. /**
  891. * Set the query grammar used by the connection.
  892. *
  893. * @param \Illuminate\Database\Query\Grammars\Grammar $grammar
  894. * @return $this
  895. */
  896. public function setQueryGrammar(Query\Grammars\Grammar $grammar)
  897. {
  898. $this->queryGrammar = $grammar;
  899. return $this;
  900. }
  901. /**
  902. * Get the schema grammar used by the connection.
  903. *
  904. * @return \Illuminate\Database\Schema\Grammars\Grammar
  905. */
  906. public function getSchemaGrammar()
  907. {
  908. return $this->schemaGrammar;
  909. }
  910. /**
  911. * Set the schema grammar used by the connection.
  912. *
  913. * @param \Illuminate\Database\Schema\Grammars\Grammar $grammar
  914. * @return $this
  915. */
  916. public function setSchemaGrammar(Schema\Grammars\Grammar $grammar)
  917. {
  918. $this->schemaGrammar = $grammar;
  919. return $this;
  920. }
  921. /**
  922. * Get the query post processor used by the connection.
  923. *
  924. * @return \Illuminate\Database\Query\Processors\Processor
  925. */
  926. public function getPostProcessor()
  927. {
  928. return $this->postProcessor;
  929. }
  930. /**
  931. * Set the query post processor used by the connection.
  932. *
  933. * @param \Illuminate\Database\Query\Processors\Processor $processor
  934. * @return $this
  935. */
  936. public function setPostProcessor(Processor $processor)
  937. {
  938. $this->postProcessor = $processor;
  939. return $this;
  940. }
  941. /**
  942. * Get the event dispatcher used by the connection.
  943. *
  944. * @return \Illuminate\Contracts\Events\Dispatcher
  945. */
  946. public function getEventDispatcher()
  947. {
  948. return $this->events;
  949. }
  950. /**
  951. * Set the event dispatcher instance on the connection.
  952. *
  953. * @param \Illuminate\Contracts\Events\Dispatcher $events
  954. * @return $this
  955. */
  956. public function setEventDispatcher(Dispatcher $events)
  957. {
  958. $this->events = $events;
  959. return $this;
  960. }
  961. /**
  962. * Unset the event dispatcher for this connection.
  963. *
  964. * @return void
  965. */
  966. public function unsetEventDispatcher()
  967. {
  968. $this->events = null;
  969. }
  970. /**
  971. * Determine if the connection in a "dry run".
  972. *
  973. * @return bool
  974. */
  975. public function pretending()
  976. {
  977. return $this->pretending === true;
  978. }
  979. /**
  980. * Get the connection query log.
  981. *
  982. * @return array
  983. */
  984. public function getQueryLog()
  985. {
  986. return $this->queryLog;
  987. }
  988. /**
  989. * Clear the query log.
  990. *
  991. * @return void
  992. */
  993. public function flushQueryLog()
  994. {
  995. $this->queryLog = [];
  996. }
  997. /**
  998. * Enable the query log on the connection.
  999. *
  1000. * @return void
  1001. */
  1002. public function enableQueryLog()
  1003. {
  1004. $this->loggingQueries = true;
  1005. }
  1006. /**
  1007. * Disable the query log on the connection.
  1008. *
  1009. * @return void
  1010. */
  1011. public function disableQueryLog()
  1012. {
  1013. $this->loggingQueries = false;
  1014. }
  1015. /**
  1016. * Determine whether we're logging queries.
  1017. *
  1018. * @return bool
  1019. */
  1020. public function logging()
  1021. {
  1022. return $this->loggingQueries;
  1023. }
  1024. /**
  1025. * Get the name of the connected database.
  1026. *
  1027. * @return string
  1028. */
  1029. public function getDatabaseName()
  1030. {
  1031. return $this->database;
  1032. }
  1033. /**
  1034. * Set the name of the connected database.
  1035. *
  1036. * @param string $database
  1037. * @return $this
  1038. */
  1039. public function setDatabaseName($database)
  1040. {
  1041. $this->database = $database;
  1042. return $this;
  1043. }
  1044. /**
  1045. * Get the table prefix for the connection.
  1046. *
  1047. * @return string
  1048. */
  1049. public function getTablePrefix()
  1050. {
  1051. return $this->tablePrefix;
  1052. }
  1053. /**
  1054. * Set the table prefix in use by the connection.
  1055. *
  1056. * @param string $prefix
  1057. * @return $this
  1058. */
  1059. public function setTablePrefix($prefix)
  1060. {
  1061. $this->tablePrefix = $prefix;
  1062. $this->getQueryGrammar()->setTablePrefix($prefix);
  1063. return $this;
  1064. }
  1065. /**
  1066. * Set the table prefix and return the grammar.
  1067. *
  1068. * @param \Illuminate\Database\Grammar $grammar
  1069. * @return \Illuminate\Database\Grammar
  1070. */
  1071. public function withTablePrefix(Grammar $grammar)
  1072. {
  1073. $grammar->setTablePrefix($this->tablePrefix);
  1074. return $grammar;
  1075. }
  1076. /**
  1077. * Register a connection resolver.
  1078. *
  1079. * @param string $driver
  1080. * @param \Closure $callback
  1081. * @return void
  1082. */
  1083. public static function resolverFor($driver, Closure $callback)
  1084. {
  1085. static::$resolvers[$driver] = $callback;
  1086. }
  1087. /**
  1088. * Get the connection resolver for the given driver.
  1089. *
  1090. * @param string $driver
  1091. * @return mixed
  1092. */
  1093. public static function getResolver($driver)
  1094. {
  1095. return static::$resolvers[$driver] ?? null;
  1096. }
  1097. }