-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathDatabase.php
More file actions
316 lines (284 loc) · 8.01 KB
/
Database.php
File metadata and controls
316 lines (284 loc) · 8.01 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
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
<?php
namespace Tivins\Database;
use Exception;
use PDO;
use PDOException;
use Tivins\Database\Connectors\Connector;
use Tivins\Database\Connectors\ConnectorType;
use Tivins\Database\Exceptions\ConditionException;
use Tivins\Database\Exceptions\ConnectionException;
use Tivins\Database\Exceptions\DatabaseException;
/**
*
*/
class Database
{
/**
*
*/
private string $prefix = '';
/**
* @var Callable|null
*/
private $logCallback = null;
/**
* @var Callable|null
*/
private $failureCallback = null;
private PDO $handler;
/**
* Initialize a new Database object from the given connector.
* @throws ConnectionException
*/
public function __construct(private readonly Connector $connector)
{
$this->handler = $connector->connect();
$this->configureAttributes();
}
/**
*
*/
private function configureAttributes(): void
{
$this->handler->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_OBJ);
$this->handler->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
/**
* Define a string prefix for all tables of the database.
* For example, if a prefix is set to `test_`, then, the table name `user` will be turned into `test_user`.
*
* @param string $prefix
* @return $this
*/
public function setTablePrefix(string $prefix): self
{
$this->prefix = $prefix;
return $this;
}
/**
* Defines a callback sent before executing the query.
* The prototype of the callback should be :
*
* php function(string $sql, array $parameters): void;
*
* if $failureCallback is null, the callback feature is cancelled.
*/
public function setLogCallback(?callable $callback): void
{
$this->logCallback = $callback;
}
/**
* Define a failure callback called when an exception is thrown in the query() function.
* The prototype of the callback should be :
*
* function(Database $db, DatabaseException $exception): bool;
*
* Where the function's return TRUE to abort exception, or FALSE to keep unchanged the exception flow.
*
* if $failureCallback is null, the callback feature is cancelled.
*
* @param Callable|null $failureCallback
* @return Database
*/
public function setFailureCallback(?callable $failureCallback): Database
{
$this->failureCallback = $failureCallback;
return $this;
}
/**
* Returns the ID of the last inserted row or sequence value.
*
* @alias PDO::lastInsertId()
*/
public function lastId(): int
{
return $this->handler->lastInsertId();
}
/**
* Creates a select query for $tableName.
*/
public function select(string $tableName, string $alias): SelectQuery
{
return new SelectQuery($this, $this->prefixTableName($tableName), $alias);
}
/**
* Creates a MergeQuery for $tableName.
*/
public function selectInsert(string $tableName): SelectInsertQuery
{
return new SelectInsertQuery($this, $tableName);
}
/**
* Creates a MergeQuery for $tableName.
*/
public function merge(string $tableName): MergeQuery
{
return new MergeQuery($this, $tableName);
}
/**
* Creates an InsertQuery for $tableName.
*/
public function insert(string $tableName): InsertQuery
{
return new InsertQuery($this, $this->prefix . $tableName);
}
/**
* Creates an UpdateQuery for $tableName.
*/
public function update(string $tableName): UpdateQuery
{
return new UpdateQuery($this, $this->prefix . $tableName);
}
/**
* Creates a DeleteQuery for $tableName.
*/
public function delete(string $tableName): DeleteQuery
{
return new DeleteQuery($this, $this->prefix . $tableName);
}
/**
* Creates a CreateQuery for $tableName.
*/
public function create(string $tableName): CreateQuery
{
return new CreateQuery($this, $this->prefix . $tableName, $this->connector);
}
public function or(): Conditions
{
return new Conditions(Conditions::MODE_OR);
}
/**
*
*/
public function and(): Conditions
{
return new Conditions(Conditions::MODE_AND);
}
/**
* Shortcut to get a single row from the given table, column, value.
*
* @throws DatabaseException|ConditionException
* @example
* ```php
* $db_user = $db->fetchRow('users', 'uid', $userId);
* ```
*/
public function fetchRow(string $tableName, string $column, $value): ?object
{
return $this->select($tableName, 't')
->addFields('t')
->condition($column, $value)
->execute()
->fetch();
}
/**
* @throws DatabaseException
*/
public function dropTable(string $tableName, bool $prefix = true): self
{
$tableName = $prefix ? $this->prefixTableName($tableName) : $tableName;
$this->query("drop table if exists `$tableName`");
return $this;
}
/**
* @throws Exception
*/
public function getTables(): array
{
return $this->query($this->getConnectorType()->getShowTablesQuery())->fetchCol();
}
/**
* @throws DatabaseException
*/
public function dropAllTables(): array
{
$tables = $this->getTables();
foreach ($tables as $table) {
$this->dropTable($table, prefix: false);
}
return $tables;
}
public function prefixTableName(string $tableName): string
{
return $this->prefix . $tableName;
}
/**
* @throws DatabaseException
*/
public function query(string $query, array $parameters = []): Statement
{
if ($this->logCallback) {
call_user_func($this->logCallback, $query, $parameters);
}
$sth = $this->handler->prepare($query);
try {
$sth->execute($parameters);
} catch (PDOException $exception) {
$cancelException = false;
if ($this->failureCallback && call_user_func($this->failureCallback, $this, $exception)) {
$cancelException = true;
}
if (!$cancelException) {
throw new DatabaseException($exception);
}
}
return new Statement($sth);
}
/**
* Destroy all records of the table $tableName and reset auto-increment index.
*
* @throws DatabaseException
*/
public function truncateTable(string $tableName): self
{
$tableName = $this->prefixTableName($tableName);
$this->query("truncate table `$tableName`");
return $this;
}
/**
* Gets the columns used as primary key.
*
* @throws DatabaseException
*/
public function getPrimary(string $tableName): array
{
$tableName = $this->prefixTableName($tableName);
$keys = $this->query('SHOW KEYS FROM ' . $tableName . ' where key_name = \'PRIMARY\'')->fetchAll();
return array_column($keys, 'Column_name');
}
/**
* Alias of PDO::beginTransaction()
* @throws PDOException
*/
public function transaction(): void
{
$this->handler->beginTransaction();
}
/**
* Alias of PDO::rollback()
* @throws PDOException
*/
public function rollback(): void
{
$this->handler->rollBack();
}
/**
* Alias of PDO::commit()
* @throws PDOException
*/
public function commit(): void
{
$this->handler->commit();
}
/**
* Registers a User Defined Function for use in SQL statements.
*/
public function sqliteCreateFunction($function_name, $callback, $num_args = -1, $flags = 0): bool
{
return $this->handler->sqliteCreateFunction($function_name, $callback, $num_args, $flags);
}
public function getConnectorType(): ConnectorType
{
return $this->connector->getType();
}
}