MysqlMutex.php 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. <?php
  2. /**
  3. * @link http://www.yiiframework.com/
  4. * @copyright Copyright (c) 2008 Yii Software LLC
  5. * @license http://www.yiiframework.com/license/
  6. */
  7. namespace yii\mutex;
  8. use Yii;
  9. use yii\base\InvalidConfigException;
  10. /**
  11. * @author resurtm <[email protected]>
  12. * @since 2.0
  13. */
  14. class MysqlMutex extends Mutex
  15. {
  16. /**
  17. * Initializes MySQL specific mutex component implementation.
  18. * @throws InvalidConfigException if [[db]] is not MySQL connection.
  19. */
  20. public function init()
  21. {
  22. parent::init();
  23. if ($this->db->driverName !== 'mysql') {
  24. throw new InvalidConfigException('In order to use MysqlMutex connection must be configured to use MySQL database.');
  25. }
  26. }
  27. /**
  28. * Acquires lock by given name.
  29. * @param string $name of the lock to be acquired.
  30. * @param integer $timeout to wait for lock to become released.
  31. * @return boolean acquiring result.
  32. * @see http://dev.mysql.com/doc/refman/5.0/en/miscellaneous-functions.html#function_get-lock
  33. */
  34. protected function acquireLock($name, $timeout = 0)
  35. {
  36. return (boolean)$this->db
  37. ->createCommand('SELECT GET_LOCK(:name, :timeout)', [':name' => $name, ':timeout' => $timeout])
  38. ->queryScalar();
  39. }
  40. /**
  41. * Releases lock by given name.
  42. * @param string $name of the lock to be released.
  43. * @return boolean release result.
  44. * @see http://dev.mysql.com/doc/refman/5.0/en/miscellaneous-functions.html#function_release-lock
  45. */
  46. protected function releaseLock($name)
  47. {
  48. return (boolean)$this->db
  49. ->createCommand('SELECT RELEASE_LOCK(:name)', [':name' => $name])
  50. ->queryScalar();
  51. }
  52. }