Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

94 lines
2.6KB

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