QueryException.php 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. <?php
  2. namespace Illuminate\Database;
  3. use Illuminate\Support\Str;
  4. use PDOException;
  5. use Throwable;
  6. class QueryException extends PDOException
  7. {
  8. /**
  9. * The database connection name.
  10. *
  11. * @var string
  12. */
  13. public $connectionName;
  14. /**
  15. * The SQL for the query.
  16. *
  17. * @var string
  18. */
  19. protected $sql;
  20. /**
  21. * The bindings for the query.
  22. *
  23. * @var array
  24. */
  25. protected $bindings;
  26. /**
  27. * Create a new query exception instance.
  28. *
  29. * @param string $connectionName
  30. * @param string $sql
  31. * @param array $bindings
  32. * @param \Throwable $previous
  33. * @return void
  34. */
  35. public function __construct($connectionName, $sql, array $bindings, Throwable $previous)
  36. {
  37. parent::__construct('', 0, $previous);
  38. $this->connectionName = $connectionName;
  39. $this->sql = $sql;
  40. $this->bindings = $bindings;
  41. $this->code = $previous->getCode();
  42. $this->message = $this->formatMessage($connectionName, $sql, $bindings, $previous);
  43. if ($previous instanceof PDOException) {
  44. $this->errorInfo = $previous->errorInfo;
  45. }
  46. }
  47. /**
  48. * Format the SQL error message.
  49. *
  50. * @param string $connectionName
  51. * @param string $sql
  52. * @param array $bindings
  53. * @param \Throwable $previous
  54. * @return string
  55. */
  56. protected function formatMessage($connectionName, $sql, $bindings, Throwable $previous)
  57. {
  58. return $previous->getMessage().' (Connection: '.$connectionName.', SQL: '.Str::replaceArray('?', $bindings, $sql).')';
  59. }
  60. /**
  61. * Get the connection name for the query.
  62. *
  63. * @return string
  64. */
  65. public function getConnectionName()
  66. {
  67. return $this->connectionName;
  68. }
  69. /**
  70. * Get the SQL for the query.
  71. *
  72. * @return string
  73. */
  74. public function getSql()
  75. {
  76. return $this->sql;
  77. }
  78. /**
  79. * Get the bindings for the query.
  80. *
  81. * @return array
  82. */
  83. public function getBindings()
  84. {
  85. return $this->bindings;
  86. }
  87. }