Pessimistic.php 11.6 KB
Newer Older
lsmith's avatar
lsmith committed
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
<?php
/*
 *  $Id$
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * This software consists of voluntary contributions made by many individuals
 * and is licensed under the LGPL. For more information, see
 * <http://www.phpdoctrine.com>.
 */
/**
 * Offline locking of records comes in handy where you need to make sure that
 * a time-consuming task on a record or many records, which is spread over several
 * page requests can't be interfered by other users.
 *
 * @link        www.phpdoctrine.com
 * @author      Roman Borschel <roman@code-factory.org>
 * @author      Pierre Minnieur <pm@pierre-minnieur.de>
 * @author      Konsta Vesterinen <kvesteri@cc.hut.fi>
 * @license     http://www.opensource.org/licenses/lgpl-license.php LGPL
 * @since       1.0
 * @package     Doctrine
 * @category    Object Relational Mapping
 * @version     $Revision$
 */
lsmith's avatar
lsmith committed
36 37
class Doctrine_Locking_Manager_Pessimistic
{
lsmith's avatar
lsmith committed
38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56
    /**
     * The conn that is used by the locking manager
     *
     * @var Doctrine_Connection object
     */
    private $conn;
    /**
     * The database table name for the lock tracking
     */
    private $_lockTable = 'doctrine_lock_tracking';

    /**
     * Constructs a new locking manager object
     *
     * When the CREATE_TABLES attribute of the connection on which the manager
     * is supposed to work on is set to true, the locking table is created.
     *
     * @param Doctrine_Connection $conn The database connection to use
     */
lsmith's avatar
lsmith committed
57 58
    public function __construct(Doctrine_Connection $conn)
    {
lsmith's avatar
lsmith committed
59 60
        $this->conn = $conn;

zYne's avatar
zYne committed
61
        if ($this->conn->getAttribute(Doctrine::ATTR_EXPORT) & Doctrine::EXPORT_TABLES) {
lsmith's avatar
lsmith committed
62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98
            $columns = array();
            $columns['object_type']        = array('type'    => 'string',
                                                   'length'  => 50,
                                                   'notnull' => true,
                                                   'primary' => true);

            $columns['object_key']         = array('type'    => 'string',
                                                   'length'  => 250,
                                                   'notnull' => true,
                                                   'primary' => true);

            $columns['user_ident']         = array('type'    => 'string',
                                                   'length'  => 50,
                                                   'notnull' => true);

            $columns['timestamp_obtained'] = array('type'    => 'integer',
                                                   'length'  => 10,
                                                   'notnull' => true);

            $options = array('primary' => array('object_type', 'object_key'));
            try {
                $this->conn->export->createTable($this->_lockTable, $columns, $options);
            } catch(Exception $e) {

            }
        }
    }

    /**
     * Obtains a lock on a {@link Doctrine_Record}
     *
     * @param  Doctrine_Record $record     The record that has to be locked
     * @param  mixed           $userIdent  A unique identifier of the locking user
     * @return boolean  TRUE if the locking was successful, FALSE if another user
     *                  holds a lock on this record
     * @throws Doctrine_Locking_Exception  If the locking failed due to database errors
     */
lsmith's avatar
lsmith committed
99 100
    public function getLock(Doctrine_Record $record, $userIdent)
    {
lsmith's avatar
lsmith committed
101 102 103 104
        $objectType = $record->getTable()->getComponentName();
        $key        = $record->obtainIdentifier();

        $gotLock = false;
105
        $time = time();
lsmith's avatar
lsmith committed
106 107 108 109 110 111 112

        if (is_array($key)) {
            // Composite key
            $key = implode('|', $key);
        }

        try {
113
            $dbh = $this->conn->getDbh();
lsmith's avatar
lsmith committed
114 115
            $dbh->beginTransaction();

zYne's avatar
zYne committed
116 117 118 119
            $stmt = $dbh->prepare('INSERT INTO ' . $this->_lockTable
                                  . ' (object_type, object_key, user_ident, timestamp_obtained)'
                                  . ' VALUES (:object_type, :object_key, :user_ident, :ts_obtained)');

lsmith's avatar
lsmith committed
120 121 122
            $stmt->bindParam(':object_type', $objectType);
            $stmt->bindParam(':object_key', $key);
            $stmt->bindParam(':user_ident', $userIdent);
123
            $stmt->bindParam(':ts_obtained', $time);
lsmith's avatar
lsmith committed
124 125 126 127 128 129 130 131 132 133

            try {
                $stmt->execute();
                $gotLock = true;

            // we catch an Exception here instead of PDOException since we might also be catching Doctrine_Exception
            } catch(Exception $pkviolation) {
                // PK violation occured => existing lock!
            }

zYne's avatar
zYne committed
134
            if ( ! $gotLock) {
lsmith's avatar
lsmith committed
135 136 137 138
                $lockingUserIdent = $this->_getLockingUserIdent($objectType, $key);
                if ($lockingUserIdent !== null && $lockingUserIdent == $userIdent) {
                    $gotLock = true; // The requesting user already has a lock
                    // Update timestamp
zYne's avatar
zYne committed
139 140 141 142 143
                    $stmt = $dbh->prepare('UPDATE ' . $this->_lockTable 
                                          . ' SET timestamp_obtained = :ts'
                                          . ' WHERE object_type = :object_type AND'
                                          . ' object_key  = :object_key  AND'
                                          . ' user_ident  = :user_ident');
144
                    $stmt->bindParam(':ts', $time);
lsmith's avatar
lsmith committed
145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167
                    $stmt->bindParam(':object_type', $objectType);
                    $stmt->bindParam(':object_key', $key);
                    $stmt->bindParam(':user_ident', $lockingUserIdent);
                    $stmt->execute();
                }
            }
            $dbh->commit();
        } catch (Exception $pdoe) {
            $dbh->rollback();
            throw new Doctrine_Locking_Exception($pdoe->getMessage());
        }

        return $gotLock;
    }

    /**
     * Releases a lock on a {@link Doctrine_Record}
     *
     * @param  Doctrine_Record $record    The record for which the lock has to be released
     * @param  mixed           $userIdent The unique identifier of the locking user
     * @return boolean  TRUE if a lock was released, FALSE if no lock was released
     * @throws Doctrine_Locking_Exception If the release procedure failed due to database errors
     */
lsmith's avatar
lsmith committed
168 169
    public function releaseLock(Doctrine_Record $record, $userIdent)
    {
lsmith's avatar
lsmith committed
170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204
        $objectType = $record->getTable()->getComponentName();
        $key        = $record->obtainIdentifier();

        if (is_array($key)) {
            // Composite key
            $key = implode('|', $key);
        }

        try {
            $dbh = $this->conn->getDbh();
            $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
     */
lsmith's avatar
lsmith committed
205 206
    private function _getLockingUserIdent($objectType, $key)
    {
lsmith's avatar
lsmith committed
207 208 209 210 211 212 213
        if (is_array($key)) {
            // Composite key
            $key = implode('|', $key);
        }

        try {
            $dbh = $this->conn->getDbh();
zYne's avatar
zYne committed
214 215
            $stmt = $dbh->prepare('SELECT user_ident FROM ' . $this->_lockTable
                                  . ' WHERE object_type = :object_type AND object_key = :object_key');
lsmith's avatar
lsmith committed
216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238
            $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.
     */
lsmith's avatar
lsmith committed
239 240
    public function getLockOwner($lockedRecord)
    {
lsmith's avatar
lsmith committed
241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256
        $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
     */
lsmith's avatar
lsmith committed
257 258
    public function releaseAgedLocks($age = 900, $objectType = null, $userIdent = null)
    {
lsmith's avatar
lsmith committed
259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290
        $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());
        }
    }

}