Connection.php 33 KB

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