123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104 |
- <?php
- namespace yii\mutex;
- use yii\base\InvalidArgumentException;
- use yii\base\InvalidConfigException;
- class PgsqlMutex extends DbMutex
- {
- use RetryAcquireTrait;
-
- public function init()
- {
- parent::init();
- if ($this->db->driverName !== 'pgsql') {
- throw new InvalidConfigException('In order to use PgsqlMutex connection must be configured to use PgSQL database.');
- }
- }
-
- private function getKeysFromName($name)
- {
- return array_values(unpack('n2', sha1($name, true)));
- }
-
- protected function acquireLock($name, $timeout = 0)
- {
- list($key1, $key2) = $this->getKeysFromName($name);
- return $this->retryAcquire($timeout, function () use ($key1, $key2) {
- return $this->db->useMaster(function ($db) use ($key1, $key2) {
-
- return (bool) $db->createCommand(
- 'SELECT pg_try_advisory_lock(:key1, :key2)',
- [':key1' => $key1, ':key2' => $key2]
- )->queryScalar();
- });
- });
- }
-
- protected function releaseLock($name)
- {
- list($key1, $key2) = $this->getKeysFromName($name);
- return $this->db->useMaster(function ($db) use ($key1, $key2) {
-
- return (bool) $db->createCommand(
- 'SELECT pg_advisory_unlock(:key1, :key2)',
- [':key1' => $key1, ':key2' => $key2]
- )->queryScalar();
- });
- }
- }
|