-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDatabaseManager.php
More file actions
293 lines (258 loc) · 7.93 KB
/
DatabaseManager.php
File metadata and controls
293 lines (258 loc) · 7.93 KB
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
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
<?php
namespace WebStream\Database;
use Closure;
use Doctrine\DBAL\TransactionIsolationLevel;
use WebStream\Container\Container;
use WebStream\Database\Driver\DatabaseDriver;
use WebStream\DI\Injector;
use WebStream\Exception\Extend\DatabaseException;
/**
* DatabaseManager
* @author Ryuichi TANAKA.
* @since 2013/12/07
* @version 0.4
*/
class DatabaseManager
{
use Injector;
/**
* @var ConnectionManager コネクションマネージャ
*/
private ConnectionManager $connectionManager;
/**
* @var DatabaseDriver データベースコネクション
*/
private DatabaseDriver $connection;
/**
* @var bool 自動コミットフラグ
*/
private bool $isAutoCommit;
/**
* @var Query クエリオブジェクト
*/
private Query $query;
/**
* @var Logger ロガー
*/
private $logger;
/**
* constructor
* @param Container $container
*/
public function __construct(Container $container)
{
$this->connectionManager = new ConnectionManager($container);
$this->logger = $container->logger;
$this->isAutoCommit = false;
}
/**
* destructor
*/
public function __destruct()
{
$this->disconnect();
unset($this->query);
}
/**
* データベース接続する
* すでに接続中であれば再接続はしない
*/
public function connect()
{
try {
$this->connection->connect();
$this->query = new Query($this->connection);
$this->query->inject('logger', $this->logger);
} catch (\PDOException $e) {
throw new DatabaseException($e);
}
}
/**
* データベース切断する
*/
public function disconnect()
{
if (!isset($this->connection)) {
return;
}
try {
if ($this->inTransaction()) {
// トランザクションが明示的に開始された状態でcommit/rollbackが行われていない場合
// ログに警告を書き込み、強制的にロールバックする
$this->connection->rollback();
$this->logger->warn("Not has been executed commit or rollback after the transaction started.");
}
$this->connection->disconnect();
} catch (\Exception $e) {
throw new DatabaseException($e);
}
}
/**
* トランザクションを開始する
* @param int $isolationLevel トランザクション分離レベル
*/
public function beginTransaction(int $isolationLevel)
{
// 既にトランザクションが開始されている場合、継続しているトランザクションを有効のままにする
// トランザクションを破棄して再度開始する場合は明示的に破棄してから再呼び出しする
if ($this->inTransaction()) {
$this->logger->debug("Transaction already started.");
return;
}
if (!$this->connection->beginTransaction()) {
throw new DatabaseException("Failed to start transaction.");
}
$this->connection->setAutoCommit($this->isAutoCommit);
if (
$isolationLevel === TransactionIsolationLevel::READ_UNCOMMITTED ||
$isolationLevel === TransactionIsolationLevel::READ_COMMITTED ||
$isolationLevel === TransactionIsolationLevel::REPEATABLE_READ ||
$isolationLevel === TransactionIsolationLevel::SERIALIZABLE
) {
$this->connection->setTransactionIsolation($isolationLevel);
} else {
throw new DatabaseException("Invalid transaction isolation level: " . $isolationLevel);
}
$this->logger->debug("Transaction start.");
}
/**
* コミットする
*/
public function commit()
{
try {
if ($this->connection !== null) {
if ($this->inTransaction()) {
$this->connection->commit();
$this->logger->debug("Execute commit.");
} else {
$this->logger->warn("Not executed commit because the transaction is not started.");
}
} else {
throw new DatabaseException("Can't execute commit.");
}
} catch (\Exception $e) {
$this->query = null;
throw new DatabaseException($e);
}
}
/**
* ロールバックする
*/
public function rollback()
{
try {
if ($this->connection !== null) {
if ($this->inTransaction()) {
$this->connection->rollback();
$this->logger->debug("Execute rollback.");
} else {
$this->logger->warn("Not executed rollback because the transaction is not started.");
}
} else {
throw new DatabaseException("Can't execute rollback.");
}
} catch (\Exception $e) {
$this->query = null;
throw new DatabaseException($e);
}
}
/**
* トランザクションスコープを使用する
* @param Closure $closure クロージャ
* @param array $config
* @return object 処理結果
*/
public function transactional(\Closure $closure, $config = [])
{
if (!array_key_exists('isolationLevel', $config)) {
$config['isolationLevel'] = TransactionIsolationLevel::READ_COMMITTED;
}
if (!array_key_exists('autoCommit', $config)) {
$config['autoCommit'] = false;
}
$this->isAutoCommit = $config['autoCommit'];
$this->beginTransaction($config['isolationLevel']);
try {
$result = $closure($this);
$this->commit();
return $result;
} catch (DatabaseException $e) {
$this->rollback();
throw $e;
} catch (\Throwable $e) {
$this->rollback();
throw new DatabaseException($e);
}
}
/**
* 自動コミットを有効化
*/
public function enableAutoCommit()
{
$this->isAutoCommit = true;
}
/**
* 自動コミットを無効化
*/
public function disableAutoCommit()
{
$this->isAutoCommit = false;
}
/**
* トランザクション内かどうか
* @return bool トランザクション内かどうか
*/
public function inTransaction()
{
if ($this->connection->inTransaction()) {
return true;
}
return false;
}
/**
* DB接続されているか
* @param boolean 接続有無
* @return bool
*/
public function isConnected()
{
return $this->connection->isConnected();
}
/**
* トランザクション分離レベルを返却する
* @return int トランザクション分離レベル
*/
public function getTransactionIsolation()
{
return $this->connection->getTransactionIsolation();
}
/**
* データベース接続が可能かどうか
* @param string Modelファイルパス
* @return bool 接続可否
*/
public function loadConnection($filepath)
{
$connection = $this->connectionManager->getConnection($filepath);
if ($connection !== null) {
$this->connection = $connection;
}
return $this->connection !== null;
}
/**
* クエリを設定する
* @param string $sql SQL
* @param array $bind パラメータ
* @return Query
*/
public function query(string $sql, array $bind = [])
{
if ($this->query === null) {
throw new DatabaseException("Query does not set because database connection failed.");
}
$this->query->setSql($sql);
$this->query->setBind($bind);
return $this->query;
}
}