Counter & decrement - has been decremented?

Is there a way to know if a counter() method has modified the counter value?
Or eventually the previous counter value?

Suppose there is a counter named index that is initialized to 2, then we start decrementing it:

$bucket->counter('index', -1); // output 1, previous was 2, decremented of 1
$bucket->counter('index', -1); // output 0, previous was 1, decremented of 1
$bucket->counter('index', -1); // output 0, previous was 0, no decrement operation executed

How can we notice the difference between the last 2 counter() operations?

Thanks

It is not possible unfortunately for memcached decrement unfortunately.

But you could use subdocument counters (decrement fields inside the document), it behaves just like regular counters, but allows you to dive into document structure. Also it does allow negative values, and gives you error on overflow (smaller than -9223372036854775808 or larger than 9223372036854775807). For example:

<?php
$cluster = new \CouchbaseCluster('couchbase://192.168.1.221');
$bucket = $cluster->openBucket('default');

$bucket->upsert('foo', ['cnt' => -9223372036854775803]);


while (true) {
    $res = $bucket->mutateIn('foo')->counter('cnt', -1)->execute();
    if ($res->error) {
        printf("cannot increment 'cnt': %s\n", $res->error->getMessage());
        break;
    }
    var_dump($res->value[0]['value']);
}

This code will output something like this:

$ php test.php
int(-9223372036854775804)
int(-9223372036854775805)
int(-9223372036854775806)
int(-9223372036854775807)
int(-9223372036854775808)
cannot increment 'cnt': LCB_SUBDOC_MULTI_FAILURE: Could not execute one or more multi lookups or mutations

Thank you @avsej, now it is clear. By the way, it was useful for me if there was an atomic operation that returned also the previous value, but that’s not a problem! :slight_smile: