SQLParserUtils.php 9.95 KB
Newer Older
1 2 3 4
<?php

namespace Doctrine\DBAL;

5
use function array_fill;
6
use function array_fill_keys;
7
use function array_key_exists;
8
use function array_keys;
9 10 11 12 13 14 15 16 17
use function array_merge;
use function array_slice;
use function array_values;
use function count;
use function implode;
use function is_int;
use function key;
use function ksort;
use function preg_match_all;
18
use function sprintf;
19 20 21
use function strlen;
use function strpos;
use function substr;
22

Grégoire Paris's avatar
Grégoire Paris committed
23
use const PREG_OFFSET_CAPTURE;
24

25 26 27
/**
 * Utility class that parses sql statements with regard to types and parameters.
 */
28 29
class SQLParserUtils
{
Sergei Morozov's avatar
Sergei Morozov committed
30 31 32 33
    /**#@+
     *
     * @deprecated Will be removed as internal implementation details.
     */
34 35
    public const POSITIONAL_TOKEN = '\?';
    public const NAMED_TOKEN      = '(?<!:):[a-zA-Z_][a-zA-Z0-9_]*';
36
    // Quote characters within string literals can be preceded by a backslash.
37 38 39
    public const ESCAPED_SINGLE_QUOTED_TEXT   = "(?:'(?:\\\\)+'|'(?:[^'\\\\]|\\\\'?|'')*')";
    public const ESCAPED_DOUBLE_QUOTED_TEXT   = '(?:"(?:\\\\)+"|"(?:[^"\\\\]|\\\\"?)*")';
    public const ESCAPED_BACKTICK_QUOTED_TEXT = '(?:`(?:\\\\)+`|`(?:[^`\\\\]|\\\\`?)*`)';
40 41
    /**#@-*/

42
    private const ESCAPED_BRACKET_QUOTED_TEXT = '(?<!\b(?i:ARRAY))\[(?:[^\]])*\]';
43

44
    /**
Benjamin Morel's avatar
Benjamin Morel committed
45
     * Gets an array of the placeholders in an sql statements as keys and their positions in the query string.
46
     *
Sergei Morozov's avatar
Sergei Morozov committed
47 48
     * For a statement with positional parameters, returns a zero-indexed list of placeholder position.
     * For a statement with named parameters, returns a map of placeholder positions to their parameter names.
49
     *
Sergei Morozov's avatar
Sergei Morozov committed
50 51
     * @deprecated Will be removed as internal implementation detail.
     *
52 53
     * @param string $statement
     * @param bool   $isPositional
Benjamin Morel's avatar
Benjamin Morel committed
54
     *
Sergei Morozov's avatar
Sergei Morozov committed
55
     * @return int[]|string[]
56
     */
57
    public static function getPlaceholderPositions($statement, $isPositional = true)
58
    {
Sergei Morozov's avatar
Sergei Morozov committed
59 60 61 62 63 64 65 66 67 68
        return $isPositional
            ? self::getPositionalPlaceholderPositions($statement)
            : self::getNamedPlaceholderPositions($statement);
    }

    /**
     * Returns a zero-indexed list of placeholder position.
     *
     * @return int[]
     */
69
    private static function getPositionalPlaceholderPositions(string $statement): array
Sergei Morozov's avatar
Sergei Morozov committed
70 71 72 73 74
    {
        return self::collectPlaceholders(
            $statement,
            '?',
            self::POSITIONAL_TOKEN,
75
            static function (string $_, int $placeholderPosition, int $fragmentPosition, array &$carry): void {
Sergei Morozov's avatar
Sergei Morozov committed
76 77 78 79 80 81 82 83 84 85
                $carry[] = $placeholderPosition + $fragmentPosition;
            }
        );
    }

    /**
     * Returns a map of placeholder positions to their parameter names.
     *
     * @return string[]
     */
86
    private static function getNamedPlaceholderPositions(string $statement): array
Sergei Morozov's avatar
Sergei Morozov committed
87 88 89 90 91
    {
        return self::collectPlaceholders(
            $statement,
            ':',
            self::NAMED_TOKEN,
92
            static function (string $placeholder, int $placeholderPosition, int $fragmentPosition, array &$carry): void {
Sergei Morozov's avatar
Sergei Morozov committed
93 94 95 96 97 98 99 100
                $carry[$placeholderPosition + $fragmentPosition] = substr($placeholder, 1);
            }
        );
    }

    /**
     * @return mixed[]
     */
101
    private static function collectPlaceholders(string $statement, string $match, string $token, callable $collector): array
Sergei Morozov's avatar
Sergei Morozov committed
102
    {
103
        if (strpos($statement, $match) === false) {
104
            return [];
105
        }
106

Sergei Morozov's avatar
Sergei Morozov committed
107
        $carry = [];
108 109

        foreach (self::getUnquotedStatementFragments($statement) as $fragment) {
110
            preg_match_all('/' . $token . '/', $fragment[0], $matches, PREG_OFFSET_CAPTURE);
111
            foreach ($matches[0] as $placeholder) {
Sergei Morozov's avatar
Sergei Morozov committed
112
                $collector($placeholder[0], $placeholder[1], $fragment[1], $carry);
113 114 115
            }
        }

Sergei Morozov's avatar
Sergei Morozov committed
116
        return $carry;
117
    }
118

119
    /**
120
     * For a positional query this method can rewrite the sql statement with regard to array parameters.
121
     *
122 123 124
     * @param string                 $query  The SQL query to execute.
     * @param mixed[]                $params The parameters to bind to the query.
     * @param array<string|int|null> $types  The types the previous parameters are in.
125
     *
126
     * @return mixed[]
Benjamin Morel's avatar
Benjamin Morel committed
127 128
     *
     * @throws SQLParserUtilsException
129
     */
130
    public static function expandListParameters($query, $params, $types)
131
    {
Fabio B. Silva's avatar
Fabio B. Silva committed
132
        $isPositional   = is_int(key($params));
133
        $arrayPositions = [];
Fabio B. Silva's avatar
Fabio B. Silva committed
134 135
        $bindIndex      = -1;

136
        if ($isPositional) {
137 138 139 140
            // make sure that $types has the same keys as $params
            // to allow omitting parameters with unspecified types
            $types += array_fill_keys(array_keys($params), null);

141 142 143 144
            ksort($params);
            ksort($types);
        }

145
        foreach ($types as $name => $type) {
146
            ++$bindIndex;
147

Fabio B. Silva's avatar
Fabio B. Silva committed
148 149 150 151 152 153
            if ($type !== Connection::PARAM_INT_ARRAY && $type !== Connection::PARAM_STR_ARRAY) {
                continue;
            }

            if ($isPositional) {
                $name = $bindIndex;
154
            }
Fabio B. Silva's avatar
Fabio B. Silva committed
155 156

            $arrayPositions[$name] = false;
157
        }
158

159
        if (( ! $arrayPositions && $isPositional)) {
160
            return [$query, $params, $types];
161
        }
162

163 164 165
        if ($isPositional) {
            $paramOffset = 0;
            $queryOffset = 0;
166 167
            $params      = array_values($params);
            $types       = array_values($types);
Fabio B. Silva's avatar
Fabio B. Silva committed
168

Sergei Morozov's avatar
Sergei Morozov committed
169 170
            $paramPos = self::getPositionalPlaceholderPositions($query);

171
            foreach ($paramPos as $needle => $needlePos) {
172
                if (! isset($arrayPositions[$needle])) {
173 174
                    continue;
                }
175

Fabio B. Silva's avatar
Fabio B. Silva committed
176
                $needle    += $paramOffset;
177
                $needlePos += $queryOffset;
Fabio B. Silva's avatar
Fabio B. Silva committed
178
                $count      = count($params[$needle]);
179

180
                $params = array_merge(
181
                    array_slice($params, 0, $needle),
182
                    $params[$needle],
183
                    array_slice($params, $needle + 1)
184
                );
185

186
                $types = array_merge(
187
                    array_slice($types, 0, $needle),
188
                    $count ?
189
                        // array needles are at {@link \Doctrine\DBAL\ParameterType} constants
190
                        // + {@link \Doctrine\DBAL\Connection::ARRAY_PARAM_OFFSET}
191
                        array_fill(0, $count, $types[$needle] - Connection::ARRAY_PARAM_OFFSET) :
192
                        [],
193
                    array_slice($types, $needle + 1)
194
                );
195

196 197
                $expandStr = $count ? implode(', ', array_fill(0, $count, '?')) : 'NULL';
                $query     = substr($query, 0, $needlePos) . $expandStr . substr($query, $needlePos + 1);
198

Grégoire Paris's avatar
Grégoire Paris committed
199 200
                $paramOffset += $count - 1; // Grows larger by number of parameters minus the replaced needle.
                $queryOffset += strlen($expandStr) - 1;
201
            }
202

203
            return [$query, $params, $types];
Fabio B. Silva's avatar
Fabio B. Silva committed
204
        }
205

Fabio B. Silva's avatar
Fabio B. Silva committed
206
        $queryOffset = 0;
207 208
        $typesOrd    = [];
        $paramsOrd   = [];
Fabio B. Silva's avatar
Fabio B. Silva committed
209

Sergei Morozov's avatar
Sergei Morozov committed
210 211
        $paramPos = self::getNamedPlaceholderPositions($query);

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

216
            if (! isset($arrayPositions[$paramName]) && ! isset($arrayPositions[':' . $paramName])) {
Fabio B. Silva's avatar
Fabio B. Silva committed
217
                $pos         += $queryOffset;
Grégoire Paris's avatar
Grégoire Paris committed
218
                $queryOffset -= $paramLen - 1;
Fabio B. Silva's avatar
Fabio B. Silva committed
219
                $paramsOrd[]  = $value;
220
                $typesOrd[]   = static::extractParam($paramName, $types, false, ParameterType::STRING);
Grégoire Paris's avatar
Grégoire Paris committed
221
                $query        = substr($query, 0, $pos) . '?' . substr($query, $pos + $paramLen);
222

Fabio B. Silva's avatar
Fabio B. Silva committed
223 224 225
                continue;
            }

226 227
            $count     = count($value);
            $expandStr = $count > 0 ? implode(', ', array_fill(0, $count, '?')) : 'NULL';
Fabio B. Silva's avatar
Fabio B. Silva committed
228 229 230

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

Fabio B. Silva's avatar
Fabio B. Silva committed
234
            $pos         += $queryOffset;
Grégoire Paris's avatar
Grégoire Paris committed
235 236
            $queryOffset += strlen($expandStr) - $paramLen;
            $query        = substr($query, 0, $pos) . $expandStr . substr($query, $pos + $paramLen);
237
        }
238

239
        return [$query, $paramsOrd, $typesOrd];
240
    }
241 242 243 244 245 246 247 248 249 250

    /**
     * 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
251
     *
252
     * @return mixed[][]
253
     */
254
    private static function getUnquotedStatementFragments($statement)
255
    {
256 257 258 259 260 261 262
        $literal    = self::ESCAPED_SINGLE_QUOTED_TEXT . '|' .
            self::ESCAPED_DOUBLE_QUOTED_TEXT . '|' .
            self::ESCAPED_BACKTICK_QUOTED_TEXT . '|' .
            self::ESCAPED_BRACKET_QUOTED_TEXT;
        $expression = sprintf('/((.+(?i:ARRAY)\\[.+\\])|([^\'"`\\[]+))(?:%s)?/s', $literal);

        preg_match_all($expression, $statement, $fragments, PREG_OFFSET_CAPTURE);
263 264 265

        return $fragments[1];
    }
266 267

    /**
268
     * @param string $paramName     The name of the parameter (without a colon in front)
269
     * @param mixed  $paramsOrTypes A hash of parameters or types
270 271
     * @param bool   $isParam
     * @param mixed  $defaultValue  An optional default value. If omitted, an exception is thrown
272 273
     *
     * @return mixed
274 275
     *
     * @throws SQLParserUtilsException
276
     */
277
    private static function extractParam($paramName, $paramsOrTypes, $isParam, $defaultValue = null)
278
    {
279
        if (array_key_exists($paramName, $paramsOrTypes)) {
280 281 282 283
            return $paramsOrTypes[$paramName];
        }

        // Hash keys can be prefixed with a colon for compatibility
284
        if (array_key_exists(':' . $paramName, $paramsOrTypes)) {
285 286 287
            return $paramsOrTypes[':' . $paramName];
        }

288
        if ($defaultValue !== null) {
289 290 291 292 293 294
            return $defaultValue;
        }

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

        throw SQLParserUtilsException::missingType($paramName);
297
    }
298
}