forked from doctrine/dbal
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Connection.php
117 lines (95 loc) · 2.74 KB
/
Connection.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
<?php
declare(strict_types=1);
namespace Doctrine\DBAL\Driver\Mysqli;
use Doctrine\DBAL\Driver\Connection as ConnectionInterface;
use Doctrine\DBAL\Driver\Exception;
use Doctrine\DBAL\Driver\Mysqli\Exception\ConnectionError;
use mysqli;
use mysqli_sql_exception;
final class Connection implements ConnectionInterface
{
/**
* Name of the option to set connection flags
*/
public const OPTION_FLAGS = 'flags';
private mysqli $connection;
/**
* @internal The connection can be only instantiated by its driver.
*/
public function __construct(mysqli $connection)
{
$this->connection = $connection;
}
public function getServerVersion(): string
{
return $this->connection->get_server_info();
}
public function prepare(string $sql): Statement
{
try {
$stmt = $this->connection->prepare($sql);
} catch (mysqli_sql_exception $e) {
throw ConnectionError::upcast($e);
}
if ($stmt === false) {
throw ConnectionError::new($this->connection);
}
return new Statement($stmt);
}
public function query(string $sql): Result
{
return $this->prepare($sql)->execute();
}
public function quote(string $value): string
{
return "'" . $this->connection->escape_string($value) . "'";
}
public function exec(string $sql): int
{
try {
$result = $this->connection->query($sql);
} catch (mysqli_sql_exception $e) {
throw ConnectionError::upcast($e);
}
if ($result === false) {
throw ConnectionError::new($this->connection);
}
return $this->connection->affected_rows;
}
public function lastInsertId(): int|string
{
$lastInsertId = $this->connection->insert_id;
if ($lastInsertId === 0) {
throw Exception\NoIdentityValue::new();
}
return $this->connection->insert_id;
}
public function beginTransaction(): void
{
$this->connection->begin_transaction();
}
public function commit(): void
{
try {
if (! $this->connection->commit()) {
throw ConnectionError::new($this->connection);
}
} catch (mysqli_sql_exception $e) {
throw ConnectionError::upcast($e);
}
}
public function rollBack(): void
{
try {
if (! $this->connection->rollback()) {
throw ConnectionError::new($this->connection);
}
} catch (mysqli_sql_exception $e) {
throw ConnectionError::upcast($e);
}
}
public function getNativeConnection(): mysqli
{
return $this->connection;
}
}