MediaWiki  master
GeneralizedSql.php
Go to the documentation of this file.
1 <?php
22 namespace Wikimedia\Rdbms;
23 
31  private $rawSql;
33  private $trxId;
35  private $prefix;
36 
38  private $genericSql;
39 
45  public function __construct( $rawSql, $trxId, $prefix ) {
46  $this->rawSql = $rawSql;
47  $this->trxId = $trxId;
48  $this->prefix = $prefix;
49  }
50 
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 
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 }
Wikimedia\Rdbms
Definition: ChronologyProtector.php:24
Wikimedia\Rdbms\GeneralizedSql
Lazy-loaded wrapper for simplification and scrubbing of SQL queries for profiling.
Definition: GeneralizedSql.php:29
Wikimedia\Rdbms\GeneralizedSql\generalizeSQL
static generalizeSQL( $sql)
Removes most variables from an SQL query and replaces them with X or N for numbers.
Definition: GeneralizedSql.php:59
Wikimedia\Rdbms\GeneralizedSql\stringify
stringify()
Definition: GeneralizedSql.php:84
Wikimedia\Rdbms\GeneralizedSql\$prefix
string $prefix
Definition: GeneralizedSql.php:35
Wikimedia\Rdbms\GeneralizedSql\__construct
__construct( $rawSql, $trxId, $prefix)
Definition: GeneralizedSql.php:45
Wikimedia\Rdbms\GeneralizedSql\$trxId
string $trxId
Definition: GeneralizedSql.php:33
Wikimedia\Rdbms\GeneralizedSql\$genericSql
string null $genericSql
Definition: GeneralizedSql.php:38
Wikimedia\Rdbms\GeneralizedSql\$rawSql
string $rawSql
Definition: GeneralizedSql.php:31