Database.php 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. <?php
  2. /**
  3. * Pimf
  4. *
  5. * @copyright Copyright (c) Gjero Krsteski (http://krsteski.de)
  6. * @license http://krsteski.de/new-bsd-license New BSD License
  7. */
  8. namespace Pimf;
  9. /**
  10. * @package Pimf
  11. * @author Gjero Krsteski <[email protected]>
  12. */
  13. class Database extends \PDO
  14. {
  15. /**
  16. * The current transaction level.
  17. *
  18. * @var int
  19. */
  20. protected $transLevel = 0;
  21. /**
  22. * Check database drivers that support savepoints.
  23. *
  24. * @return bool
  25. */
  26. public function nestable()
  27. {
  28. return in_array(
  29. $this->getAttribute(\PDO::ATTR_DRIVER_NAME), array("pgsql", "mysql")
  30. );
  31. }
  32. /**
  33. * @return bool|void
  34. */
  35. public function beginTransaction()
  36. {
  37. if ($this->transLevel == 0 || !$this->nestable()) {
  38. parent::beginTransaction();
  39. } else {
  40. $this->exec("SAVEPOINT LEVEL{$this->transLevel}");
  41. }
  42. $this->transLevel++;
  43. }
  44. /**
  45. * @return bool|void
  46. */
  47. public function commit()
  48. {
  49. $this->transLevel--;
  50. if ($this->transLevel == 0 || !$this->nestable()) {
  51. parent::commit();
  52. } else {
  53. $this->exec("RELEASE SAVEPOINT LEVEL{$this->transLevel}");
  54. }
  55. }
  56. /**
  57. * @return bool|void
  58. * @throws \PDOException
  59. */
  60. public function rollBack()
  61. {
  62. if ($this->transLevel == 0) {
  63. throw new \PDOException('trying to rollback without a transaction-start', 25000);
  64. }
  65. $this->transLevel--;
  66. if ($this->transLevel == 0 || !$this->nestable()) {
  67. parent::rollBack();
  68. } else {
  69. $this->exec("ROLLBACK TO SAVEPOINT LEVEL{$this->transLevel}");
  70. }
  71. }
  72. }