Hi,

I asked a few days ago how to handled concurrency with Cake. Thanks to 
some members of this group, examples and time, I have a possible solution.
However, I need your experience to validate this solution.

I want to warn users when a record they save was modified in the 
meanwhile by somebody else.
I add a datetime column in the table called "tst" (I can't use 
"modified" column, 'cause the value of this column seems to be updated 
before the callback 'beforeSave'... and of course, I use beforeSave 
method !).
On the beforeSave(), I start a transaction and lock "for update" the 
record. Then I compare the tst value with the value I retrieved. If it's 
the same, I go on and update the tst value with the current datetime. If 
not, I halt the process with an error.
I must add in my view $form->hidden("model.tst").
I should do the same kind of process on beforeDelete()
If a deadlock or timeout occurs, I handle these errors somewhere else.

Any opinion ? A way to improve it ?

Thanks !

function beforeSave()
    {
        foreach ($this->data as $key=>$value)
        {
            if (!isset($value['tst']))
            {   
                continue;
            }
            $pkValue = $this->id;
            $pkCol = $this->primaryKey;
            $pkType = $this->getColumnType($this->primaryKey);
            $db =& ConnectionManager::getDataSource($this->useDbConfig);
            $db->begin($this);
            $sql = "SELECT tst FROM " . $this->table . " WHERE " . 
$pkCol . " = ";
            switch ($pkType) {
                case 'integer': // TODO : add other numeric type
                    break;
                default:
                    $pkValue = "'".$pkValue."'";
                break;
            }
           
            $sql.=$pkValue. " FOR UPDATE";
            $modifiedInDB = $this->query($sql);
            if (!count($modifiedInDB))
            {
               // Record deleted
                $this->WWsetSqlErrMsg("Enregistrement déjà supprimé");
                $db->rollback($this);
                return false;
            }
            if ($modifiedInDB[0][$this->table]['tst'] != $value['tst'])
            {
                // Record deleted by somebody else
                $this->WWsetSqlErrMsg("Enregistrement modifié par un 
autre utilisateur");
                $db->rollback($this);
                return false;
            }
            else
            {
                $this->set('tst',date("Y-m-d G:i:s",strtotime('now')));
            }
        }
        return true;
    }



--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups 
"CakePHP" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/cake-php?hl=en
-~----------~----~----~----~------~----~------~--~---

Reply via email to