-
Notifications
You must be signed in to change notification settings - Fork 27
/
Copy pathsqlite.php
112 lines (99 loc) · 2.56 KB
/
sqlite.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
<?php
class sqlite implements \Countable
{
/**
* @var PDO
*/
private $db = null;
/**
* @var string
*/
private $name = null;
public function __construct($name, $filename = "data.sqlite3")
{
$this->db = new PDO('sqlite:' . $filename);
$this->db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$this->name = $name;
$this->createTable();
}
/**
* @param string $key key
*
* @throws InvalidArgumentException
* @return string|null
*/
public function get($key)
{
if (!is_string($key)) {
throw new InvalidArgumentException('Expected string as key');
}
$stmt = $this->db->prepare(
'SELECT value FROM ' . $this->name . ' WHERE key = :key;'
);
$stmt->bindParam(':key', $key, PDO::PARAM_STR);
$stmt->execute();
if ($row = $stmt->fetch(PDO::FETCH_OBJ)) {
return $row->value;
}
return null;
}
/**
* @param string $key key
* @param string $value value
*
* @throws InvalidArgumentException
*/
public function set($key, $value)
{
if (!is_string($key)) {
throw new InvalidArgumentException('Expected string as key');
}
$queryString = 'REPLACE INTO ' . $this->name . ' VALUES (:key, :value);';
$stmt = $this->db->prepare($queryString);
$stmt->bindParam(':key', $key, \PDO::PARAM_STR);
$stmt->bindParam(':value', $value, \PDO::PARAM_STR);
$stmt->execute();
}
/**
* @param string $key key
*
* @return null
*/
public function delete($key)
{
$stmt = $this->db->prepare(
'DELETE FROM ' . $this->name . ' WHERE key = :key;'
);
$stmt->bindParam(':key', $key, \PDO::PARAM_STR);
$stmt->execute();
}
/**
* Delete all values from store
*
* @return null
*/
public function deleteAll()
{
$stmt = $this->db->prepare('DELETE FROM ' . $this->name);
$stmt->execute();
$this->data = array();
}
/**
* @return int
*/
public function count()
{
return (int) $this->db->query('SELECT COUNT(*) FROM ' . $this->name)->fetchColumn();
}
/**
* Create storage table in database if not exists
*
* @return null
*/
private function createTable()
{
$stmt = 'CREATE TABLE IF NOT EXISTS "' . $this->name . '"';
$stmt.= '(key TEXT PRIMARY KEY, value TEXT);';
$this->db->exec($stmt);
}
}