-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathPostgresAdvisoryLocker.php
More file actions
53 lines (42 loc) · 1.18 KB
/
PostgresAdvisoryLocker.php
File metadata and controls
53 lines (42 loc) · 1.18 KB
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
<?php
namespace Fervo\AdvisoryLocker;
use Doctrine\DBAL\Connection;
/**
*
*/
class PostgresAdvisoryLocker implements AdvisoryLockerInterface
{
use PerformTrait;
protected $conn;
protected $databaseScope;
public function __construct(Connection $conn, bool $databaseScope = false)
{
$this->conn = $conn;
$this->databaseScope = $databaseScope;
}
public function acquire(string $name)
{
$key = $this->createKey($name);
$rs = $this->conn->query("SELECT pg_try_advisory_lock($key);");
if ($rs->fetchColumn(0) === false) {
throw new Exception\AcquireFailedException();
}
}
public function release(string $name)
{
$key = $this->createKey($name);
$rs = $this->conn->query("SELECT pg_advisory_unlock($key);");
if ($rs->fetchColumn(0) === false) {
throw new Exception\ReleaseFailedException();
}
}
protected function createKey(string $name): int
{
if ($this->databaseScope) {
$fullName = $this->conn->getDatabase().'-'.$name;
} else {
$fullName = $name;
}
return crc32($fullName);
}
}