-
Notifications
You must be signed in to change notification settings - Fork 49
Expand file tree
/
Copy pathInsertMultipleParser.php
More file actions
79 lines (67 loc) · 2.35 KB
/
InsertMultipleParser.php
File metadata and controls
79 lines (67 loc) · 2.35 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
<?php
namespace Vimeo\MysqlEngine\Parser;
use Vimeo\MysqlEngine\Query\CreateQuery;
use Vimeo\MysqlEngine\Query\Expression\Expression;
use Vimeo\MysqlEngine\TokenType;
use Vimeo\MysqlEngine\Query\InsertQuery;
final class InsertMultipleParser
{
/**
* @return array<string, CreateQuery>
*/
public function parse(string $sql): array
{
return self::walk($this->splitStatements($sql));
}
/**
* @var list<string>
*/
private $tokens = [];
/**
* @var array<int, array{0:int, 1:int}>
*/
private $sourceMap = [];
/**
* @return non-empty-list<string>
*/
private function splitStatements(string $sql): array
{
$re_split_sql = '%
# Match an SQL record ending with ";"
\s* # Discard leading whitespace.
( # $1: Trimmed non-empty SQL record.
(?: # Group for content alternatives.
\'[^\'\\\\]*(?:\\\\.[^\'\\\\]*)*\' # Either a single quoted string,
| "[^"\\\\]*(?:\\\\.[^"\\\\]*)*" # or a double quoted string,
| /\*[^*]*\*+(?:[^*/][^*]*\*+)*/ # or a multi-line comment,
| \#.* # or a # single line comment,
| --.* # or a -- single line comment,
| [^"\';#] # or one non-["\';#-]
)+ # One or more content alternatives
(?:;|$) # Record end is a ; or string end.
) # End $1: Trimmed SQL record.
%xs';
if (preg_match_all($re_split_sql, $sql, $matches)) {
$statements = $matches[1];
}
return $statements ?? [];
}
/**
* @param array<string> $statements
*
* @return array<string, InsertQuery>
*/
private static function walk(array $statements)
{
$result = [];
foreach ($statements as $statement) {
$statement = trim($statement);
if (false === stripos($statement, 'INSERT INTO')) {
continue;
}
$statement = rtrim($statement, ';');
$result[] = SQLParser::parse($statement);
}
return $result;
}
}