1
0

transaction.class.php 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. <?php
  2. namespace Juju\PDO;
  3. require_once(realpath(dirname(__DIR__).'/pdo.class.php'));
  4. use Juju\PDO;
  5. class Transaction {
  6. private $pdo;
  7. private $_pdo;
  8. private $savepoint = 0;
  9. private $dirty = false;
  10. public function __construct(PDO $pdo){
  11. $this->pdo = $pdo;
  12. if(!$pdo->beginTransaction()){
  13. throw $this->getError();
  14. }
  15. }
  16. public function __destruct(){
  17. if($this->dirty){
  18. throw new \Exception("Transaction not committed");
  19. }
  20. $this->pdo->setAttribute(\PDO::ATTR_AUTOCOMMIT, true);
  21. $this->savepoint = 0;
  22. }
  23. public function __get(string $name){
  24. switch($name){
  25. case 'savepoint':case 'dirty':
  26. return $this->$name;
  27. break;
  28. default:
  29. throw new \Exception("Invalid property {$name}");
  30. }
  31. }
  32. public function commit(bool $final = false){
  33. if($this->dirty){
  34. $this->savepoint++;
  35. $this->exec("savepoint trans_{$this->savepoint}");
  36. $this->dirty = false;
  37. }
  38. }
  39. public function rollback(bool $final = false){
  40. if($this->savepoint > 0){
  41. if($this->dirty){
  42. $this->exec("rollback to trans_{$this->savepoint}");
  43. }
  44. $this->savepoint--;
  45. }
  46. $this->dirty = false;
  47. }
  48. public function transaction(callable $fn){
  49. $this->commit();
  50. if($fn($this) === false){
  51. $this->rollback();
  52. }else{
  53. $this->commit();
  54. }
  55. }
  56. public function table(string $name){
  57. return new Table($this, $name);
  58. }
  59. public function prepare(...$args){
  60. $this->dirty = true;
  61. return $this->pdo->prepare(...$args);
  62. }
  63. public function exec(...$args){
  64. $this->dirty = true;
  65. return $this->pdo->exec(...$args);
  66. }
  67. public function query(...$args){
  68. $this->dirty = true;
  69. return $this->pdo->query(...$args);
  70. }
  71. public function quote(...$args){
  72. return $this->pdo->quote(...$args);
  73. }
  74. public function lastInsertId(...$args){
  75. return $this->pdo->lastInsertId(...$args);
  76. }
  77. public function getError(){
  78. return $this->pdo->getError();
  79. }
  80. public function stringFilter(...$args){
  81. return $this->pdo->stringFilter(...$args);
  82. }
  83. public function stringSet(...$args){
  84. return $this->pdo->stringSet(...$args);
  85. }
  86. public function stringColumn(...$args){
  87. return $this->pdo->stringColumn(...$args);
  88. }
  89. public function stringIndex(...$args){
  90. return $this->pdo->stringIndex(...$args);
  91. }
  92. public function stringForeignKey(...$args){
  93. return $this->pdo->stringForeignKey(...$args);
  94. }
  95. }
  96. ?>