SQLParserUtils.php 8.85 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 38
    const ESCAPED_SINGLE_QUOTED_TEXT = "(?:'(?:\\\\\\\\)+'|'(?:[^'\\\\]|\\\\'?|'')*')";
    const ESCAPED_DOUBLE_QUOTED_TEXT = '(?:"(?:\\\\\\\\)+"|"(?:[^"\\\\]|\\\\"?)*")';
    const ESCAPED_BACKTICK_QUOTED_TEXT = '(?:`(?:\\\\\\\\)+`|`(?:[^`\\\\]|\\\\`?)*`)';
    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
     *
46 47
     * @param string $statement
     * @param bool   $isPositional
Benjamin Morel's avatar
Benjamin Morel committed
48
     *
49 50
     * @return array
     */
51
    public static function getPlaceholderPositions($statement, $isPositional = true)
52
    {
53 54
        $match = ($isPositional) ? '?' : ':';
        if (strpos($statement, $match) === false) {
55
            return [];
56
        }
57

58
        $token = ($isPositional) ? self::POSITIONAL_TOKEN : self::NAMED_TOKEN;
59
        $paramMap = [];
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
    public static function expandListParameters($query, $params, $types)
88
    {
Fabio B. Silva's avatar
Fabio B. Silva committed
89
        $isPositional   = is_int(key($params));
90
        $arrayPositions = [];
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
            return [$query, $params, $types];
114
        }
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 143 144
                        // array needles are at {@link \Doctrine\DBAL\ParameterType} constants
                        // + {@link Doctrine\DBAL\Connection::ARRAY_PARAM_OFFSET}
                        array_fill(0, $count, $types[$needle] - Connection::ARRAY_PARAM_OFFSET) :
145
                        [],
146
                    array_slice($types, $needle + 1)
147
                );
148

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

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

156
            return [$query, $params, $types];
Fabio B. Silva's avatar
Fabio B. Silva committed
157
        }
158

Fabio B. Silva's avatar
Fabio B. Silva committed
159
        $queryOffset = 0;
160 161
        $typesOrd    = [];
        $paramsOrd   = [];
Fabio B. Silva's avatar
Fabio B. Silva committed
162 163

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

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

Fabio B. Silva's avatar
Fabio B. Silva committed
174 175 176 177
                continue;
            }

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

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

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

190
        return [$query, $paramsOrd, $typesOrd];
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
     */
204
    private static function getUnquotedStatementFragments($statement)
205
    {
206 207
        $literal = self::ESCAPED_SINGLE_QUOTED_TEXT . '|' .
                   self::ESCAPED_DOUBLE_QUOTED_TEXT . '|' .
208 209 210
                   self::ESCAPED_BACKTICK_QUOTED_TEXT . '|' .
                   self::ESCAPED_BRACKET_QUOTED_TEXT;
        preg_match_all("/([^'\"`\[]+)(?:$literal)?/s", $statement, $fragments, PREG_OFFSET_CAPTURE);
211 212 213

        return $fragments[1];
    }
214 215

    /**
216 217 218 219
     * @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
220 221 222 223
     *
     * @throws SQLParserUtilsException
     * @return mixed
     */
224
    private static function extractParam($paramName, $paramsOrTypes, $isParam, $defaultValue = null)
225
    {
226
        if (array_key_exists($paramName, $paramsOrTypes)) {
227 228 229 230
            return $paramsOrTypes[$paramName];
        }

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

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

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

        throw SQLParserUtilsException::missingType($paramName);
244
    }
245
}