Repository navigation
Expand file tree
/
Copy pathDatabase.php
More file actions
581 lines (462 loc) · 14.2 KB
/
Copy pathDatabase.php
File metadata and controls
581 lines (462 loc) · 14.2 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
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
<?php
/**
* This file is part of the Nette Framework (https://nette.org)
* Copyright (c) 2004 David Grudl (https://davidgrudl.com)
*/
declare(strict_types=1);
namespace Nette\Database;
use JetBrains\PhpStorm\Language;
use Nette;
use Nette\Caching\Cache;
use Nette\Utils\Arrays;
/**
* Manages database connection and executes SQL queries.
*/
class Database
{
private const Drivers = [
'pdo-mssql' => Drivers\PDO\MSSQL\Driver::class,
'pdo-mysql' => Drivers\PDO\MySQL\Driver::class,
'pdo-oci' => Drivers\PDO\OCI\Driver::class,
'pdo-odbc' => Drivers\PDO\ODBC\Driver::class,
'pdo-pgsql' => Drivers\PDO\PgSQL\Driver::class,
'pdo-sqlite' => Drivers\PDO\SQLite\Driver::class,
'pdo-sqlsrv' => Drivers\PDO\SQLSrv\Driver::class,
];
private const TypeConverterOptions = ['convertBoolean', 'convertDateTime', 'convertDecimal', 'newDateTime'];
/** @var array<callable(self): void> Occurs after connection is established */
public array $onConnect = [];
/** @var array<callable(self, Result|DriverException): void> Occurs after query is executed */
public array $onQuery = [];
private Drivers\Driver $driver;
private ?Drivers\Connection $connection = null;
private Drivers\Engine $engine;
private SqlPreprocessor $preprocessor;
private TypeConverter $typeConverter;
private ?SqlLiteral $lastQuery = null;
private int $transactionDepth = 0;
private bool $autoCommit = true;
private ?Cache $cache = null;
private ?Conventions $conventions = null;
private ?Structure $structure = null;
public static function createFromParameters(
#[\SensitiveParameter]
...$params,
): self
{
$params = count($params) === 1 && is_array($params[0] ?? null) ? $params[0] : $params;
if ($class = $params['driverClass'] ?? null) {
if (!is_subclass_of($class, Drivers\Driver::class)) {
throw new \LogicException("Driver class '$class' is not subclass of " . Drivers\Driver::class);
}
unset($params['driverClass']);
} elseif ($driver = $params['driver'] ?? null) {
$class = self::Drivers[$driver] ?? throw new \LogicException("Unknown driver '$driver'.");
unset($params['driver']);
} elseif ($dsn = $params['dsn'] ?? null) {
$driver = explode(':', $dsn)[0];
$class = self::Drivers['pdo-' . $driver] ?? throw new \LogicException("Unknown PDO driver '$driver'.");
} else {
throw new \LogicException("Missing options 'driver', 'driverClass' or 'dsn'.");
}
$args = array_diff_key($params, array_flip(self::TypeConverterOptions));
$explorer = new self(new $class(...$args));
array_map(fn($opt) => isset($params[$opt]) && ($explorer->typeConverter->$opt = (bool) $params[$opt]), self::TypeConverterOptions);
$this->autoCommit = (bool) ($params['autoCommit'] ?? true);
return $explorer;
}
public static function createFromDsn(
string $dsn,
?string $username = null,
#[\SensitiveParameter]
?string $password = null,
array $options = [],
): self
{
$params = compact('dsn', 'username', 'password', 'options');
foreach ($options as $key => $value) {
if (!is_int($key) && $value !== null) {
$params[$key] = $value;
unset($params['options'][$key]);
}
}
unset($params['lazy']);
return self::createFromParameters($params);
}
public function __construct(
Drivers\Driver|string $driver,
) {
if (is_string($driver)) { // back compatibility with version 3.x
$explorer = self::createFromDsn(...func_get_args());
[$this->driver, $this->typeConverter] = [$explorer->driver, $explorer->typeConverter];
} else {
$this->driver = $driver;
$this->typeConverter = new TypeConverter;
}
}
/**
* Connects to the database server if not already connected.
* @throws ConnectionException
*/
public function connect(): void
{
if ($this->connection) {
return;
}
try {
$this->connection = $this->driver->connect();
} catch (DriverException $e) {
throw ConnectionException::from($e);
}
if (!$this->autoCommit) {
$this->beginTransaction();
}
Arrays::invoke($this->onConnect, $this);
}
/**
* Disconnects and connects to database again.
*/
public function reconnect(): void
{
$this->disconnect();
$this->connect();
}
/**
* Disconnects from database.
*/
public function disconnect(): void
{
$this->connection = null;
}
#[\Deprecated]
public function getDsn(): string
{
throw new Nette\DeprecatedException(__METHOD__ . '() is deprecated.');
}
#[\Deprecated('use getConnection()->getNativeConnection()')]
public function getPdo(): \PDO
{
trigger_error(__METHOD__ . '() is deprecated, use getConnection()->getNativeConnection()', E_USER_DEPRECATED);
return $this->getConnection()->getNativeConnection();
}
public function getConnection(): Drivers\Connection
{
$this->connect();
return $this->connection;
}
#[\Deprecated('use getConnection()')]
public function getSupplementalDriver(): Drivers\Connection
{
trigger_error(__METHOD__ . '() is deprecated, use getConnection()', E_USER_DEPRECATED);
return $this->getConnection();
}
public function getDatabaseEngine(): Drivers\Engine
{
return $this->engine ??= $this->driver->createEngine(new Drivers\Accessory\LazyConnection($this->getConnection(...)));
}
public function getServerVersion(): string
{
return $this->getConnection()->getServerVersion();
}
public function getReflection(): Reflection
{
return new Reflection($this->getDatabaseEngine());
}
public function getTypeConverter(): TypeConverter
{
return $this->typeConverter;
}
#[\Deprecated]
public function setRowNormalizer(?callable $normalizer): static
{
throw new Nette\DeprecatedException(__METHOD__ . "() is deprecated, configure 'convert*' options instead.");
}
/**
* Returns the ID of the last inserted row, or the last value from a sequence.
*/
public function getInsertId(?string $sequence = null): int|string
{
try {
return $this->getConnection()->getInsertId($sequence);
} catch (DriverException $e) {
throw $this->convertException($e);
}
}
/**
* Quotes string for use in SQL.
*/
public function quote(string $string): string
{
return $this->getConnection()->quote($string);
}
/**
* Starts a transaction.
* @throws \LogicException when called inside a transaction
*/
public function beginTransaction(): void
{
if ($this->transactionDepth === 0) {
$this->logOperation($this->getConnection()->beginTransaction(...), new SqlLiteral('BEGIN TRANSACTION'));
} else {
$this->createSavepoint($this->transactionDepth - 1);
}
$this->transactionDepth++;
}
/**
* Commits current transaction.
* @throws \LogicException when called inside a transaction
*/
public function commit(): void
{
if ($this->transactionDepth === 0) {
throw new \LogicException('No active transaction to commit.');
} elseif (--$this->transactionDepth === 0) {
$this->logOperation($this->getConnection()->commit(...), new SqlLiteral('COMMIT'));
if (!$this->autoCommit) {
$this->beginTransaction();
}
} else {
$this->releaseSavepoint($this->transactionDepth);
}
}
/**
* Rolls back current transaction.
* @throws \LogicException when called inside a transaction
*/
public function rollBack(): void
{
if ($this->transactionDepth === 0) {
throw new \LogicException('No active transaction to roll back.');
} elseif (--$this->transactionDepth === 0) {
$this->logOperation($this->getConnection()->rollBack(...), new SqlLiteral('ROLLBACK'));
if (!$this->autoCommit) {
$this->beginTransaction();
}
} else {
$this->rollbackToSavepoint($this->transactionDepth);
}
}
/**
* Executes callback inside a transaction. Supports nesting.
* @param callable(static): mixed $callback
*/
public function transaction(callable $callback): mixed
{
$this->beginTransaction();
try {
$res = $callback($this);
$this->commit();
return $res;
} catch (\Throwable $e) {
$this->rollBack();
throw $e;
}
}
public function setAutoCommit(bool $state): void
{
if ($this->autoCommit === $state) {
return;
}
while ($this->transactionDepth > 0) {
if (--$this->transactionDepth === 0) {
$this->query('::commit');
} else {
$this->releaseSavepoint($this->transactionDepth);
}
}
$this->autoCommit = $state;
if (!$state && $this->connection) {
$this->beginTransaction();
}
}
public function createSavepoint(int $level): void
{
$this->query('SAVEPOINT LEVEL' . $level); // TODO: to driver, logOperation
}
public function releaseSavepoint(int $level): void
{
$this->query('RELEASE SAVEPOINT LEVEL' . $level);
}
/**
* Generates and executes SQL query.
* @param literal-string $sql
*/
public function query(#[Language('SQL')] string $sql, #[Language('GenericSQL')] mixed ...$params): Result
{
[$sql, $params] = $this->preprocess($sql, ...$params);
return $this->logOperation(
fn() => $this->connection->query($sql, $params),
$this->lastQuery = new SqlLiteral($sql, $params),
);
}
/**
* @param literal-string $sql
* @param array<mixed> $params
*/
#[\Deprecated('use query()')]
public function queryArgs(string $sql, array $params): Result
{
trigger_error(__METHOD__ . '() is deprecated, use query()', E_USER_DEPRECATED);
return $this->query($sql, ...$params);
}
/**
* Preprocesses SQL query with parameter substitution and returns the resulting SQL and bound parameters.
* @param literal-string $sql
* @return array{string, array<mixed>}
*/
public function preprocess(string $sql, mixed ...$params): array
{
$this->connect();
$this->preprocessor ??= new SqlPreprocessor($this);
return $params
? $this->preprocessor->process(func_get_args())
: [$sql, []];
}
/** @param \Closure(): (Drivers\Result|void) $callback */
private function logOperation(\Closure $callback, SqlLiteral $query): Result
{
try {
$time = microtime(as_float: true);
$result = $callback();
$time = microtime(as_float: true) - $time;
} catch (DriverException $e) {
$e = $this->convertException($e);
Arrays::invoke($this->onQuery, $this, $e);
throw $e;
}
$result = new Result($this, $query, $result, $time);
Arrays::invoke($this->onQuery, $this, $result);
return $result;
}
public function getLastQuery(): ?SqlLiteral
{
return $this->lastQuery;
}
#[\Deprecated('use getLastQuery()->getSql()')]
public function getLastQueryString(): ?string
{
trigger_error(__METHOD__ . '() is deprecated, use getLastQuery()->getSql()', E_USER_DEPRECATED);
return $this->lastQuery?->getSql();
}
private function convertException(DriverException $e): DriverException
{
$class = $this->getDatabaseEngine()->classifyException($e);
return $class ? $class::from($e) : $e;
}
/********************* shortcuts ****************d*g**/
/**
* Executes SQL query and returns the first row, or null if no rows were returned.
* @param literal-string $sql
*/
public function fetch(#[Language('SQL')] string $sql, #[Language('GenericSQL')] mixed ...$params): ?Row
{
return $this->query($sql, ...$params)->fetch();
}
/**
* Executes SQL query and returns the first row as an associative array, or null.
* @param literal-string $sql
* @return ?array<mixed>
*/
public function fetchAssoc(#[Language('SQL')] string $sql, #[Language('GenericSQL')] mixed ...$params): ?array
{
return $this->query($sql, ...$params)->fetchAssoc();
}
/**
* Executes SQL query and returns the first field of the first row, or null.
* @param literal-string $sql
*/
public function fetchField(#[Language('SQL')] string $sql, #[Language('GenericSQL')] mixed ...$params): mixed
{
return $this->query($sql, ...$params)->fetchField();
}
/**
* Executes SQL query and returns the first row as an indexed array, or null.
* @param literal-string $sql
* @return ?list<mixed>
*/
public function fetchList(#[Language('SQL')] string $sql, #[Language('GenericSQL')] mixed ...$params): ?array
{
return $this->query($sql, ...$params)->fetchList();
}
/**
* Executes SQL query and returns the first row as an indexed array, or null.
* @param literal-string $sql
* @return ?list<mixed>
*/
public function fetchFields(#[Language('SQL')] string $sql, #[Language('GenericSQL')] mixed ...$params): ?array
{
return $this->query($sql, ...$params)->fetchList();
}
/**
* Executes SQL query and returns rows as key-value pairs.
* @param literal-string $sql
* @return array<mixed, mixed>
*/
public function fetchPairs(#[Language('SQL')] string $sql, #[Language('GenericSQL')] mixed ...$params): array
{
return $this->query($sql, ...$params)->fetchPairs();
}
/**
* Executes SQL query and returns all rows as an array of Row objects.
* @param literal-string $sql
* @return list<Row>
*/
public function fetchAll(#[Language('SQL')] string $sql, #[Language('GenericSQL')] mixed ...$params): array
{
return $this->query($sql, ...$params)->fetchAll();
}
/**
* Executes SQL query and returns all rows as an array of arrays.
* Useful because the rows can be typed using @var.
* @param literal-string $sql
* @return list<array>
*/
public function fetchAllAssoc(#[Language('SQL')] string $sql, #[Language('GenericSQL')] mixed ...$params): array
{
return $this->query($sql, ...$params)->fetchAllAssoc();
}
/**
* Creates SQL literal value.
*/
public static function literal(string $value, mixed ...$params): SqlLiteral
{
return new SqlLiteral($value, $params);
}
/********************* active row ****************d*g**/
public function table(string $table): Table\Selection
{
return new Table\Selection($this, $table);
}
public function setCache(Cache $cache): static
{
if (isset($this->structure)) {
throw new \LogicException('Cannot set cache after structure is created.');
}
$this->cache = $cache;
return $this;
}
/** @internal */
public function getCache(): ?Cache
{
return $this->cache;
}
public function setConventions(Conventions $conventions): static
{
if (isset($this->conventions)) {
throw new \LogicException('Conventions are already set.');
}
$this->conventions = $conventions;
return $this;
}
/** @internal */
public function getConventions(): Conventions
{
return $this->conventions ??= new Conventions\DiscoveredConventions($this->getStructure());
}
/** @internal */
public function getStructure(): Structure
{
return $this->structure ??= new Structure($this->getDatabaseEngine(), $this->getCache());
}
}
class_exists(Connection::class);