1<?php
2
3namespace dokuwiki\plugin\sqlite;
4
5class Tools
6{
7    /**
8     * Split sql queries on semicolons, unless when semicolons are quoted
9     *
10     * Usually you don't need this. It's only really needed if you need individual results for
11     * multiple queries. For example in the admin interface.
12     *
13     * @param string $sql
14     * @return string[] sql queries
15     */
16    public static function SQLstring2array($sql)
17    {
18        $statements = [];
19        $len = strlen($sql);
20
21        // Simple state machine to "parse" sql into single statements
22        $in_str = false;
23        $in_com = false;
24        $statement = '';
25        for ($i = 0; $i < $len; $i++) {
26            $prev = $i ? $sql[$i - 1] : "\n";
27            $char = $sql[$i];
28            $next = $i < ($len - 1) ? $sql[$i + 1] : '';
29
30            // in comment? ignore everything until line end
31            if ($in_com) {
32                if ($char == "\n") {
33                    $in_com = false;
34                }
35                continue;
36            }
37
38            // handle strings
39            if ($in_str) {
40                if ($char == "'") {
41                    if ($next == "'") {
42                        // current char is an escape for the next
43                        $statement .= $char . $next;
44                        $i++;
45                        continue;
46                    } else {
47                        // end of string
48                        $statement .= $char;
49                        $in_str = false;
50                        continue;
51                    }
52                }
53                // still in string
54                $statement .= $char;
55                continue;
56            }
57
58            // new comment?
59            if ($char == '-' && $next == '-' && $prev == "\n") {
60                $in_com = true;
61                continue;
62            }
63
64            // new string?
65            if ($char == "'") {
66                $in_str = true;
67                $statement .= $char;
68                continue;
69            }
70
71            // the real delimiter
72            if ($char == ';') {
73                $statements[] = trim($statement);
74                $statement = '';
75                continue;
76            }
77
78            // some standard query stuff
79            $statement .= $char;
80        }
81        if ($statement) $statements[] = trim($statement);
82
83        return array_filter($statements); // remove empty statements
84    }
85}
86