-
-
Notifications
You must be signed in to change notification settings - Fork 4
/
PgsqlMutex.php
72 lines (59 loc) · 2 KB
/
PgsqlMutex.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
<?php
declare(strict_types=1);
namespace Yiisoft\Mutex\Pgsql;
use InvalidArgumentException;
use PDO;
use Yiisoft\Mutex\Mutex;
use function array_values;
use function sha1;
use function unpack;
/**
* PgsqlMutex implements mutex "lock" mechanism via PostgreSQL locks.
*/
final class PgsqlMutex extends Mutex
{
private array $lockKeys;
private PDO $connection;
/**
* @param string $name Mutex name.
* @param PDO $connection PDO connection instance to use.
*/
public function __construct(string $name, PDO $connection)
{
// Converts a string into two 16-bit integer keys using the SHA1 hash function.
$this->lockKeys = array_values(unpack('n2', sha1($name, true)));
$this->connection = $connection;
/** @var string $driverName */
$driverName = $connection->getAttribute(PDO::ATTR_DRIVER_NAME);
if ($driverName !== 'pgsql') {
throw new InvalidArgumentException("PostgreSQL connection instance should be passed. Got \"$driverName\".");
}
parent::__construct(self::class, $name);
}
/**
* {@inheritdoc}
*
* @see https://www.postgresql.org/docs/13/functions-admin.html
*/
protected function acquireLock(int $timeout = 0): bool
{
$statement = $this->connection->prepare('SELECT pg_try_advisory_lock(:key1, :key2)');
$statement->bindValue(':key1', $this->lockKeys[0]);
$statement->bindValue(':key2', $this->lockKeys[1]);
$statement->execute();
return (bool) $statement->fetchColumn();
}
/**
* {@inheritdoc}
*
* @see https://www.postgresql.org/docs/13/functions-admin.html
*/
protected function releaseLock(): bool
{
$statement = $this->connection->prepare('SELECT pg_advisory_unlock(:key1, :key2)');
$statement->bindValue(':key1', $this->lockKeys[0]);
$statement->bindValue(':key2', $this->lockKeys[1]);
$statement->execute();
return (bool) $statement->fetchColumn();
}
}