PgsqlMutex.php 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  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\base\InvalidConfigException;
  9. use yii\base\InvalidParamException;
  10. /**
  11. * PgsqlMutex implements mutex "lock" mechanism via PgSQL locks.
  12. *
  13. * Application configuration example:
  14. *
  15. * ```
  16. * [
  17. * 'components' => [
  18. * 'db' => [
  19. * 'class' => 'yii\db\Connection',
  20. * 'dsn' => 'pgsql:host=127.0.0.1;dbname=demo',
  21. * ]
  22. * 'mutex' => [
  23. * 'class' => 'yii\mutex\PgsqlMutex',
  24. * ],
  25. * ],
  26. * ]
  27. * ```
  28. *
  29. * @see Mutex
  30. *
  31. * @author nineinchnick <janek.jan@gmail.com>
  32. * @since 2.0.8
  33. */
  34. class PgsqlMutex extends DbMutex
  35. {
  36. /**
  37. * Initializes PgSQL specific mutex component implementation.
  38. * @throws InvalidConfigException if [[db]] is not PgSQL connection.
  39. */
  40. public function init()
  41. {
  42. parent::init();
  43. if ($this->db->driverName !== 'pgsql') {
  44. throw new InvalidConfigException('In order to use PgsqlMutex connection must be configured to use PgSQL database.');
  45. }
  46. }
  47. /**
  48. * Converts a string into two 16 bit integer keys using the SHA1 hash function.
  49. * @param string $name
  50. * @return array contains two 16 bit integer keys
  51. */
  52. private function getKeysFromName($name)
  53. {
  54. return array_values(unpack('n2', sha1($name, true)));
  55. }
  56. /**
  57. * Acquires lock by given name.
  58. * @param string $name of the lock to be acquired.
  59. * @param int $timeout to wait for lock to become released.
  60. * @return bool acquiring result.
  61. * @see http://www.postgresql.org/docs/9.0/static/functions-admin.html
  62. */
  63. protected function acquireLock($name, $timeout = 0)
  64. {
  65. if ($timeout !== 0) {
  66. throw new InvalidParamException('PgsqlMutex does not support timeout.');
  67. }
  68. list($key1, $key2) = $this->getKeysFromName($name);
  69. return (bool) $this->db
  70. ->createCommand('SELECT pg_try_advisory_lock(:key1, :key2)', [':key1' => $key1, ':key2' => $key2])
  71. ->queryScalar();
  72. }
  73. /**
  74. * Releases lock by given name.
  75. * @param string $name of the lock to be released.
  76. * @return bool release result.
  77. * @see http://www.postgresql.org/docs/9.0/static/functions-admin.html
  78. */
  79. protected function releaseLock($name)
  80. {
  81. list($key1, $key2) = $this->getKeysFromName($name);
  82. return (bool) $this->db
  83. ->createCommand('SELECT pg_advisory_unlock(:key1, :key2)', [':key1' => $key1, ':key2' => $key2])
  84. ->queryScalar();
  85. }
  86. }