SQLParserUtils.php 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234
  1. <?php
  2. /*
  3. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  4. * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  5. * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  6. * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  7. * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  8. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  9. * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  10. * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  11. * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  12. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  13. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  14. *
  15. * This software consists of voluntary contributions made by many individuals
  16. * and is licensed under the MIT license. For more information, see
  17. * <http://www.doctrine-project.org>.
  18. */
  19. namespace Doctrine\DBAL;
  20. use Doctrine\DBAL\Connection;
  21. /**
  22. * Utility class that parses sql statements with regard to types and parameters.
  23. *
  24. * @license http://www.opensource.org/licenses/lgpl-license.php LGPL
  25. * @link www.doctrine-project.com
  26. * @since 2.0
  27. * @author Benjamin Eberlei <kontakt@beberlei.de>
  28. */
  29. class SQLParserUtils
  30. {
  31. const POSITIONAL_TOKEN = '\?';
  32. const NAMED_TOKEN = '(?<!:):[a-zA-Z_][a-zA-Z0-9_]*';
  33. // Quote characters within string literals can be preceded by a backslash.
  34. const ESCAPED_SINGLE_QUOTED_TEXT = "'(?:[^'\\\\]|\\\\'|\\\\\\\\)*'";
  35. const ESCAPED_DOUBLE_QUOTED_TEXT = '"(?:[^"\\\\]|\\\\"|\\\\\\\\)*"';
  36. /**
  37. * Get an array of the placeholders in an sql statements as keys and their positions in the query string.
  38. *
  39. * Returns an integer => integer pair (indexed from zero) for a positional statement
  40. * and a string => int[] pair for a named statement.
  41. *
  42. * @param string $statement
  43. * @param bool $isPositional
  44. * @return array
  45. */
  46. static public function getPlaceholderPositions($statement, $isPositional = true)
  47. {
  48. $match = ($isPositional) ? '?' : ':';
  49. if (strpos($statement, $match) === false) {
  50. return array();
  51. }
  52. $token = ($isPositional) ? self::POSITIONAL_TOKEN : self::NAMED_TOKEN;
  53. $paramMap = array();
  54. foreach (self::getUnquotedStatementFragments($statement) as $fragment) {
  55. preg_match_all("/$token/", $fragment[0], $matches, PREG_OFFSET_CAPTURE);
  56. foreach ($matches[0] as $placeholder) {
  57. if ($isPositional) {
  58. $paramMap[] = $placeholder[1] + $fragment[1];
  59. } else {
  60. $pos = $placeholder[1] + $fragment[1];
  61. $paramMap[$pos] = substr($placeholder[0], 1, strlen($placeholder[0]));
  62. }
  63. }
  64. }
  65. return $paramMap;
  66. }
  67. /**
  68. * For a positional query this method can rewrite the sql statement with regard to array parameters.
  69. *
  70. * @param string $query The SQL query to execute.
  71. * @param array $params The parameters to bind to the query.
  72. * @param array $types The types the previous parameters are in.
  73. *
  74. * @throws SQLParserUtilsException
  75. * @return array
  76. */
  77. static public function expandListParameters($query, $params, $types)
  78. {
  79. $isPositional = is_int(key($params));
  80. $arrayPositions = array();
  81. $bindIndex = -1;
  82. foreach ($types as $name => $type) {
  83. ++$bindIndex;
  84. if ($type !== Connection::PARAM_INT_ARRAY && $type !== Connection::PARAM_STR_ARRAY) {
  85. continue;
  86. }
  87. if ($isPositional) {
  88. $name = $bindIndex;
  89. }
  90. $arrayPositions[$name] = false;
  91. }
  92. if (( ! $arrayPositions && $isPositional)) {
  93. return array($query, $params, $types);
  94. }
  95. $paramPos = self::getPlaceholderPositions($query, $isPositional);
  96. if ($isPositional) {
  97. $paramOffset = 0;
  98. $queryOffset = 0;
  99. foreach ($paramPos as $needle => $needlePos) {
  100. if ( ! isset($arrayPositions[$needle])) {
  101. continue;
  102. }
  103. $needle += $paramOffset;
  104. $needlePos += $queryOffset;
  105. $count = count($params[$needle]);
  106. $params = array_merge(
  107. array_slice($params, 0, $needle),
  108. $params[$needle],
  109. array_slice($params, $needle + 1)
  110. );
  111. $types = array_merge(
  112. array_slice($types, 0, $needle),
  113. $count ?
  114. array_fill(0, $count, $types[$needle] - Connection::ARRAY_PARAM_OFFSET) : // array needles are at PDO::PARAM_* + 100
  115. array(),
  116. array_slice($types, $needle + 1)
  117. );
  118. $expandStr = implode(", ", array_fill(0, $count, "?"));
  119. $query = substr($query, 0, $needlePos) . $expandStr . substr($query, $needlePos + 1);
  120. $paramOffset += ($count - 1); // Grows larger by number of parameters minus the replaced needle.
  121. $queryOffset += (strlen($expandStr) - 1);
  122. }
  123. return array($query, $params, $types);
  124. }
  125. $queryOffset = 0;
  126. $typesOrd = array();
  127. $paramsOrd = array();
  128. foreach ($paramPos as $pos => $paramName) {
  129. $paramLen = strlen($paramName) + 1;
  130. $value = static::extractParam($paramName, $params, true);
  131. if ( ! isset($arrayPositions[$paramName]) && ! isset($arrayPositions[':' . $paramName])) {
  132. $pos += $queryOffset;
  133. $queryOffset -= ($paramLen - 1);
  134. $paramsOrd[] = $value;
  135. $typesOrd[] = static::extractParam($paramName, $types, false, \PDO::PARAM_STR);
  136. $query = substr($query, 0, $pos) . '?' . substr($query, ($pos + $paramLen));
  137. continue;
  138. }
  139. $count = count($value);
  140. $expandStr = $count > 0 ? implode(', ', array_fill(0, $count, '?')) : '?';
  141. foreach ($value as $val) {
  142. $paramsOrd[] = $val;
  143. $typesOrd[] = static::extractParam($paramName, $types, false) - Connection::ARRAY_PARAM_OFFSET;
  144. }
  145. $pos += $queryOffset;
  146. $queryOffset += (strlen($expandStr) - $paramLen);
  147. $query = substr($query, 0, $pos) . $expandStr . substr($query, ($pos + $paramLen));
  148. }
  149. return array($query, $paramsOrd, $typesOrd);
  150. }
  151. /**
  152. * Slice the SQL statement around pairs of quotes and
  153. * return string fragments of SQL outside of quoted literals.
  154. * Each fragment is captured as a 2-element array:
  155. *
  156. * 0 => matched fragment string,
  157. * 1 => offset of fragment in $statement
  158. *
  159. * @param string $statement
  160. * @return array
  161. */
  162. static private function getUnquotedStatementFragments($statement)
  163. {
  164. $literal = self::ESCAPED_SINGLE_QUOTED_TEXT . '|' . self::ESCAPED_DOUBLE_QUOTED_TEXT;
  165. preg_match_all("/([^'\"]+)(?:$literal)?/s", $statement, $fragments, PREG_OFFSET_CAPTURE);
  166. return $fragments[1];
  167. }
  168. /**
  169. * @param string $paramName The name of the parameter (without a colon in front)
  170. * @param array $paramsOrTypes A hash of parameters or types
  171. * @param bool $isParam
  172. * @param mixed $defaultValue An optional default value. If omitted, an exception is thrown
  173. *
  174. * @throws SQLParserUtilsException
  175. * @return mixed
  176. */
  177. static private function extractParam($paramName, $paramsOrTypes, $isParam, $defaultValue = null)
  178. {
  179. if (isset($paramsOrTypes[$paramName])) {
  180. return $paramsOrTypes[$paramName];
  181. }
  182. // Hash keys can be prefixed with a colon for compatibility
  183. if (isset($paramsOrTypes[':' . $paramName])) {
  184. return $paramsOrTypes[':' . $paramName];
  185. }
  186. if (null !== $defaultValue) {
  187. return $defaultValue;
  188. }
  189. if ($isParam) {
  190. throw SQLParserUtilsException::missingParam($paramName);
  191. }
  192. throw SQLParserUtilsException::missingType($paramName);
  193. }
  194. }