-
Notifications
You must be signed in to change notification settings - Fork 9
/
Tools.php
85 lines (75 loc) · 2.38 KB
/
Tools.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
<?php
namespace dokuwiki\plugin\sqlite;
class Tools
{
/**
* Split sql queries on semicolons, unless when semicolons are quoted
*
* Usually you don't need this. It's only really needed if you need individual results for
* multiple queries. For example in the admin interface.
*
* @param string $sql
* @return string[] sql queries
*/
public static function SQLstring2array($sql)
{
$statements = [];
$len = strlen($sql);
// Simple state machine to "parse" sql into single statements
$in_str = false;
$in_com = false;
$statement = '';
for ($i = 0; $i < $len; $i++) {
$prev = $i ? $sql[$i - 1] : "\n";
$char = $sql[$i];
$next = $i < ($len - 1) ? $sql[$i + 1] : '';
// in comment? ignore everything until line end
if ($in_com) {
if ($char == "\n") {
$in_com = false;
}
continue;
}
// handle strings
if ($in_str) {
if ($char == "'") {
if ($next == "'") {
// current char is an escape for the next
$statement .= $char . $next;
$i++;
continue;
} else {
// end of string
$statement .= $char;
$in_str = false;
continue;
}
}
// still in string
$statement .= $char;
continue;
}
// new comment?
if ($char == '-' && $next == '-' && $prev == "\n") {
$in_com = true;
continue;
}
// new string?
if ($char == "'") {
$in_str = true;
$statement .= $char;
continue;
}
// the real delimiter
if ($char == ';') {
$statements[] = trim($statement);
$statement = '';
continue;
}
// some standard query stuff
$statement .= $char;
}
if ($statement) $statements[] = trim($statement);
return array_filter($statements); // remove empty statements
}
}