Transaction.php 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | ThinkPHP [ WE CAN DO IT JUST THINK ]
  4. // +----------------------------------------------------------------------
  5. // | Copyright (c) 2006~2019 http://thinkphp.cn All rights reserved.
  6. // +----------------------------------------------------------------------
  7. // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
  8. // +----------------------------------------------------------------------
  9. // | Author: liu21st <liu21st@gmail.com>
  10. // +----------------------------------------------------------------------
  11. declare (strict_types = 1);
  12. namespace think\db\concern;
  13. use think\db\BaseQuery;
  14. /**
  15. * 事务支持
  16. */
  17. trait Transaction
  18. {
  19. /**
  20. * 执行数据库Xa事务
  21. * @access public
  22. * @param callable $callback 数据操作方法回调
  23. * @param array $dbs 多个查询对象或者连接对象
  24. * @return mixed
  25. * @throws PDOException
  26. * @throws \Exception
  27. * @throws \Throwable
  28. */
  29. public function transactionXa($callback, array $dbs = [])
  30. {
  31. $xid = uniqid('xa');
  32. if (empty($dbs)) {
  33. $dbs[] = $this->getConnection();
  34. }
  35. foreach ($dbs as $key => $db) {
  36. if ($db instanceof BaseQuery) {
  37. $db = $db->getConnection();
  38. $dbs[$key] = $db;
  39. }
  40. $db->startTransXa($xid);
  41. }
  42. try {
  43. $result = null;
  44. if (is_callable($callback)) {
  45. $result = call_user_func_array($callback, [$this]);
  46. }
  47. foreach ($dbs as $db) {
  48. $db->prepareXa($xid);
  49. }
  50. foreach ($dbs as $db) {
  51. $db->commitXa($xid);
  52. }
  53. return $result;
  54. } catch (\Exception | \Throwable $e) {
  55. foreach ($dbs as $db) {
  56. $db->rollbackXa($xid);
  57. }
  58. throw $e;
  59. }
  60. }
  61. /**
  62. * 执行数据库事务
  63. * @access public
  64. * @param callable $callback 数据操作方法回调
  65. * @return mixed
  66. */
  67. public function transaction(callable $callback)
  68. {
  69. return $this->connection->transaction($callback);
  70. }
  71. /**
  72. * 启动事务
  73. * @access public
  74. * @return void
  75. */
  76. public function startTrans(): void
  77. {
  78. $this->connection->startTrans();
  79. }
  80. /**
  81. * 用于非自动提交状态下面的查询提交
  82. * @access public
  83. * @return void
  84. * @throws PDOException
  85. */
  86. public function commit(): void
  87. {
  88. $this->connection->commit();
  89. }
  90. /**
  91. * 事务回滚
  92. * @access public
  93. * @return void
  94. * @throws PDOException
  95. */
  96. public function rollback(): void
  97. {
  98. $this->connection->rollback();
  99. }
  100. }