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

namespace Doctrine\DBAL;

5 6 7 8 9 10 11 12 13 14 15 16
use const PREG_OFFSET_CAPTURE;
use function array_fill;
use function array_key_exists;
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;
17
use function sprintf;
18 19 20 21
use function strlen;
use function strpos;
use function substr;

22 23 24
/**
 * Utility class that parses sql statements with regard to types and parameters.
 */
25 26
class SQLParserUtils
{
27 28
    public const POSITIONAL_TOKEN = '\?';
    public const NAMED_TOKEN      = '(?<!:):[a-zA-Z_][a-zA-Z0-9_]*';
29 30

    // Quote characters within string literals can be preceded by a backslash.
31 32 33
    public const ESCAPED_SINGLE_QUOTED_TEXT   = "(?:'(?:\\\\\\\\)+'|'(?:[^'\\\\]|\\\\'?|'')*')";
    public const ESCAPED_DOUBLE_QUOTED_TEXT   = '(?:"(?:\\\\\\\\)+"|"(?:[^"\\\\]|\\\\"?)*")';
    public const ESCAPED_BACKTICK_QUOTED_TEXT = '(?:`(?:\\\\\\\\)+`|`(?:[^`\\\\]|\\\\`?)*`)';
34
    private const ESCAPED_BRACKET_QUOTED_TEXT = '(?<!\b(?i:ARRAY))\[(?:[^\]])*\]';
35

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

54
        $token    = $isPositional ? self::POSITIONAL_TOKEN : self::NAMED_TOKEN;
55
        $paramMap = [];
56 57

        foreach (self::getUnquotedStatementFragments($statement) as $fragment) {
58
            preg_match_all('/' . $token . '/', $fragment[0], $matches, PREG_OFFSET_CAPTURE);
59
            foreach ($matches[0] as $placeholder) {
60
                if ($isPositional) {
61
                    $paramMap[] = $placeholder[1] + $fragment[1];
62
                } else {
63
                    $pos            = $placeholder[1] + $fragment[1];
64
                    $paramMap[$pos] = substr($placeholder[0], 1, strlen($placeholder[0]));
65 66 67 68 69 70
                }
            }
        }

        return $paramMap;
    }
71

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

89 90 91 92 93
        if ($isPositional) {
            ksort($params);
            ksort($types);
        }

94
        foreach ($types as $name => $type) {
95
            ++$bindIndex;
96

Fabio B. Silva's avatar
Fabio B. Silva committed
97 98 99 100 101 102
            if ($type !== Connection::PARAM_INT_ARRAY && $type !== Connection::PARAM_STR_ARRAY) {
                continue;
            }

            if ($isPositional) {
                $name = $bindIndex;
103
            }
Fabio B. Silva's avatar
Fabio B. Silva committed
104 105

            $arrayPositions[$name] = false;
106
        }
107

108
        if (( ! $arrayPositions && $isPositional)) {
109
            return [$query, $params, $types];
110
        }
111

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

114 115 116
        if ($isPositional) {
            $paramOffset = 0;
            $queryOffset = 0;
117 118
            $params      = array_values($params);
            $types       = array_values($types);
Fabio B. Silva's avatar
Fabio B. Silva committed
119

120
            foreach ($paramPos as $needle => $needlePos) {
121
                if (! isset($arrayPositions[$needle])) {
122 123
                    continue;
                }
124

Fabio B. Silva's avatar
Fabio B. Silva committed
125
                $needle    += $paramOffset;
126
                $needlePos += $queryOffset;
Fabio B. Silva's avatar
Fabio B. Silva committed
127
                $count      = count($params[$needle]);
128

129
                $params = array_merge(
130
                    array_slice($params, 0, $needle),
131
                    $params[$needle],
132
                    array_slice($params, $needle + 1)
133
                );
134

135
                $types = array_merge(
136
                    array_slice($types, 0, $needle),
137
                    $count ?
138 139 140
                        // 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) :
141
                        [],
142
                    array_slice($types, $needle + 1)
143
                );
144

145 146
                $expandStr = $count ? implode(', ', array_fill(0, $count, '?')) : 'NULL';
                $query     = substr($query, 0, $needlePos) . $expandStr . substr($query, $needlePos + 1);
147

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

152
            return [$query, $params, $types];
Fabio B. Silva's avatar
Fabio B. Silva committed
153
        }
154

Fabio B. Silva's avatar
Fabio B. Silva committed
155
        $queryOffset = 0;
156 157
        $typesOrd    = [];
        $paramsOrd   = [];
Fabio B. Silva's avatar
Fabio B. Silva committed
158 159

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

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

Fabio B. Silva's avatar
Fabio B. Silva committed
170 171 172
                continue;
            }

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

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

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

186
        return [$query, $paramsOrd, $typesOrd];
187
    }
188 189 190 191 192 193 194 195 196 197

    /**
     * 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
198
     *
199
     * @return mixed[][]
200
     */
201
    private static function getUnquotedStatementFragments($statement)
202
    {
203 204 205 206 207 208 209
        $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);
210 211 212

        return $fragments[1];
    }
213 214

    /**
215
     * @param string $paramName     The name of the parameter (without a colon in front)
216
     * @param mixed  $paramsOrTypes A hash of parameters or types
217 218
     * @param bool   $isParam
     * @param mixed  $defaultValue  An optional default value. If omitted, an exception is thrown
219 220
     *
     * @return mixed
221 222
     *
     * @throws SQLParserUtilsException
223
     */
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
            return $paramsOrTypes[':' . $paramName];
        }

235
        if ($defaultValue !== null) {
236 237 238 239 240 241
            return $defaultValue;
        }

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

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