-
Notifications
You must be signed in to change notification settings - Fork 0
/
DB.php
136 lines (111 loc) · 3 KB
/
DB.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
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
<?php
namespace B;
class DB
{
protected $pdo;
public function __construct($file = '')
{
$new = !file_exists($file);
$this->pdo = new \PDO('sqlite:'.$file);
$this->pdo->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
$this->pdo->setAttribute(\PDO::ATTR_DEFAULT_FETCH_MODE, \PDO::FETCH_ASSOC);
if ($new) {
$this->createTables();
}
}
private function createTables()
{
$this->pdo->prepare("
CREATE TABLE b (
id INTEGER PRIMARY KEY,
date TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
desc TEXT NOT NULL DEFAULT '',
link TEXT NOT NULL DEFAULT '' UNIQUE
);
")->execute();
}
public function add($desc, $link)
{
$this->pdo->prepare('
INSERT INTO b (desc, link) VALUES (:desc, :link)
')->execute([
':desc' => $desc,
':link' => $link,
]);
return true;
}
public function exists($link)
{
$st = $this->pdo->prepare('
SELECT id FROM b
WHERE link = :link
');
$st->execute([ ':link' => $link ]);
return (bool) $st->fetch();
}
public function getEntries($filter = false, $skip = false, $count = false)
{
if (!$filter) {
$filter = '%';
}
if ($skip !== false && $count !== false) {
$limit = 'LIMIT :skip, :count';
} else {
$limit = '';
}
if ($filter) {
$queryParts = explode(' ', $filter);
$where = [];
$args = [];
foreach ($queryParts as $i => $part) {
$where[] = "desc LIKE :filter$i";
$args[":filter$i"] = '%'.$part.'%';
}
} else {
$where[] = "desc LIKE :filter";
$args[":filter"] = '%';
}
$st = $this->pdo->prepare("
SELECT id, desc, link FROM b
WHERE ". join(' AND ', $where) ."
ORDER BY date DESC
$limit
");
if ($skip !== false && $count !== false) {
$args['skip'] = $skip;
$args['count'] = $count;
}
$st->execute($args);
$ret = $st->fetchAll();
return $ret;
}
public function deleteEntry($id)
{
$this->pdo->prepare('
DELETE FROM b WHERE id = :id
')->execute([
':id' => $id,
]);
return true;
}
public function setTitle($id, $title)
{
$this->pdo->prepare('
UPDATE b SET desc = :desc WHERE id = :id
')->execute([
':id' => $id,
':desc' => $title,
]);
return true;
}
public function setLink($id, $link)
{
$this->pdo->prepare('
UPDATE b SET link = :link WHERE id = :id
')->execute([
':id' => $id,
':link' => $link,
]);
return true;
}
}