Skip to content

Commit 7fc452b

Browse files
committed
support atomic add on database instead of getting and putting
1 parent 19c5054 commit 7fc452b

1 file changed

Lines changed: 30 additions & 2 deletions

File tree

‎src/Illuminate/Cache/DatabaseStore.php‎

Lines changed: 30 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
use Illuminate\Contracts\Cache\Store;
88
use Illuminate\Database\ConnectionInterface;
99
use Illuminate\Database\PostgresConnection;
10+
use Illuminate\Database\QueryException;
1011
use Illuminate\Support\InteractsWithTime;
1112
use Illuminate\Support\Str;
1213

@@ -116,9 +117,7 @@ public function get($key)
116117
public function put($key, $value, $seconds)
117118
{
118119
$key = $this->prefix.$key;
119-
120120
$value = $this->serialize($value);
121-
122121
$expiration = $this->getTime() + $seconds;
123122

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

132+
/**
133+
* Store an item in the cache if the key doesn't exist.
134+
*
135+
* @param string $key
136+
* @param mixed $value
137+
* @param int $seconds
138+
* @return bool
139+
*/
140+
public function add($key, $value, $seconds)
141+
{
142+
$key = $this->prefix.$key;
143+
$value = $this->serialize($value);
144+
$expiration = $this->getTime() + $seconds;
145+
146+
try {
147+
return $this->table()->insert(compact('key', 'value', 'expiration'));
148+
} catch (QueryException $e) {
149+
return $this->table()
150+
->where('key', $key)
151+
->where('expiration', '<=', $this->getTime())
152+
->update([
153+
'value' => $value,
154+
'expiration' => $expiration,
155+
]) >= 1;
156+
}
157+
158+
return false;
159+
}
160+
133161
/**
134162
* Increment the value of an item in the cache.
135163
*

0 commit comments

Comments
 (0)