Optimistic locking


#1

Dear All,

is there a recommend way to implement optimistic locking (eg version field)?
I’ve found nothing in the documentation.

KR
Axel


#2

Hi Axel.

Our guideline for ATK is that we do not imply any database fields/types/structure so that you can use it with existing databases in the core. There are some extensions that implement audit. Optimistic locking would also have to be implemented through an add-on because it relies on a ‘last updated’ field.

Here is my suggestion:

$model->addHook('beforeSave', function() {
    // don't care for records without associated id
    if (!$this->id) return;

    // load raw timestamp
    $ts = $this->action('field', ['last_changed']))
        ->where($this->id_field, $this->id)
        ->getOne()

    // convert to native PHP format
    $ts_php = $this->persistence->typecastLoadField(
        $this->getElement('last_changed'), 
        $ts
    );

    // prevent from saving (we are inside transaction)
    if ($ts_php != $this['last_changed'])) {
        throw new Exception('Record was modified elsewhere');
    }

    // update
    $this['last_action'] = new DateTime();
});

I hope i understood this correctly :slight_smile:


#3

Hi romaninsh

great, that’s exactly what I was looking for.
Many Thanks

KR

Axel