Repository navigation
Expand file tree
/
Copy pathMySqlConnection.php
More file actions
executable file
·316 lines (274 loc) · 8.38 KB
/
Copy pathMySqlConnection.php
File metadata and controls
executable file
·316 lines (274 loc) · 8.38 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 Illuminate\Database;
use Closure;
use Exception;
use Illuminate\Database\Query\Grammars\MySqlGrammar as QueryGrammar;
use Illuminate\Database\Query\Processors\MySqlProcessor;
use Illuminate\Database\Schema\Grammars\MySqlGrammar as SchemaGrammar;
use Illuminate\Database\Schema\MySqlBuilder;
use Illuminate\Database\Schema\MySqlSchemaState;
use Illuminate\Filesystem\Filesystem;
use Illuminate\Support\Str;
use PDO;
use RuntimeException;
class MySqlConnection extends Connection
{
/**
* The last inserted ID generated by the server.
*
* @var string|int|null
*/
protected $lastInsertId;
/**
* {@inheritdoc}
*/
public function getDriverTitle()
{
return $this->isMaria() ? 'MariaDB' : 'MySQL';
}
/**
* Run an insert statement against the database.
*
* @param string $query
* @param array $bindings
* @param string|null $sequence
* @return bool
*/
public function insert($query, $bindings = [], $sequence = null)
{
return $this->run($query, $bindings, function ($query, $bindings) use ($sequence) {
if ($this->pretending()) {
return true;
}
$statement = $this->getPdo()->prepare($query);
$this->bindValues($statement, $this->prepareBindings($bindings));
$this->recordsHaveBeenModified();
$result = $statement->execute();
$this->lastInsertId = $this->getPdo()->lastInsertId($sequence);
return $result;
});
}
/**
* Execute the given callback using OLAP workload.
*
* @template TReturn
*
* @param (\Closure($this): TReturn) $callback
* @return TReturn
*/
public function olap(Closure $callback)
{
if (! $this->isVitess()) {
return $callback($this);
}
$this->setWorkload('olap');
try {
return $callback($this);
} finally {
$this->setWorkload('oltp');
}
}
/**
* Set the Vitess workload for the connection.
*
* @param 'olap'|'oltp' $workload
* @return void
*/
protected function setWorkload($workload)
{
$this->run("set workload = '{$workload}'", [], function ($query) {
if ($this->pretending()) {
return true;
}
$this->getPdo()->exec($query);
if ($this->readPdo instanceof Closure) {
$this->readPdo = call_user_func($this->readPdo);
}
$this->readPdo?->exec($query);
return true;
});
}
/**
* Escape a binary value for safe SQL embedding.
*
* @param string $value
* @return string
*/
protected function escapeBinary($value)
{
$hex = bin2hex($value);
return "x'{$hex}'";
}
/**
* Determine if the given database exception was caused by a unique constraint violation.
*
* @param \Exception $exception
* @return bool
*/
protected function isUniqueConstraintError(Exception $exception)
{
return (bool) preg_match('#Integrity constraint violation: 1062#i', $exception->getMessage());
}
/**
* Determine if the given database exception was caused by an invalid or out of range value.
*/
protected function isDataTypeError(Exception $exception): bool
{
return in_array($exception->getCode(), [
'22001', // String data, right truncation
'22003', // Numeric value out of range
'22007', // Invalid datetime format
], true)
// 1264: Out of range value, 1292: Truncated incorrect value,
// 1366: Incorrect integer value, 1406: Data too long
|| (bool) preg_match('#General error: (1264|1292|1366|1406)\b#i', $exception->getMessage());
}
/**
* Extract the index that caused a unique constraint violation.
*
* @param Exception $exception
* @return array{index: string|null, columns: list<string>}
*/
protected function parseUniqueConstraintViolation(Exception $exception): array
{
preg_match(
'#Duplicate entry \'.*?\' for key \'(?:.*?\.)?(.+?)\'#i',
$exception->getMessage(),
$matches
);
return ['columns' => [], 'index' => $matches[1] ?? null];
}
/**
* Get the connection's last insert ID.
*
* @return string|int|null
*/
public function getLastInsertId()
{
return $this->lastInsertId;
}
/**
* Determine if the connected database is a MariaDB database.
*
* @return bool
*/
public function isMaria()
{
return str_contains($this->getPdo()->getAttribute(PDO::ATTR_SERVER_VERSION), 'MariaDB');
}
/**
* Determine if the connected database is a Vitess database.
*
* @return bool
*/
public function isVitess()
{
return Str::contains($this->getPdo()->getAttribute(PDO::ATTR_SERVER_VERSION), ['Vitess', 'PlanetScale'], ignoreCase: true);
}
/**
* Get the server version for the connection.
*
* @return string
*/
public function getServerVersion(): string
{
return str_contains($version = parent::getServerVersion(), 'MariaDB')
? Str::between($version, '5.5.5-', '-MariaDB')
: $version;
}
/**
* Get the ID of the last committed transaction.
*
* @return string
*
* @throws \RuntimeException
*/
public function getLastCommitId()
{
$gtid = $this->usingWritePdo(fn () => $this->selectOne('select @@log_bin as log_bin, @@global.gtid_mode as mode, @@global.gtid_executed as executed'));
if (! $gtid->log_bin || $gtid->mode !== 'ON') {
throw new RuntimeException("The MySQL configuration 'log_bin = ON' and 'gtid_mode = ON' are required to retrieve the last commit ID.");
}
return $gtid->executed;
}
/**
* Calculate the commit ID for a set of commit IDs that includes all of them.
*
* @param string[] $values
* @return string
*
* @throws \RuntimeException
*/
public function mergeCommitIds(array $values)
{
if ($values === []) {
throw new RuntimeException("The list of commit IDs can't be empty.");
}
// Normalize the joined GTID sets with gtid_subtract to keep the result as small as possible...
return $this->scalar("select gtid_subtract(?, '')", [implode(',', $values)]);
}
/**
* Determine if the given commit ID has been applied.
*
* @param string $value
* @param int $wait
* @return bool
*/
public function hasCommitId(string $value, int $wait = 0)
{
if ($wait <= 0) {
return (bool) $this->scalar('select gtid_subset(?, @@global.gtid_executed)', [$value]);
}
return (int) $this->scalar('select wait_for_executed_gtid_set(?, ?)', [$value, $wait]) === 0;
}
/**
* Get the default query grammar instance.
*
* @return \Illuminate\Database\Query\Grammars\MySqlGrammar
*/
protected function getDefaultQueryGrammar()
{
return new QueryGrammar($this);
}
/**
* Get a schema builder instance for the connection.
*
* @return \Illuminate\Database\Schema\MySqlBuilder
*/
public function getSchemaBuilder()
{
if (is_null($this->schemaGrammar)) {
$this->useDefaultSchemaGrammar();
}
return new MySqlBuilder($this);
}
/**
* Get the default schema grammar instance.
*
* @return \Illuminate\Database\Schema\Grammars\MySqlGrammar
*/
protected function getDefaultSchemaGrammar()
{
return new SchemaGrammar($this);
}
/**
* Get the schema state for the connection.
*
* @param \Illuminate\Filesystem\Filesystem|null $files
* @param callable|null $processFactory
* @return \Illuminate\Database\Schema\MySqlSchemaState
*/
public function getSchemaState(?Filesystem $files = null, ?callable $processFactory = null)
{
return new MySqlSchemaState($this, $files, $processFactory);
}
/**
* Get the default post processor instance.
*
* @return \Illuminate\Database\Query\Processors\MySqlProcessor
*/
protected function getDefaultPostProcessor()
{
return new MySqlProcessor;
}
}