-
-
Notifications
You must be signed in to change notification settings - Fork 24
Expand file tree
/
Copy pathMysqliQueryReflector.php
More file actions
344 lines (296 loc) · 11 KB
/
MysqliQueryReflector.php
File metadata and controls
344 lines (296 loc) · 11 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
<?php
declare(strict_types=1);
namespace staabm\PHPStanDba\QueryReflection;
use mysqli;
use mysqli_result;
use mysqli_sql_exception;
use PHPStan\ShouldNotHappenException;
use PHPStan\Type\Accessory\AccessoryNumericStringType;
use PHPStan\Type\Constant\ConstantArrayTypeBuilder;
use PHPStan\Type\Constant\ConstantIntegerType;
use PHPStan\Type\Constant\ConstantStringType;
use PHPStan\Type\FloatType;
use PHPStan\Type\IntegerType;
use PHPStan\Type\IntersectionType;
use PHPStan\Type\MixedType;
use PHPStan\Type\StringType;
use PHPStan\Type\Type;
use PHPStan\Type\TypeCombinator;
use PHPStan\Type\UnionType;
use staabm\PHPStanDba\Error;
use staabm\PHPStanDba\QuerySimulationException;
use staabm\PHPStanDba\Types\MysqlIntegerRanges;
final class MysqliQueryReflector implements QueryReflector
{
public const MYSQL_SYNTAX_ERROR_CODE = 1064;
public const MYSQL_UNKNOWN_COLUMN_IN_FIELDLIST = 1054;
public const MYSQL_UNKNOWN_TABLE = 1146;
public const MYSQL_HOST_NOT_FOUND = 2002;
private const MAX_CACHE_SIZE = 50;
/**
* @var mysqli
*/
private $db;
/**
* @var array<string, mysqli_sql_exception|list<object>|null>
*/
private $cache = [];
/**
* @var array<int, string>
*/
private $nativeTypes;
/**
* @var array<int, string>
*/
private $nativeFlags;
public function __construct(mysqli $mysqli)
{
$this->db = $mysqli;
// set a sane default.. atm this should not have any impact
$this->db->set_charset('utf8');
// enable exception throwing on php <8.1
mysqli_report(\MYSQLI_REPORT_ERROR | \MYSQLI_REPORT_STRICT);
$this->nativeTypes = [];
$this->nativeFlags = [];
$constants = get_defined_constants(true);
foreach ($constants['mysqli'] as $c => $n) {
if (!\is_int($n)) {
// skip bool constants like MYSQLI_IS_MARIADB
continue;
}
if (preg_match('/^MYSQLI_TYPE_(.*)/', $c, $m)) {
if (!\is_string($m[1])) {
throw new ShouldNotHappenException();
}
$this->nativeTypes[$n] = $m[1];
} elseif (preg_match('/MYSQLI_(.*)_FLAG$/', $c, $m)) {
if (!\is_string($m[1])) {
throw new ShouldNotHappenException();
}
if (!\array_key_exists($n, $this->nativeFlags)) {
$this->nativeFlags[$n] = $m[1];
}
}
}
}
public function validateQueryString(string $queryString): ?Error
{
$result = $this->simulateQuery($queryString);
if (!$result instanceof mysqli_sql_exception) {
return null;
}
$e = $result;
if (\in_array($e->getCode(), [self::MYSQL_SYNTAX_ERROR_CODE, self::MYSQL_UNKNOWN_COLUMN_IN_FIELDLIST, self::MYSQL_UNKNOWN_TABLE], true)) {
$message = $e->getMessage();
// make error string consistent across mysql/mariadb
$message = str_replace(' MySQL server', ' MySQL/MariaDB server', $message);
$message = str_replace(' MariaDB server', ' MySQL/MariaDB server', $message);
// to ease debugging, print the error we simulated
if (self::MYSQL_SYNTAX_ERROR_CODE === $e->getCode() && QueryReflection::getRuntimeConfiguration()->isDebugEnabled()) {
$simulatedQuery = QuerySimulation::simulate($queryString);
$message = $message."\n\nSimulated query: ".$simulatedQuery;
}
return new Error($message, $e->getCode());
}
return null;
}
/**
* @param self::FETCH_TYPE* $fetchType
*/
public function getResultType(string $queryString, int $fetchType): ?Type
{
$result = $this->simulateQuery($queryString);
if (!\is_array($result)) {
if (QueryReflection::getRuntimeConfiguration()->isDebugEnabled() && $result instanceof mysqli_sql_exception) {
throw new QuerySimulationException(sprintf("Cannot simulate query\n %s \nbecause of a sql error: %s", $queryString, $result->getMessage()));
}
return null;
}
$arrayBuilder = ConstantArrayTypeBuilder::createEmpty();
$i = 0;
foreach ($result as $val) {
if (!property_exists($val, 'name') || !property_exists($val, 'type') || !property_exists($val, 'flags') || !property_exists($val, 'length')) {
throw new ShouldNotHappenException();
}
if (self::FETCH_TYPE_ASSOC === $fetchType || self::FETCH_TYPE_BOTH === $fetchType) {
$arrayBuilder->setOffsetValueType(
new ConstantStringType($val->name),
$this->mapMysqlToPHPStanType($val->type, $val->flags, $val->length)
);
}
if (self::FETCH_TYPE_NUMERIC === $fetchType || self::FETCH_TYPE_BOTH === $fetchType) {
$arrayBuilder->setOffsetValueType(
new ConstantIntegerType($i),
$this->mapMysqlToPHPStanType($val->type, $val->flags, $val->length)
);
}
++$i;
}
return $arrayBuilder->getArray();
}
/**
* @return mysqli_sql_exception|list<object>|null
*/
private function simulateQuery(string $queryString)
{
if (\array_key_exists($queryString, $this->cache)) {
return $this->cache[$queryString];
}
if (\count($this->cache) > self::MAX_CACHE_SIZE) {
// make room for the next element by randomly removing a existing one
array_shift($this->cache);
}
$simulatedQuery = QuerySimulation::simulate($queryString);
if (null === $simulatedQuery) {
return $this->cache[$queryString] = null;
}
try {
$result = $this->db->query($simulatedQuery);
if (!$result instanceof mysqli_result) {
return $this->cache[$queryString] = null;
}
$resultInfo = $result->fetch_fields();
$result->free();
return $this->cache[$queryString] = $resultInfo;
} catch (mysqli_sql_exception $e) {
return $this->cache[$queryString] = $e;
}
}
private function mapMysqlToPHPStanType(int $mysqlType, int $mysqlFlags, int $length): Type
{
$numeric = false;
$notNull = false;
$unsigned = false;
$autoIncrement = false;
foreach ($this->flags2txt($mysqlFlags) as $flag) {
switch ($flag) {
case 'NUM':
$numeric = true;
break;
case 'NOT_NULL':
$notNull = true;
break;
case 'AUTO_INCREMENT':
$autoIncrement = true;
break;
case 'UNSIGNED':
$unsigned = true;
break;
// ???
case 'PRI_KEY':
case 'PART_KEY':
case 'MULTIPLE_KEY':
case 'NO_DEFAULT_VALUE':
}
}
$phpstanType = null;
$mysqlIntegerRanges = new MysqlIntegerRanges();
if ($numeric) {
if ($unsigned) {
if (3 === $length) { // bool aka tinyint(1)
$phpstanType = $mysqlIntegerRanges->unsignedTinyInt();
}
if (4 === $length) {
$phpstanType = $mysqlIntegerRanges->unsignedTinyInt();
}
if (5 === $length) {
$phpstanType = $mysqlIntegerRanges->unsignedSmallInt();
}
if (8 === $length) {
$phpstanType = $mysqlIntegerRanges->unsignedMediumInt();
}
if (10 === $length) {
$phpstanType = $mysqlIntegerRanges->unsignedInt();
}
if (20 === $length) {
$phpstanType = $mysqlIntegerRanges->unsignedBigInt();
}
} else {
if (1 == $length) {
$phpstanType = $mysqlIntegerRanges->signedTinyInt();
}
if (4 === $length) {
$phpstanType = $mysqlIntegerRanges->signedTinyInt();
}
if (6 === $length) {
$phpstanType = $mysqlIntegerRanges->signedSmallInt();
}
if (9 === $length) {
$phpstanType = $mysqlIntegerRanges->signedMediumInt();
}
if (11 === $length) {
$phpstanType = $mysqlIntegerRanges->signedInt();
}
if (20 === $length) {
$phpstanType = $mysqlIntegerRanges->signedBigInt();
}
if (22 === $length) {
$phpstanType = $mysqlIntegerRanges->signedBigInt();
}
}
}
if ($autoIncrement) {
$phpstanType = $mysqlIntegerRanges->unsignedInt();
}
if (null === $phpstanType) {
switch ($this->type2txt($mysqlType)) {
case 'DOUBLE':
case 'NEWDECIMAL':
$phpstanType = new FloatType();
break;
case 'LONGLONG':
case 'LONG':
case 'SHORT':
case 'YEAR':
case 'BIT':
case 'INT24':
$phpstanType = new IntegerType();
break;
case 'BLOB':
case 'CHAR':
case 'STRING':
case 'VAR_STRING':
case 'JSON':
case 'DATE':
case 'TIME':
case 'DATETIME':
case 'TIMESTAMP':
$phpstanType = new StringType();
break;
default:
$phpstanType = new MixedType();
}
}
if (QueryReflection::getRuntimeConfiguration()->isStringifyTypes()) {
$numberType = new UnionType([new IntegerType(), new FloatType()]);
$isNumber = $numberType->isSuperTypeOf($phpstanType)->yes();
if ($isNumber) {
$phpstanType = new IntersectionType([
new StringType(),
new AccessoryNumericStringType(),
]);
}
}
if (false === $notNull) {
$phpstanType = TypeCombinator::addNull($phpstanType);
}
return $phpstanType;
}
private function type2txt(int $typeId): ?string
{
return \array_key_exists($typeId, $this->nativeTypes) ? $this->nativeTypes[$typeId] : null;
}
/**
* @return list<string>
*/
private function flags2txt(int $flagId): array
{
$result = [];
foreach ($this->nativeFlags as $n => $t) {
if ($flagId & $n) {
$result[] = $t;
}
}
return $result;
}
}