MediaWiki  master
GeneralizedSql.php
Go to the documentation of this file.
1 <?php
21 namespace Wikimedia\Rdbms;
22 
32  private $rawSql;
34  private $trxId;
36  private $prefix;
37 
39  private $genericSql;
40 
46  public function __construct( $rawSql, $trxId, $prefix ) {
47  $this->rawSql = $rawSql;
48  $this->trxId = $trxId;
49  $this->prefix = $prefix;
50  }
51 
60  private static function generalizeSQL( $sql ) {
61  # This does the same as the regexp below would do, but in such a way
62  # as to avoid crashing php on some large strings.
63  # $sql = preg_replace( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql );
64 
65  $sql = str_replace( "\\\\", '', $sql );
66  $sql = str_replace( "\\'", '', $sql );
67  $sql = str_replace( "\\\"", '', $sql );
68  $sql = preg_replace( "/'.*'/s", "'X'", $sql );
69  $sql = preg_replace( '/".*"/s', "'X'", $sql );
70 
71  # All newlines, tabs, etc replaced by single space
72  $sql = preg_replace( '/\s+/', ' ', $sql );
73 
74  # All numbers => N,
75  # except the ones surrounded by characters, e.g. l10n
76  $sql = preg_replace( '/-?\d+(,-?\d+)+/s', 'N,...,N', $sql );
77  $sql = preg_replace( '/(?<![a-zA-Z])-?\d+(?![a-zA-Z])/s', 'N', $sql );
78 
79  return $sql;
80  }
81 
85  public function stringify() {
86  if ( $this->genericSql !== null ) {
87  return $this->genericSql;
88  }
89 
90  $this->genericSql = $this->prefix .
91  substr( self::generalizeSQL( $this->rawSql ), 0, 255 ) .
92  ( $this->trxId ? " [TRX#{$this->trxId}]" : "" );
93 
94  return $this->genericSql;
95  }
96 }
Wikimedia\Rdbms
Definition: ChronologyProtector.php:24
Wikimedia\Rdbms\GeneralizedSql
Lazy-loaded wrapper for simplification and scrubbing of SQL queries for profiling.
Definition: GeneralizedSql.php:30
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:60
Wikimedia\Rdbms\GeneralizedSql\stringify
stringify()
Definition: GeneralizedSql.php:85
Wikimedia\Rdbms\GeneralizedSql\$prefix
string $prefix
Definition: GeneralizedSql.php:36
Wikimedia\Rdbms\GeneralizedSql\__construct
__construct( $rawSql, $trxId, $prefix)
Definition: GeneralizedSql.php:46
Wikimedia\Rdbms\GeneralizedSql\$trxId
string $trxId
Definition: GeneralizedSql.php:34
Wikimedia\Rdbms\GeneralizedSql\$genericSql
string null $genericSql
Definition: GeneralizedSql.php:39
Wikimedia\Rdbms\GeneralizedSql\$rawSql
string $rawSql
Definition: GeneralizedSql.php:32