xref: /plugin/sqlite/Tools.php (revision 9a026de610436f17451876c2e640cdf912cbaac3)
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        $statements = array();
18        $len = strlen($sql);
19
20        // Simple state machine to "parse" sql into single statements
21        $in_str = false;
22        $in_com = false;
23        $statement = '';
24        for($i=0; $i<$len; $i++){
25            $prev = $i ? $sql[$i-1] : "\n";
26            $char = $sql[$i];
27            $next = $i < ($len - 1) ? $sql[$i+1] : '';
28
29            // in comment? ignore everything until line end
30            if($in_com){
31                if($char == "\n"){
32                    $in_com = false;
33                }
34                continue;
35            }
36
37            // handle strings
38            if($in_str){
39                if($char == "'"){
40                    if($next == "'"){
41                        // current char is an escape for the next
42                        $statement .= $char . $next;
43                        $i++;
44                        continue;
45                    }else{
46                        // end of string
47                        $statement .= $char;
48                        $in_str = false;
49                        continue;
50                    }
51                }
52                // still in string
53                $statement .= $char;
54                continue;
55            }
56
57            // new comment?
58            if($char == '-' && $next == '-' && $prev == "\n"){
59                $in_com = true;
60                continue;
61            }
62
63            // new string?
64            if($char == "'"){
65                $in_str = true;
66                $statement .= $char;
67                continue;
68            }
69
70            // the real delimiter
71            if($char == ';'){
72                $statements[] = trim($statement);
73                $statement = '';
74                continue;
75            }
76
77            // some standard query stuff
78            $statement .= $char;
79        }
80        if($statement) $statements[] = trim($statement);
81
82        return array_filter($statements); // remove empty statements
83    }
84}
85