1
|
|
|
<?php |
2
|
|
|
/****************************************************************************** |
3
|
|
|
* An implementation of dicto (scg.unibe.ch/dicto) in and for PHP. |
4
|
|
|
* |
5
|
|
|
* Copyright (c) 2016, 2015 Richard Klees <[email protected]> |
6
|
|
|
* |
7
|
|
|
* This software is licensed under The MIT License. You should have received |
8
|
|
|
* a copy of the license along with the code. |
9
|
|
|
*/ |
10
|
|
|
|
11
|
|
|
namespace Lechimp\Dicto\DB; |
12
|
|
|
|
13
|
|
|
use Doctrine\DBAL\Connection; |
14
|
|
|
|
15
|
|
|
abstract class DB { |
16
|
|
|
/** |
17
|
|
|
* @var Connection |
18
|
|
|
*/ |
19
|
|
|
protected $connection; |
20
|
|
|
|
21
|
|
|
public function __construct(Connection $connection) { |
22
|
|
|
$this->connection = $connection; |
23
|
|
|
} |
24
|
|
|
|
25
|
|
|
/** |
26
|
|
|
* @return \Doctrine\DBAL\Query\Builder |
27
|
|
|
*/ |
28
|
|
|
public function builder() { |
29
|
|
|
return $this->connection->createQueryBuilder(); |
30
|
|
|
} |
31
|
|
|
|
32
|
|
|
/** |
33
|
|
|
* @return Connection |
34
|
|
|
*/ |
35
|
|
|
public function connection() { |
36
|
|
|
return $this->connection; |
37
|
|
|
} |
38
|
|
|
|
39
|
|
|
/** |
40
|
|
|
* Initialize REGEXP for sqlite. |
41
|
|
|
*/ |
42
|
|
|
public function init_sqlite_regexp() { |
43
|
|
|
$pdo = $this->connection->getWrappedConnection(); |
44
|
|
|
if (!($pdo instanceof \PDO)) { |
45
|
|
|
throw new \RuntimeException( |
46
|
|
|
"Expected wrapped connection to be PDO-object."); |
47
|
|
|
} |
48
|
|
|
$pdo->sqliteCreateFunction("regexp", function($pattern, $data) { |
49
|
|
|
return preg_match("%$pattern%", $data) > 0; |
50
|
|
|
}); |
51
|
|
|
} |
52
|
|
|
|
53
|
|
|
// Creation of database. |
54
|
|
|
|
55
|
|
|
public function is_inited() { |
56
|
|
|
$res = $this->builder() |
57
|
|
|
->select("COUNT(*)") |
58
|
|
|
->from("sqlite_master") |
59
|
|
|
->where("type = 'table'") |
60
|
|
|
->execute() |
61
|
|
|
->fetchColumn(); |
62
|
|
|
return $res > 0; |
63
|
|
|
} |
64
|
|
|
|
65
|
|
|
public function maybe_init_database_schema() { |
66
|
|
|
if (!$this->is_inited()) { |
67
|
|
|
$this->init_database_schema(); |
68
|
|
|
} |
69
|
|
|
} |
70
|
|
|
|
71
|
|
|
abstract public function init_database_schema(); |
72
|
|
|
} |
73
|
|
|
|