1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Kodus\Cache\Database; |
4
|
|
|
|
5
|
|
|
use function implode; |
6
|
|
|
use PDO; |
7
|
|
|
use PDOException; |
8
|
|
|
use PDOStatement; |
9
|
|
|
|
10
|
|
|
abstract class Adapter |
11
|
|
|
{ |
12
|
|
|
/** |
13
|
|
|
* @var PDO |
14
|
|
|
*/ |
15
|
|
|
private $pdo; |
16
|
|
|
|
17
|
|
|
/** |
18
|
|
|
* @var string |
19
|
|
|
*/ |
20
|
|
|
protected $table_name; |
21
|
|
|
|
22
|
388 |
|
public function __construct(PDO $pdo, string $table_name) |
23
|
|
|
{ |
24
|
388 |
|
$this->pdo = $pdo; |
25
|
388 |
|
$this->table_name = $table_name; |
26
|
388 |
|
} |
27
|
|
|
|
28
|
|
|
abstract public function select(string $key): ?CacheEntry; |
29
|
|
|
|
30
|
|
|
abstract public function delete(string $key): void; |
31
|
|
|
|
32
|
|
|
/** |
33
|
|
|
* @param string[] $keys |
34
|
|
|
* |
35
|
|
|
* @return CacheEntry[] |
36
|
|
|
*/ |
37
|
|
|
abstract public function selectMultiple(array $keys): array; |
38
|
|
|
|
39
|
|
|
abstract public function deleteMultiple(array $keys): void; |
40
|
|
|
|
41
|
|
|
abstract public function upsert(array $values, int $expires): void; |
42
|
|
|
|
43
|
|
|
abstract public function truncate(): void; |
44
|
|
|
|
45
|
|
|
abstract public function deleteExpired(int $now): void; |
46
|
|
|
|
47
|
|
|
abstract protected function createTable(): void; |
48
|
|
|
|
49
|
388 |
|
protected function prepare(string $sql): PDOStatement |
50
|
|
|
{ |
51
|
388 |
|
return $this->pdo->prepare($sql); |
52
|
|
|
} |
53
|
|
|
|
54
|
|
|
/** |
55
|
|
|
* @param PDOStatement $statement |
56
|
|
|
* |
57
|
|
|
* @return CacheEntry[] |
58
|
|
|
*/ |
59
|
92 |
|
protected function fetch(PDOStatement $statement): array |
60
|
|
|
{ |
61
|
92 |
|
$rows = $this->execute($statement)->fetchAll(PDO::FETCH_ASSOC); |
62
|
|
|
|
63
|
92 |
|
$result = []; |
64
|
|
|
|
65
|
92 |
|
foreach ($rows as $row) { |
66
|
82 |
|
$result[] = new CacheEntry( |
67
|
82 |
|
$row["key"], |
68
|
82 |
|
is_resource($row["data"]) |
69
|
41 |
|
? stream_get_contents($row["data"]) |
70
|
82 |
|
: $row["data"], |
71
|
82 |
|
$row["expires"]); |
72
|
|
|
} |
73
|
|
|
|
74
|
92 |
|
return $result; |
75
|
|
|
} |
76
|
|
|
|
77
|
388 |
|
protected function execute(PDOStatement $statement): PDOStatement |
78
|
|
|
{ |
79
|
|
|
try { |
80
|
388 |
|
$this->unsafeExecute($statement); |
81
|
2 |
|
} catch (PDOException $error) { |
82
|
|
|
// TODO only retry if the error is a missing table error |
83
|
2 |
|
$this->createTable(); |
84
|
|
|
|
85
|
2 |
|
$this->unsafeExecute($statement); |
86
|
|
|
} |
87
|
|
|
|
88
|
388 |
|
return $statement; |
89
|
|
|
} |
90
|
|
|
|
91
|
388 |
|
protected function unsafeExecute(PDOStatement $statement): void |
92
|
|
|
{ |
93
|
388 |
|
if ($statement->execute() !== true) { |
94
|
2 |
|
throw new PDOException(implode(" ", $statement->errorInfo())); |
95
|
|
|
} |
96
|
388 |
|
} |
97
|
|
|
} |
98
|
|
|
|