DatabaseStore.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419
  1. <?php
  2. namespace Illuminate\Cache;
  3. use Closure;
  4. use Illuminate\Contracts\Cache\LockProvider;
  5. use Illuminate\Contracts\Cache\Store;
  6. use Illuminate\Database\ConnectionInterface;
  7. use Illuminate\Database\PostgresConnection;
  8. use Illuminate\Database\QueryException;
  9. use Illuminate\Database\SqlServerConnection;
  10. use Illuminate\Support\InteractsWithTime;
  11. use Illuminate\Support\Str;
  12. class DatabaseStore implements LockProvider, Store
  13. {
  14. use InteractsWithTime, RetrievesMultipleKeys;
  15. /**
  16. * The database connection instance.
  17. *
  18. * @var \Illuminate\Database\ConnectionInterface
  19. */
  20. protected $connection;
  21. /**
  22. * The database connection instance that should be used to manage locks.
  23. *
  24. * @var \Illuminate\Database\ConnectionInterface
  25. */
  26. protected $lockConnection;
  27. /**
  28. * The name of the cache table.
  29. *
  30. * @var string
  31. */
  32. protected $table;
  33. /**
  34. * A string that should be prepended to keys.
  35. *
  36. * @var string
  37. */
  38. protected $prefix;
  39. /**
  40. * The name of the cache locks table.
  41. *
  42. * @var string
  43. */
  44. protected $lockTable;
  45. /**
  46. * An array representation of the lock lottery odds.
  47. *
  48. * @var array
  49. */
  50. protected $lockLottery;
  51. /**
  52. * The default number of seconds that a lock should be held.
  53. *
  54. * @var int
  55. */
  56. protected $defaultLockTimeoutInSeconds;
  57. /**
  58. * Create a new database store.
  59. *
  60. * @param \Illuminate\Database\ConnectionInterface $connection
  61. * @param string $table
  62. * @param string $prefix
  63. * @param string $lockTable
  64. * @param array $lockLottery
  65. * @return void
  66. */
  67. public function __construct(ConnectionInterface $connection,
  68. $table,
  69. $prefix = '',
  70. $lockTable = 'cache_locks',
  71. $lockLottery = [2, 100],
  72. $defaultLockTimeoutInSeconds = 86400)
  73. {
  74. $this->table = $table;
  75. $this->prefix = $prefix;
  76. $this->connection = $connection;
  77. $this->lockTable = $lockTable;
  78. $this->lockLottery = $lockLottery;
  79. $this->defaultLockTimeoutInSeconds = $defaultLockTimeoutInSeconds;
  80. }
  81. /**
  82. * Retrieve an item from the cache by key.
  83. *
  84. * @param string|array $key
  85. * @return mixed
  86. */
  87. public function get($key)
  88. {
  89. $prefixed = $this->prefix.$key;
  90. $cache = $this->table()->where('key', '=', $prefixed)->first();
  91. // If we have a cache record we will check the expiration time against current
  92. // time on the system and see if the record has expired. If it has, we will
  93. // remove the records from the database table so it isn't returned again.
  94. if (is_null($cache)) {
  95. return;
  96. }
  97. $cache = is_array($cache) ? (object) $cache : $cache;
  98. // If this cache expiration date is past the current time, we will remove this
  99. // item from the cache. Then we will return a null value since the cache is
  100. // expired. We will use "Carbon" to make this comparison with the column.
  101. if ($this->currentTime() >= $cache->expiration) {
  102. $this->forgetIfExpired($key);
  103. return;
  104. }
  105. return $this->unserialize($cache->value);
  106. }
  107. /**
  108. * Store an item in the cache for a given number of seconds.
  109. *
  110. * @param string $key
  111. * @param mixed $value
  112. * @param int $seconds
  113. * @return bool
  114. */
  115. public function put($key, $value, $seconds)
  116. {
  117. $key = $this->prefix.$key;
  118. $value = $this->serialize($value);
  119. $expiration = $this->getTime() + $seconds;
  120. return $this->table()->upsert(compact('key', 'value', 'expiration'), 'key') > 0;
  121. }
  122. /**
  123. * Store an item in the cache if the key doesn't exist.
  124. *
  125. * @param string $key
  126. * @param mixed $value
  127. * @param int $seconds
  128. * @return bool
  129. */
  130. public function add($key, $value, $seconds)
  131. {
  132. if (! is_null($this->get($key))) {
  133. return false;
  134. }
  135. $key = $this->prefix.$key;
  136. $value = $this->serialize($value);
  137. $expiration = $this->getTime() + $seconds;
  138. if (! $this->getConnection() instanceof SqlServerConnection) {
  139. return $this->table()->insertOrIgnore(compact('key', 'value', 'expiration')) > 0;
  140. }
  141. try {
  142. return $this->table()->insert(compact('key', 'value', 'expiration'));
  143. } catch (QueryException) {
  144. // ...
  145. }
  146. return false;
  147. }
  148. /**
  149. * Increment the value of an item in the cache.
  150. *
  151. * @param string $key
  152. * @param mixed $value
  153. * @return int|bool
  154. */
  155. public function increment($key, $value = 1)
  156. {
  157. return $this->incrementOrDecrement($key, $value, function ($current, $value) {
  158. return $current + $value;
  159. });
  160. }
  161. /**
  162. * Decrement the value of an item in the cache.
  163. *
  164. * @param string $key
  165. * @param mixed $value
  166. * @return int|bool
  167. */
  168. public function decrement($key, $value = 1)
  169. {
  170. return $this->incrementOrDecrement($key, $value, function ($current, $value) {
  171. return $current - $value;
  172. });
  173. }
  174. /**
  175. * Increment or decrement an item in the cache.
  176. *
  177. * @param string $key
  178. * @param mixed $value
  179. * @param \Closure $callback
  180. * @return int|bool
  181. */
  182. protected function incrementOrDecrement($key, $value, Closure $callback)
  183. {
  184. return $this->connection->transaction(function () use ($key, $value, $callback) {
  185. $prefixed = $this->prefix.$key;
  186. $cache = $this->table()->where('key', $prefixed)
  187. ->lockForUpdate()->first();
  188. // If there is no value in the cache, we will return false here. Otherwise the
  189. // value will be decrypted and we will proceed with this function to either
  190. // increment or decrement this value based on the given action callbacks.
  191. if (is_null($cache)) {
  192. return false;
  193. }
  194. $cache = is_array($cache) ? (object) $cache : $cache;
  195. $current = $this->unserialize($cache->value);
  196. // Here we'll call this callback function that was given to the function which
  197. // is used to either increment or decrement the function. We use a callback
  198. // so we do not have to recreate all this logic in each of the functions.
  199. $new = $callback((int) $current, $value);
  200. if (! is_numeric($current)) {
  201. return false;
  202. }
  203. // Here we will update the values in the table. We will also encrypt the value
  204. // since database cache values are encrypted by default with secure storage
  205. // that can't be easily read. We will return the new value after storing.
  206. $this->table()->where('key', $prefixed)->update([
  207. 'value' => $this->serialize($new),
  208. ]);
  209. return $new;
  210. });
  211. }
  212. /**
  213. * Get the current system time.
  214. *
  215. * @return int
  216. */
  217. protected function getTime()
  218. {
  219. return $this->currentTime();
  220. }
  221. /**
  222. * Store an item in the cache indefinitely.
  223. *
  224. * @param string $key
  225. * @param mixed $value
  226. * @return bool
  227. */
  228. public function forever($key, $value)
  229. {
  230. return $this->put($key, $value, 315360000);
  231. }
  232. /**
  233. * Get a lock instance.
  234. *
  235. * @param string $name
  236. * @param int $seconds
  237. * @param string|null $owner
  238. * @return \Illuminate\Contracts\Cache\Lock
  239. */
  240. public function lock($name, $seconds = 0, $owner = null)
  241. {
  242. return new DatabaseLock(
  243. $this->lockConnection ?? $this->connection,
  244. $this->lockTable,
  245. $this->prefix.$name,
  246. $seconds,
  247. $owner,
  248. $this->lockLottery,
  249. $this->defaultLockTimeoutInSeconds
  250. );
  251. }
  252. /**
  253. * Restore a lock instance using the owner identifier.
  254. *
  255. * @param string $name
  256. * @param string $owner
  257. * @return \Illuminate\Contracts\Cache\Lock
  258. */
  259. public function restoreLock($name, $owner)
  260. {
  261. return $this->lock($name, 0, $owner);
  262. }
  263. /**
  264. * Remove an item from the cache.
  265. *
  266. * @param string $key
  267. * @return bool
  268. */
  269. public function forget($key)
  270. {
  271. $this->table()->where('key', '=', $this->prefix.$key)->delete();
  272. return true;
  273. }
  274. /**
  275. * Remove an item from the cache if it is expired.
  276. *
  277. * @param string $key
  278. * @return bool
  279. */
  280. public function forgetIfExpired($key)
  281. {
  282. $this->table()
  283. ->where('key', '=', $this->prefix.$key)
  284. ->where('expiration', '<=', $this->getTime())
  285. ->delete();
  286. return true;
  287. }
  288. /**
  289. * Remove all items from the cache.
  290. *
  291. * @return bool
  292. */
  293. public function flush()
  294. {
  295. $this->table()->delete();
  296. return true;
  297. }
  298. /**
  299. * Get a query builder for the cache table.
  300. *
  301. * @return \Illuminate\Database\Query\Builder
  302. */
  303. protected function table()
  304. {
  305. return $this->connection->table($this->table);
  306. }
  307. /**
  308. * Get the underlying database connection.
  309. *
  310. * @return \Illuminate\Database\ConnectionInterface
  311. */
  312. public function getConnection()
  313. {
  314. return $this->connection;
  315. }
  316. /**
  317. * Specify the name of the connection that should be used to manage locks.
  318. *
  319. * @param \Illuminate\Database\ConnectionInterface $connection
  320. * @return $this
  321. */
  322. public function setLockConnection($connection)
  323. {
  324. $this->lockConnection = $connection;
  325. return $this;
  326. }
  327. /**
  328. * Get the cache key prefix.
  329. *
  330. * @return string
  331. */
  332. public function getPrefix()
  333. {
  334. return $this->prefix;
  335. }
  336. /**
  337. * Serialize the given value.
  338. *
  339. * @param mixed $value
  340. * @return string
  341. */
  342. protected function serialize($value)
  343. {
  344. $result = serialize($value);
  345. if ($this->connection instanceof PostgresConnection && str_contains($result, "\0")) {
  346. $result = base64_encode($result);
  347. }
  348. return $result;
  349. }
  350. /**
  351. * Unserialize the given value.
  352. *
  353. * @param string $value
  354. * @return mixed
  355. */
  356. protected function unserialize($value)
  357. {
  358. if ($this->connection instanceof PostgresConnection && ! Str::contains($value, [':', ';'])) {
  359. $value = base64_decode($value);
  360. }
  361. return unserialize($value);
  362. }
  363. }