Skip to content

Commit

Permalink
support atomic add on database instead of getting and putting
Browse files Browse the repository at this point in the history
taylorotwell committed May 8, 2020
1 parent 19c5054 commit 7fc452b
Showing 1 changed file with 30 additions and 2 deletions.
32 changes: 30 additions & 2 deletions src/Illuminate/Cache/DatabaseStore.php
Original file line number Diff line number Diff line change
@@ -7,6 +7,7 @@
use Illuminate\Contracts\Cache\Store;
use Illuminate\Database\ConnectionInterface;
use Illuminate\Database\PostgresConnection;
use Illuminate\Database\QueryException;
use Illuminate\Support\InteractsWithTime;
use Illuminate\Support\Str;

@@ -116,9 +117,7 @@ public function get($key)
public function put($key, $value, $seconds)
{
$key = $this->prefix.$key;

$value = $this->serialize($value);

$expiration = $this->getTime() + $seconds;

try {
@@ -130,6 +129,35 @@ public function put($key, $value, $seconds)
}
}

/**
* Store an item in the cache if the key doesn't exist.
*
* @param string $key
* @param mixed $value
* @param int $seconds
* @return bool
*/
public function add($key, $value, $seconds)
{
$key = $this->prefix.$key;
$value = $this->serialize($value);
$expiration = $this->getTime() + $seconds;

try {
return $this->table()->insert(compact('key', 'value', 'expiration'));
} catch (QueryException $e) {
return $this->table()
->where('key', $key)
->where('expiration', '<=', $this->getTime())
->update([
'value' => $value,
'expiration' => $expiration,
]) >= 1;
}

return false;

This comment has been minimized.

Copy link
@sedattcom

sedattcom May 10, 2020

Contributor

why did you add "return false;" ?

}

/**
* Increment the value of an item in the cache.
*

0 comments on commit 7fc452b

Please sign in to comment.