-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathDatabase.php
307 lines (267 loc) · 9.29 KB
/
Database.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
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
294
295
296
297
298
299
300
301
302
303
304
305
306
307
<?php
/**
* @author Marwan Al-Soltany <[email protected]>
* @copyright Marwan Al-Soltany 2021
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
declare(strict_types=1);
namespace MAKS\Velox\Backend;
use MAKS\Velox\Backend\Exception;
/**
* A class that represents the database and handles database operations.
*
* Example:
* ```
* $database = Database::instance();
* $database->query('SELECT * FROM `users`');
* $database->prepare('SELECT * FROM `users` WHERE `job` = :job LIMIT 5')->execute([':job' => 'Developer'])->fetchAll();
* $database->perform('SELECT * FROM `users` WHERE `title` LIKE :title AND `id` > :id', ['title' => 'Dr.%', 'id' => 1])->fetchAll();
* ```
*
* @package Velox\Backend
* @since 1.3.0
* @api
*/
class Database extends \PDO
{
/**
* Current open database connections.
*/
protected static array $connections;
/**
* A cache to hold prepared statements.
*/
protected array $cache;
protected string $dsn;
protected ?string $username;
protected ?string $password;
protected ?array $options;
/**
* Class constructor.
*
* Adds some default options to the PDO connection.
*
* @param string $dsn
* @param string|null $username
* @param string|null $password
* @param array|null $options
*/
protected function __construct(string $dsn, ?string $username = null, ?string $password = null, ?array $options = null)
{
$this->dsn = $dsn;
$this->username = $username;
$this->password = $password;
$this->options = $options;
$this->cache = [];
parent::__construct($dsn, $username, $password, $options);
$this->setAttribute(static::ATTR_ERRMODE, static::ERRMODE_EXCEPTION);
$this->setAttribute(static::ATTR_DEFAULT_FETCH_MODE, static::FETCH_ASSOC);
$this->setAttribute(static::ATTR_EMULATE_PREPARES, false);
$this->setAttribute(static::MYSQL_ATTR_FOUND_ROWS, true);
$this->setAttribute(static::ATTR_STATEMENT_CLASS, [$this->getStatementClass()]);
}
/**
* Returns a singleton instance of the `Database` class based on connection credentials.
* This method makes sure that a single connection is opened and reused for each connection credentials set (DSN, User, Password, ...).
*
* @param string|null $dsn The DSN string.
* @param string|null $username [optional] The database username.
* @param string|null $password [optional] The database password.
* @param array|null $options [optional] PDO options.
*
* @return static
*/
final public static function connect(string $dsn, ?string $username = null, ?string $password = null, ?array $options = null): Database
{
$connection = md5(serialize(func_get_args()));
if (!isset(static::$connections[$connection])) {
static::$connections[$connection] = new static($dsn, $username, $password, $options);
}
return static::$connections[$connection];
}
/**
* Returns the singleton instance of the `Database` class using credentials found in `{database}` config.
*
* @return static
*
* @codeCoverageIgnore This method is overridden (mocked) in tests.
*/
public static function instance(): Database
{
$databaseConfig = Config::get('database', []);
try {
return static::connect(
$databaseConfig['dsn'] ?? '',
$databaseConfig['username'] ?? null,
$databaseConfig['password'] ?? null,
$databaseConfig['options'] ?? null
);
} catch (\PDOException $error) {
// connection can't be established (incorrect config), return a fake instance
return static::mock();
}
}
/**
* Returns FQN for a custom `PDOStatement` class.
*
* @return string
*/
private function getStatementClass(): string
{
$statement = new class () extends \PDOStatement {
// Makes method chaining a little bit more convenient.
#[\ReturnTypeWillChange]
public function execute($params = null)
{
parent::execute($params);
return $this;
}
// Catches the debug dump instead of printing it out directly.
#[\ReturnTypeWillChange]
public function debugDumpParams()
{
ob_start();
parent::debugDumpParams();
$dump = ob_get_contents();
ob_end_clean();
return $dump;
}
};
return get_class($statement);
}
/**
* Adds caching capabilities for prepared statement.
* {@inheritDoc}
*/
#[\ReturnTypeWillChange]
public function prepare($query, $options = [])
{
$hash = md5($query);
if (!isset($this->cache[$hash])) {
$this->cache[$hash] = parent::prepare($query, $options);
}
return $this->cache[$hash];
}
/**
* A wrapper method to perform a query on the fly using either `self::query()` or `self::prepare()` + `self::execute()`.
*
* @param string $query The query to execute.
* @param array $params The parameters to bind to the query.
*
* @return \PDOStatement
*/
public function perform(string $query, ?array $params = null): \PDOStatement
{
try {
if (empty($params)) {
return $this->query($query);
}
$statement = $this->prepare($query);
$statement->execute($params);
return $statement;
} catch (\PDOException $error) {
Exception::throw(
'QueryFailedException:PDOException',
"Could not execute the query '{$query}'",
(int)$error->getCode(),
$error
);
}
}
/**
* Serves as a wrapper method to execute some operations in transactional context with the ability to attempt retires.
*
* @param callable $callback The callback to execute inside the transaction. This callback will be bound to the `Database` class.
* @param int $retries The number of times to attempt the transaction. Each retry will be delayed by 1-3 seconds.
*
* @return mixed The result of the callback.
*
* @throws \RuntimeException If the transaction fails after all retries.
*/
public function transactional(callable $callback, int $retries = 3)
{
$callback = \Closure::fromCallable($callback)->bindTo($this);
$attempts = 0;
$return = null;
do {
$this->beginTransaction();
try {
$return = $callback($this);
$this->commit();
break;
} catch (\Throwable $error) {
$this->rollBack();
if (++$attempts === $retries) {
Exception::throw(
'TransactionFailedException:RuntimeException',
"Could not complete the transaction after {$retries} attempt(s).",
(int)$error->getCode(),
$error
);
}
sleep(rand(1, 3));
} finally {
if ($this->inTransaction()) {
$this->rollBack();
}
}
} while ($attempts < $retries);
return $return;
}
/**
* Returns a fake instance of the `Database` class.
*
* @return Database This instance will throw an exception if a method is called.
*
* @codeCoverageIgnore
*/
private static function mock()
{
return new class () extends Database {
// only methods that raise an error or throw an exception are overridden
protected function __construct()
{
// constructor arguments are not used
}
#[\ReturnTypeWillChange]
public function exec($statement)
{
static::fail();
}
#[\ReturnTypeWillChange]
public function prepare($query, $options = [])
{
static::fail();
}
#[\ReturnTypeWillChange]
public function query($query, $fetchMode = null, ...$fetchModeArgs)
{
static::fail();
}
#[\ReturnTypeWillChange]
public function beginTransaction()
{
static::fail();
}
#[\ReturnTypeWillChange]
public function commit()
{
static::fail();
}
#[\ReturnTypeWillChange]
public function rollBack()
{
static::fail();
}
private static function fail(): void
{
Exception::throw(
'ConnectionFailedException:LogicException',
'The app is currently running using a fake database, all database related operations will fail. ' .
'Add valid database credentials using "config/database.php" to resolve this issue'
);
}
};
}
}