commit | author | age
|
1a98b6
|
1 |
<?php |
JK |
2 |
class Database { |
|
3 |
private $pdo; |
|
4 |
private $getByIdStatement; |
|
5 |
private $getByNumStatement; |
|
6 |
private $addStatement; |
|
7 |
|
|
8 |
public function __construct($file) { |
|
9 |
$this->pdo = new PDO('sqlite:'.$file); |
|
10 |
$this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); |
|
11 |
|
|
12 |
$this->pdo->query('CREATE TABLE IF NOT EXISTS vehicles ( |
|
13 |
id INT PRIMARY KEY, |
|
14 |
num INT UNIQUE, |
|
15 |
weight INT |
|
16 |
)'); |
|
17 |
|
|
18 |
$this->getByIdStatement = $this->pdo->prepare('SELECT num, weight FROM vehicles WHERE id=? LIMIT 1'); |
|
19 |
$this->getByNumStatement = $this->pdo->prepare('SELECT id, weight FROM vehicles WHERE num=? LIMIT 1'); |
|
20 |
$this->addStatement = $this->pdo->prepare('INSERT OR REPLACE INTO vehicles (id, num, weight) VALUES (?, ?, ?)'); |
|
21 |
} |
|
22 |
|
64994e
|
23 |
public function beginTransaction() { |
JK |
24 |
$this->pdo->beginTransaction(); |
|
25 |
} |
|
26 |
|
|
27 |
public function commit() { |
|
28 |
$this->pdo->commit(); |
|
29 |
} |
|
30 |
|
|
31 |
public function rollback() { |
|
32 |
$this->pdo->rollback(); |
|
33 |
} |
|
34 |
|
1a98b6
|
35 |
public function getById($id) { |
JK |
36 |
$this->getByIdStatement->execute([$id]); |
|
37 |
return $this->getByIdStatement->fetch(); |
|
38 |
} |
|
39 |
|
|
40 |
public function getByNum($num) { |
|
41 |
$st = $this->getByNumStatement->execute([(int)substr($num, 2)]); |
|
42 |
return $this->getByNumStatement->fetch(); |
|
43 |
} |
|
44 |
|
|
45 |
public function clear() { |
|
46 |
$this->pdo->query('DELETE FROM vehicles'); |
|
47 |
} |
|
48 |
|
|
49 |
public function add($id, $num, $weight) { |
|
50 |
$this->addStatement->execute([$id, $num, $weight]); |
|
51 |
} |
|
52 |
|
|
53 |
public function addMapping($mapping) { |
64994e
|
54 |
$this->beginTransaction(); |
1a98b6
|
55 |
$weight = count($mapping); |
JK |
56 |
foreach($mapping as $id => $vehicle) { |
|
57 |
$this->add($id, (int)substr($vehicle['num'], 2), $weight); |
|
58 |
} |
64994e
|
59 |
$this->commit(); |
1a98b6
|
60 |
} |
JK |
61 |
} |