Merge "Add checkDependencies.php"
[lhc/web/wiklou.git] / includes / libs / rdbms / database / utils / GeneralizedSql.php
1 <?php
2 /**
3 * This program is free software; you can redistribute it and/or modify
4 * it under the terms of the GNU General Public License as published by
5 * the Free Software Foundation; either version 2 of the License, or
6 * (at your option) any later version.
7 *
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
12 *
13 * You should have received a copy of the GNU General Public License along
14 * with this program; if not, write to the Free Software Foundation, Inc.,
15 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
16 * http://www.gnu.org/copyleft/gpl.html
17 *
18 * @file
19 * @ingroup Profiler
20 */
21
22 namespace Wikimedia\Rdbms;
23
24 /**
25 * Lazy-loaded wrapper for simplification and scrubbing of SQL queries for profiling
26 *
27 * @since 1.34
28 */
29 class GeneralizedSql {
30 /** @var string */
31 private $rawSql;
32 /** @var string */
33 private $trxId;
34 /** @var string */
35 private $prefix;
36
37 /** @var string|null */
38 private $genericSql;
39
40 /**
41 * @param string $rawSql
42 * @param string $trxId
43 * @param string $prefix
44 */
45 public function __construct( $rawSql, $trxId, $prefix ) {
46 $this->rawSql = $rawSql;
47 $this->trxId = $trxId;
48 $this->prefix = $prefix;
49 }
50
51 /**
52 * Removes most variables from an SQL query and replaces them with X or N for numbers.
53 * It's only slightly flawed. Don't use for anything important.
54 *
55 * @param string $sql A SQL Query
56 *
57 * @return string
58 */
59 private static function generalizeSQL( $sql ) {
60 # This does the same as the regexp below would do, but in such a way
61 # as to avoid crashing php on some large strings.
62 # $sql = preg_replace( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql );
63
64 $sql = str_replace( "\\\\", '', $sql );
65 $sql = str_replace( "\\'", '', $sql );
66 $sql = str_replace( "\\\"", '', $sql );
67 $sql = preg_replace( "/'.*'/s", "'X'", $sql );
68 $sql = preg_replace( '/".*"/s', "'X'", $sql );
69
70 # All newlines, tabs, etc replaced by single space
71 $sql = preg_replace( '/\s+/', ' ', $sql );
72
73 # All numbers => N,
74 # except the ones surrounded by characters, e.g. l10n
75 $sql = preg_replace( '/-?\d+(,-?\d+)+/s', 'N,...,N', $sql );
76 $sql = preg_replace( '/(?<![a-zA-Z])-?\d+(?![a-zA-Z])/s', 'N', $sql );
77
78 return $sql;
79 }
80
81 /**
82 * @return string
83 */
84 public function stringify() {
85 if ( $this->genericSql !== null ) {
86 return $this->genericSql;
87 }
88
89 $this->genericSql = $this->prefix .
90 substr( self::generalizeSQL( $this->rawSql ), 0, 255 ) .
91 ( $this->trxId ? " [TRX#{$this->trxId}]" : "" );
92
93 return $this->genericSql;
94 }
95 }