0 follower

Final Class Yiisoft\Mutex\Pgsql\PgsqlMutex

InheritanceYiisoft\Mutex\Pgsql\PgsqlMutex » Yiisoft\Mutex\Mutex

PgsqlMutex implements mutex "lock" mechanism via PostgreSQL locks.

Public Methods

Hide inherited methods

Method Description Defined By
__construct() Yiisoft\Mutex\Pgsql\PgsqlMutex

Method Details

Hide inherited methods

__construct() public method

public mixed __construct ( string $name, PDO $connection )
$name string

Mutex name.

$connection PDO

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.
     *
     * @psalm-suppress PossiblyFalseArgument `unpack()` never returns `false` here because `sha1(...)` with raw
     * output always returns a 20-byte string, which is more than enough for the 4 bytes required by the 'n2' format
     * (two unsigned 16-bit big-endian integers).
     */
    $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);
}

            
acquireLock() protected method
protected acquireLock ( integer $timeout 0 )
$timeout integer

                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();
}

            
releaseLock() protected method
protected releaseLock ( )

                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();
}