SQLParserUtils.php 8.78 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
<?php
/*
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * This software consists of voluntary contributions made by many individuals
Benjamin Eberlei's avatar
Benjamin Eberlei committed
16
 * and is licensed under the MIT license. For more information, see
17 18 19 20 21
 * <http://www.doctrine-project.org>.
 */

namespace Doctrine\DBAL;

22 23 24
/**
 * Utility class that parses sql statements with regard to types and parameters.
 *
Benjamin Morel's avatar
Benjamin Morel committed
25 26 27
 * @link   www.doctrine-project.org
 * @since  2.0
 * @author Benjamin Eberlei <kontakt@beberlei.de>
28
 */
29 30
class SQLParserUtils
{
31
    const POSITIONAL_TOKEN = '\?';
Thomas Subera's avatar
Thomas Subera committed
32
    const NAMED_TOKEN      = '(?<!:):[a-zA-Z_][a-zA-Z0-9_]*';
33 34

    // Quote characters within string literals can be preceded by a backslash.
35 36 37
    const ESCAPED_SINGLE_QUOTED_TEXT = "(?:'(?:\\\\\\\\)+'|'(?:[^'\\\\]|\\\\'?|'')*')";
    const ESCAPED_DOUBLE_QUOTED_TEXT = '(?:"(?:\\\\\\\\)+"|"(?:[^"\\\\]|\\\\"?)*")';
    const ESCAPED_BACKTICK_QUOTED_TEXT = '(?:`(?:\\\\\\\\)+`|`(?:[^`\\\\]|\\\\`?)*`)';
38
    const ESCAPED_BRACKET_QUOTED_TEXT = '(?<!\bARRAY)\[(?:[^\]])*\]';
39

40
    /**
Benjamin Morel's avatar
Benjamin Morel committed
41
     * Gets an array of the placeholders in an sql statements as keys and their positions in the query string.
42
     *
43 44
     * Returns an integer => integer pair (indexed from zero) for a positional statement
     * and a string => int[] pair for a named statement.
45
     *
Benjamin Morel's avatar
Benjamin Morel committed
46 47 48
     * @param string  $statement
     * @param boolean $isPositional
     *
49 50
     * @return array
     */
51
    static public function getPlaceholderPositions($statement, $isPositional = true)
52
    {
53 54 55 56
        $match = ($isPositional) ? '?' : ':';
        if (strpos($statement, $match) === false) {
            return array();
        }
57

58
        $token = ($isPositional) ? self::POSITIONAL_TOKEN : self::NAMED_TOKEN;
59
        $paramMap = array();
60 61 62 63

        foreach (self::getUnquotedStatementFragments($statement) as $fragment) {
            preg_match_all("/$token/", $fragment[0], $matches, PREG_OFFSET_CAPTURE);
            foreach ($matches[0] as $placeholder) {
64
                if ($isPositional) {
65
                    $paramMap[] = $placeholder[1] + $fragment[1];
66
                } else {
67 68
                    $pos = $placeholder[1] + $fragment[1];
                    $paramMap[$pos] = substr($placeholder[0], 1, strlen($placeholder[0]));
69 70 71 72 73 74
                }
            }
        }

        return $paramMap;
    }
75

76
    /**
77
     * For a positional query this method can rewrite the sql statement with regard to array parameters.
78
     *
Benjamin Morel's avatar
Benjamin Morel committed
79 80 81
     * @param string $query  The SQL query to execute.
     * @param array  $params The parameters to bind to the query.
     * @param array  $types  The types the previous parameters are in.
82
     *
83
     * @return array
Benjamin Morel's avatar
Benjamin Morel committed
84 85
     *
     * @throws SQLParserUtilsException
86 87
     */
    static public function expandListParameters($query, $params, $types)
88
    {
Fabio B. Silva's avatar
Fabio B. Silva committed
89
        $isPositional   = is_int(key($params));
90
        $arrayPositions = array();
Fabio B. Silva's avatar
Fabio B. Silva committed
91 92
        $bindIndex      = -1;

93 94 95 96 97
        if ($isPositional) {
            ksort($params);
            ksort($types);
        }

98
        foreach ($types as $name => $type) {
99
            ++$bindIndex;
100

Fabio B. Silva's avatar
Fabio B. Silva committed
101 102 103 104 105 106
            if ($type !== Connection::PARAM_INT_ARRAY && $type !== Connection::PARAM_STR_ARRAY) {
                continue;
            }

            if ($isPositional) {
                $name = $bindIndex;
107
            }
Fabio B. Silva's avatar
Fabio B. Silva committed
108 109

            $arrayPositions[$name] = false;
110
        }
111

112
        if (( ! $arrayPositions && $isPositional)) {
113 114
            return array($query, $params, $types);
        }
115

116
        $paramPos = self::getPlaceholderPositions($query, $isPositional);
Fabio B. Silva's avatar
Fabio B. Silva committed
117

118 119 120
        if ($isPositional) {
            $paramOffset = 0;
            $queryOffset = 0;
121 122
            $params      = array_values($params);
            $types       = array_values($types);
Fabio B. Silva's avatar
Fabio B. Silva committed
123

124
            foreach ($paramPos as $needle => $needlePos) {
Fabio B. Silva's avatar
Fabio B. Silva committed
125
                if ( ! isset($arrayPositions[$needle])) {
126 127
                    continue;
                }
128

Fabio B. Silva's avatar
Fabio B. Silva committed
129
                $needle    += $paramOffset;
130
                $needlePos += $queryOffset;
Fabio B. Silva's avatar
Fabio B. Silva committed
131
                $count      = count($params[$needle]);
132

133
                $params = array_merge(
134
                    array_slice($params, 0, $needle),
135
                    $params[$needle],
136
                    array_slice($params, $needle + 1)
137
                );
138

139
                $types = array_merge(
140
                    array_slice($types, 0, $needle),
141
                    $count ?
142
                        array_fill(0, $count, $types[$needle] - Connection::ARRAY_PARAM_OFFSET) : // array needles are at PDO::PARAM_* + 100
143
                        array(),
144
                    array_slice($types, $needle + 1)
145
                );
146

147
                $expandStr  = $count ? implode(", ", array_fill(0, $count, "?")) : 'NULL';
Fabio B. Silva's avatar
Fabio B. Silva committed
148
                $query      = substr($query, 0, $needlePos) . $expandStr . substr($query, $needlePos + 1);
149

Fabio B. Silva's avatar
Fabio B. Silva committed
150
                $paramOffset += ($count - 1); // Grows larger by number of parameters minus the replaced needle.
151 152
                $queryOffset += (strlen($expandStr) - 1);
            }
153

Fabio B. Silva's avatar
Fabio B. Silva committed
154 155
            return array($query, $params, $types);
        }
156

Fabio B. Silva's avatar
Fabio B. Silva committed
157 158 159 160 161
        $queryOffset = 0;
        $typesOrd    = array();
        $paramsOrd   = array();

        foreach ($paramPos as $pos => $paramName) {
162 163
            $paramLen = strlen($paramName) + 1;
            $value    = static::extractParam($paramName, $params, true);
Fabio B. Silva's avatar
Fabio B. Silva committed
164

165
            if ( ! isset($arrayPositions[$paramName]) && ! isset($arrayPositions[':' . $paramName])) {
Fabio B. Silva's avatar
Fabio B. Silva committed
166 167 168
                $pos         += $queryOffset;
                $queryOffset -= ($paramLen - 1);
                $paramsOrd[]  = $value;
169
                $typesOrd[]   = static::extractParam($paramName, $types, false, \PDO::PARAM_STR);
Fabio B. Silva's avatar
Fabio B. Silva committed
170
                $query        = substr($query, 0, $pos) . '?' . substr($query, ($pos + $paramLen));
171

Fabio B. Silva's avatar
Fabio B. Silva committed
172 173 174 175
                continue;
            }

            $count      = count($value);
176
            $expandStr  = $count > 0 ? implode(', ', array_fill(0, $count, '?')) : 'NULL';
Fabio B. Silva's avatar
Fabio B. Silva committed
177 178 179

            foreach ($value as $val) {
                $paramsOrd[] = $val;
180
                $typesOrd[]  = static::extractParam($paramName, $types, false) - Connection::ARRAY_PARAM_OFFSET;
181
            }
182

Fabio B. Silva's avatar
Fabio B. Silva committed
183 184 185
            $pos         += $queryOffset;
            $queryOffset += (strlen($expandStr) - $paramLen);
            $query        = substr($query, 0, $pos) . $expandStr . substr($query, ($pos + $paramLen));
186
        }
187

Fabio B. Silva's avatar
Fabio B. Silva committed
188
        return array($query, $paramsOrd, $typesOrd);
189
    }
190 191 192 193 194 195 196 197 198 199 200 201 202 203

    /**
     * Slice the SQL statement around pairs of quotes and
     * return string fragments of SQL outside of quoted literals.
     * Each fragment is captured as a 2-element array:
     *
     * 0 => matched fragment string,
     * 1 => offset of fragment in $statement
     *
     * @param string $statement
     * @return array
     */
    static private function getUnquotedStatementFragments($statement)
    {
204 205
        $literal = self::ESCAPED_SINGLE_QUOTED_TEXT . '|' .
                   self::ESCAPED_DOUBLE_QUOTED_TEXT . '|' .
206 207 208
                   self::ESCAPED_BACKTICK_QUOTED_TEXT . '|' .
                   self::ESCAPED_BRACKET_QUOTED_TEXT;
        preg_match_all("/([^'\"`\[]+)(?:$literal)?/s", $statement, $fragments, PREG_OFFSET_CAPTURE);
209 210 211

        return $fragments[1];
    }
212 213 214 215 216 217 218 219 220 221 222 223

    /**
     * @param string    $paramName      The name of the parameter (without a colon in front)
     * @param array     $paramsOrTypes  A hash of parameters or types
     * @param bool      $isParam
     * @param mixed     $defaultValue   An optional default value. If omitted, an exception is thrown
     *
     * @throws SQLParserUtilsException
     * @return mixed
     */
    static private function extractParam($paramName, $paramsOrTypes, $isParam, $defaultValue = null)
    {
224
        if (array_key_exists($paramName, $paramsOrTypes)) {
225 226 227 228
            return $paramsOrTypes[$paramName];
        }

        // Hash keys can be prefixed with a colon for compatibility
229
        if (array_key_exists(':' . $paramName, $paramsOrTypes)) {
230 231 232 233 234 235 236 237 238 239
            return $paramsOrTypes[':' . $paramName];
        }

        if (null !== $defaultValue) {
            return $defaultValue;
        }

        if ($isParam) {
            throw SQLParserUtilsException::missingParam($paramName);
        }
Benjamin Eberlei's avatar
Benjamin Eberlei committed
240 241

        throw SQLParserUtilsException::missingType($paramName);
242
    }
243
}