MysqlMutex.php 1.53 KB
Newer Older
resurtm committed
1
<?php
2 3 4 5 6
/**
 * @link http://www.yiiframework.com/
 * @copyright Copyright (c) 2008 Yii Software LLC
 * @license http://www.yiiframework.com/license/
 */
resurtm committed
7

resurtm committed
8
namespace yii\mutex;
resurtm committed
9 10 11 12

use Yii;
use yii\base\InvalidConfigException;

13 14 15 16
/**
 * @author resurtm <resurtm@gmail.com>
 * @since 2.0
 */
resurtm committed
17
class MysqlMutex extends Mutex
resurtm committed
18
{
19 20 21 22
	/**
	 * Initializes MySQL specific mutex component implementation.
	 * @throws InvalidConfigException if [[db]] is not MySQL connection.
	 */
resurtm committed
23 24 25 26
	public function init()
	{
		parent::init();
		if ($this->db->driverName !== 'mysql') {
resurtm committed
27
			throw new InvalidConfigException('In order to use MysqlMutex connection must be configured to use MySQL database.');
resurtm committed
28 29 30
		}
	}

31
	/**
32
	 * Acquires lock by given name.
33 34 35 36 37
	 * @param string $name of the lock to be acquired.
	 * @param integer $timeout to wait for lock to become released.
	 * @return boolean acquiring result.
	 * @see http://dev.mysql.com/doc/refman/5.0/en/miscellaneous-functions.html#function_get-lock
	 */
resurtm committed
38
	protected function acquireLock($name, $timeout = 0)
resurtm committed
39 40
	{
		return (boolean)$this->db
Alexander Makarov committed
41
			->createCommand('SELECT GET_LOCK(:name, :timeout)', [':name' => $name, ':timeout' => $timeout])
resurtm committed
42 43 44
			->queryScalar();
	}

45
	/**
46
	 * Releases lock by given name.
47 48 49 50
	 * @param string $name of the lock to be released.
	 * @return boolean release result.
	 * @see http://dev.mysql.com/doc/refman/5.0/en/miscellaneous-functions.html#function_release-lock
	 */
resurtm committed
51
	protected function releaseLock($name)
resurtm committed
52 53
	{
		return (boolean)$this->db
Alexander Makarov committed
54
			->createCommand('SELECT RELEASE_LOCK(:name)', [':name' => $name])
resurtm committed
55 56 57
			->queryScalar();
	}
}