# Source for file Pessimistic.php

Documentation is available at Pessimistic.php

1. <?php
2. /*
3. * $Id: Pessimistic.php 1468 2007-05-24 16:54:42Z zYne $
4. *
5. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
6. * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
7. * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
8. * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
9. * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
10. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
11. * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
12. * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
13. * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
14. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
15. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
16. *
17. * This software consists of voluntary contributions made by many individuals
18. * and is licensed under the LGPL. For more information, see
19. * <http://www.phpdoctrine.com>.
20. */
21. /**
22. * Offline locking of records comes in handy where you need to make sure that
23. * a time-consuming task on a record or many records, which is spread over several
24. * page requests can't be interfered by other users.
25. *
26. * @link www.phpdoctrine.com
27. * @author Roman Borschel <roman@code-factory.org>
28. * @author Pierre Minnieur <pm@pierre-minnieur.de>
29. * @author Konsta Vesterinen <kvesteri@cc.hut.fi>
30. * @license http://www.opensource.org/licenses/lgpl-license.php LGPL
31. * @since 1.0
32. * @package Doctrine
33. * @category Object Relational Mapping
34. * @version $Revision: 1468 $
35. */
36. class Doctrine_Locking_Manager_Pessimistic
37. {
38. /**
39. * The conn that is used by the locking manager
40. *
41. * @var Doctrine_Connection object
42. */
43. private $conn;
44. /**
45. * The database table name for the lock tracking
46. */
47. private $_lockTable = 'doctrine_lock_tracking';
49. /**
50. * Constructs a new locking manager object
51. *
52. * When the CREATE_TABLES attribute of the connection on which the manager
53. * is supposed to work on is set to true, the locking table is created.
54. *
55. * @param Doctrine_Connection $conn The database connection to use
56. */
57. public function __construct(Doctrine_Connection $conn)
58. {
59. $this->conn = $conn;
61. if ($this->conn->getAttribute(Doctrine::ATTR_EXPORT) & Doctrine::EXPORT_TABLES) {
62. $columns = array();
63. $columns['object_type'] = array('type' => 'string',
64. 'length' => 50,
65. 'notnull' => true,
66. 'primary' => true);
68. $columns['object_key'] = array('type' => 'string',
69. 'length' => 250,
70. 'notnull' => true,
71. 'primary' => true);
73. $columns['user_ident'] = array('type' => 'string',
74. 'length' => 50,
75. 'notnull' => true);
77. $columns['timestamp_obtained'] = array('type' => 'integer',
78. 'length' => 10,
79. 'notnull' => true);
81. $options = array('primary' => array('object_type', 'object_key'));
82. try {
83. $this->conn->export->createTable($this->_lockTable, $columns, $options);
84. } catch(Exception $e) {
86. }
87. }
88. }
90. /**
91. * Obtains a lock on a {@link Doctrine_Record}
92. *
93. * @param Doctrine_Record $record The record that has to be locked
94. * @param mixed $userIdent A unique identifier of the locking user
95. * @return boolean TRUE if the locking was successful, FALSE if another user
96. * holds a lock on this record
97. * @throws Doctrine_Locking_Exception If the locking failed due to database errors
98. */
99. public function getLock(Doctrine_Record $record, $userIdent)
100. {
101. $objectType = $record->getTable()->getComponentName();
102. $key = $record->obtainIdentifier();
104. $gotLock = false;
105. $time = time();
107. if (is_array($key)) {
108. // Composite key
109. $key = implode('|', $key);
110. }
112. try {
113. $dbh = $this->conn->getDbh();
114. $dbh->beginTransaction();
116. $stmt = $dbh->prepare('INSERT INTO ' . $this->_lockTable
117. . ' (object_type, object_key, user_ident, timestamp_obtained)'
118. . ' VALUES (:object_type, :object_key, :user_ident, :ts_obtained)');
120. $stmt->bindParam(':object_type', $objectType);
121. $stmt->bindParam(':object_key', $key);
122. $stmt->bindParam(':user_ident', $userIdent);
123. $stmt->bindParam(':ts_obtained', $time);
125. try {
126. $stmt->execute();
127. $gotLock = true;
129. // we catch an Exception here instead of PDOException since we might also be catching Doctrine_Exception
130. } catch(Exception $pkviolation) {
131. // PK violation occured => existing lock!
132. }
134. if ( ! $gotLock) {
135. $lockingUserIdent = $this->_getLockingUserIdent($objectType, $key);
136. if ($lockingUserIdent !== null && $lockingUserIdent == $userIdent) {
137. $gotLock = true; // The requesting user already has a lock
138. // Update timestamp
139. $stmt = $dbh->prepare('UPDATE ' . $this->_lockTable
140. . ' SET timestamp_obtained = :ts'
141. . ' WHERE object_type = :object_type AND'
142. . ' object_key = :object_key AND'
143. . ' user_ident = :user_ident');
144. $stmt->bindParam(':ts', $time);
145. $stmt->bindParam(':object_type', $objectType);
146. $stmt->bindParam(':object_key', $key);
147. $stmt->bindParam(':user_ident', $lockingUserIdent);
148. $stmt->execute();
149. }
150. }
151. $dbh->commit();
152. } catch (Exception $pdoe) {
153. $dbh->rollback();
154. throw new Doctrine_Locking_Exception($pdoe->getMessage());
155. }
157. return $gotLock;
158. }
160. /**
161. * Releases a lock on a {@link Doctrine_Record}
162. *
163. * @param Doctrine_Record $record The record for which the lock has to be released
164. * @param mixed $userIdent The unique identifier of the locking user
165. * @return boolean TRUE if a lock was released, FALSE if no lock was released
166. * @throws Doctrine_Locking_Exception If the release procedure failed due to database errors
167. */
168. public function releaseLock(Doctrine_Record $record, $userIdent)
169. {
170. $objectType = $record->getTable()->getComponentName();
171. $key = $record->obtainIdentifier();
173. if (is_array($key)) {
174. // Composite key
175. $key = implode('|', $key);
176. }
178. try {
179. $dbh = $this->conn->getDbh();
180. $stmt = $dbh->prepare("DELETE FROM $this->_lockTable WHERE

object_type = :object_type AND
- object_key = :object_key AND
- user_ident = :user_ident");
- $stmt->bindParam(':object_type', $objectType);
- $stmt->bindParam(':object_key', $key);
- $stmt->bindParam(':user_ident', $userIdent);
- $stmt->execute();
- $count = $stmt->rowCount();
- return ($count > 0);
- } catch (PDOException $pdoe) {
- throw new Doctrine_Locking_Exception($pdoe->getMessage());
- }
- }
- /**
- * Gets the unique user identifier of a lock
- *
- * @param string $objectType The type of the object (component name)
- * @param mixed $key The unique key of the object
- * @return mixed The unique user identifier for the specified lock
- * @throws Doctrine_Locking_Exception If the query failed due to database errors
- */
- private function _getLockingUserIdent($objectType, $key)
- {
- if (is_array($key)) {
- // Composite key
- $key = implode('|', $key);
- }
- try {
- $dbh = $this->conn->getDbh();
- $stmt = $dbh->prepare('SELECT user_ident FROM ' . $this->_lockTable
- . ' WHERE object_type = :object_type AND object_key = :object_key');
- $stmt->bindParam(':object_type', $objectType);
- $stmt->bindParam(':object_key', $key);
- $success = $stmt->execute();
- if (!$success) {
- throw new Doctrine_Locking_Exception("Failed to determine locking user");
- }
- $userIdent = $stmt->fetchColumn();
- } catch (PDOException $pdoe) {
- throw new Doctrine_Locking_Exception($pdoe->getMessage());
- }
- return $userIdent;
- }
- /**
- * Gets the identifier that identifies the owner of the lock on the given
- * record.
- *
- * @param Doctrine_Record $lockedRecord The record.
- * @return mixed The unique user identifier that identifies the owner of the lock.
- */
- public function getLockOwner($lockedRecord)
- {
- $objectType = $lockedRecord->getTable()->getComponentName();
- $key = $lockedRecord->obtainIdentifier();
- return $this->_getLockingUserIdent($objectType, $key);
- }
- /**
- * Releases locks older than a defined amount of seconds
- *
- * When called without parameters all locks older than 15 minutes are released.
- *
- * @param integer $age The maximum valid age of locks in seconds
- * @param string $objectType The type of the object (component name)
- * @param mixed $userIdent The unique identifier of the locking user
- * @return integer The number of locks that have been released
- * @throws Doctrine_Locking_Exception If the release process failed due to database errors
- */
- public function releaseAgedLocks($age = 900, $objectType = null, $userIdent = null)
- {
- $age = time() - $age;
- try {
- $dbh = $this->conn->getDbh();
- $stmt = $dbh->prepare('DELETE FROM ' . $this->_lockTable . ' WHERE timestamp_obtained < :age');
- $stmt->bindParam(':age', $age);
- $query = 'DELETE FROM ' . $this->_lockTable . ' WHERE timestamp_obtained < :age';
- if ($objectType) {
- $query .= ' AND object_type = :object_type';
- }
- if ($userIdent) {
- $query .= ' AND user_ident = :user_ident';
- }
- $stmt = $dbh->prepare($query);
- $stmt->bindParam(':age', $age);
- if ($objectType) {
- $stmt->bindParam(':object_type', $objectType);
- }
- if ($userIdent) {
- $stmt->bindParam(':user_ident', $userIdent);
- }
- $stmt->execute();
- $count = $stmt->rowCount();
- return $count;
- } catch (PDOException $pdoe) {
- throw new Doctrine_Locking_Exception($pdoe->getMessage());
- }
- }
- }