PageRenderTime 49ms CodeModel.GetById 19ms RepoModel.GetById 0ms app.codeStats 0ms

/include/adodb/adodb-perf.inc.php

https://github.com/radicaldesigns/amp
PHP | 1056 lines | 850 code | 90 blank | 116 comment | 125 complexity | a78cbfe241ccbc1e1b8dffbbd4fc815a MD5 | raw file
Possible License(s): LGPL-2.1, GPL-2.0, BSD-3-Clause, LGPL-2.0, CC-BY-SA-3.0, AGPL-1.0
  1. <?php
  2. /*
  3. V4.92a 29 Aug 2006 (c) 2000-2006 John Lim (jlim#natsoft.com.my). All rights reserved.
  4. Released under both BSD license and Lesser GPL library license.
  5. Whenever there is any discrepancy between the two licenses,
  6. the BSD license will take precedence. See License.txt.
  7. Set tabs to 4 for best viewing.
  8. Latest version is available at http://adodb.sourceforge.net
  9. Library for basic performance monitoring and tuning.
  10. My apologies if you see code mixed with presentation. The presentation suits
  11. my needs. If you want to separate code from presentation, be my guest. Patches
  12. are welcome.
  13. */
  14. if (!defined('ADODB_DIR')) include_once(dirname(__FILE__).'/adodb.inc.php');
  15. include_once(ADODB_DIR.'/tohtml.inc.php');
  16. define( 'ADODB_OPT_HIGH', 2);
  17. define( 'ADODB_OPT_LOW', 1);
  18. // returns in K the memory of current process, or 0 if not known
  19. function adodb_getmem()
  20. {
  21. if (function_exists('memory_get_usage'))
  22. return (integer) ((memory_get_usage()+512)/1024);
  23. $pid = getmypid();
  24. if ( strncmp(strtoupper(PHP_OS),'WIN',3)==0) {
  25. $output = array();
  26. exec('tasklist /FI "PID eq ' . $pid. '" /FO LIST', $output);
  27. return substr($output[5], strpos($output[5], ':') + 1);
  28. }
  29. /* Hopefully UNIX */
  30. exec("ps --pid $pid --no-headers -o%mem,size", $output);
  31. if (sizeof($output) == 0) return 0;
  32. $memarr = explode(' ',$output[0]);
  33. if (sizeof($memarr)>=2) return (integer) $memarr[1];
  34. return 0;
  35. }
  36. // avoids localization problems where , is used instead of .
  37. function adodb_round($n,$prec)
  38. {
  39. return number_format($n, $prec, '.', '');
  40. }
  41. /* return microtime value as a float */
  42. function adodb_microtime()
  43. {
  44. $t = microtime();
  45. $t = explode(' ',$t);
  46. return (float)$t[1]+ (float)$t[0];
  47. }
  48. /* sql code timing */
  49. function& adodb_log_sql(&$conn,$sql,$inputarr)
  50. {
  51. $perf_table = adodb_perf::table();
  52. $conn->fnExecute = false;
  53. $t0 = microtime();
  54. $rs = $conn->Execute($sql,$inputarr);
  55. $t1 = microtime();
  56. if (!empty($conn->_logsql) && (empty($conn->_logsqlErrors) || !$rs)) {
  57. $conn->_logsql = false; // disable logsql error simulation
  58. $dbT = $conn->databaseType;
  59. $a0 = split(' ',$t0);
  60. $a0 = (float)$a0[1]+(float)$a0[0];
  61. $a1 = split(' ',$t1);
  62. $a1 = (float)$a1[1]+(float)$a1[0];
  63. $time = $a1 - $a0;
  64. if (!$rs) {
  65. $errM = $conn->ErrorMsg();
  66. $errN = $conn->ErrorNo();
  67. $conn->lastInsID = 0;
  68. $tracer = substr('ERROR: '.htmlspecialchars($errM),0,250);
  69. } else {
  70. $tracer = '';
  71. $errM = '';
  72. $errN = 0;
  73. $dbg = $conn->debug;
  74. $conn->debug = false;
  75. if (!is_object($rs) || $rs->dataProvider == 'empty')
  76. $conn->_affected = $conn->affected_rows(true);
  77. $conn->lastInsID = @$conn->Insert_ID();
  78. $conn->debug = $dbg;
  79. }
  80. if (isset($_SERVER['HTTP_HOST'])) {
  81. $tracer .= '<br>'.$_SERVER['HTTP_HOST'];
  82. if (isset($_SERVER['PHP_SELF'])) $tracer .= $_SERVER['PHP_SELF'];
  83. } else
  84. if (isset($_SERVER['PHP_SELF'])) $tracer .= '<br>'.$_SERVER['PHP_SELF'];
  85. //$tracer .= (string) adodb_backtrace(false);
  86. $tracer = (string) substr($tracer,0,500);
  87. if (is_array($inputarr)) {
  88. if (is_array(reset($inputarr))) $params = 'Array sizeof='.sizeof($inputarr);
  89. else {
  90. // Quote string parameters so we can see them in the
  91. // performance stats. This helps spot disabled indexes.
  92. $xar_params = $inputarr;
  93. foreach ($xar_params as $xar_param_key => $xar_param) {
  94. if (gettype($xar_param) == 'string')
  95. $xar_params[$xar_param_key] = '"' . $xar_param . '"';
  96. }
  97. $params = implode(', ', $xar_params);
  98. if (strlen($params) >= 3000) $params = substr($params, 0, 3000);
  99. }
  100. } else {
  101. $params = '';
  102. }
  103. if (is_array($sql)) $sql = $sql[0];
  104. $arr = array('b'=>strlen($sql).'.'.crc32($sql),
  105. 'c'=>substr($sql,0,3900), 'd'=>$params,'e'=>$tracer,'f'=>adodb_round($time,6));
  106. //var_dump($arr);
  107. $saved = $conn->debug;
  108. $conn->debug = 0;
  109. $d = $conn->sysTimeStamp;
  110. if (empty($d)) $d = date("'Y-m-d H:i:s'");
  111. if ($conn->dataProvider == 'oci8' && $dbT != 'oci8po') {
  112. $isql = "insert into $perf_table values($d,:b,:c,:d,:e,:f)";
  113. } else if ($dbT == 'odbc_mssql' || $dbT == 'informix' || $dbT == 'odbtp') {
  114. $timer = $arr['f'];
  115. if ($dbT == 'informix') $sql2 = substr($sql2,0,230);
  116. $sql1 = $conn->qstr($arr['b']);
  117. $sql2 = $conn->qstr($arr['c']);
  118. $params = $conn->qstr($arr['d']);
  119. $tracer = $conn->qstr($arr['e']);
  120. $isql = "insert into $perf_table (created,sql0,sql1,params,tracer,timer) values($d,$sql1,$sql2,$params,$tracer,$timer)";
  121. if ($dbT == 'informix') $isql = str_replace(chr(10),' ',$isql);
  122. $arr = false;
  123. } else {
  124. if ($dbT == 'db2') $arr['f'] = (float) $arr['f'];
  125. $isql = "insert into $perf_table (created,sql0,sql1,params,tracer,timer) values( $d,?,?,?,?,?)";
  126. }
  127. $ok = $conn->Execute($isql,$arr);
  128. $conn->debug = $saved;
  129. if ($ok) {
  130. $conn->_logsql = true;
  131. } else {
  132. $err2 = $conn->ErrorMsg();
  133. $conn->_logsql = true; // enable logsql error simulation
  134. $perf = NewPerfMonitor($conn);
  135. if ($perf) {
  136. if ($perf->CreateLogTable()) $ok = $conn->Execute($isql,$arr);
  137. } else {
  138. $ok = $conn->Execute("create table $perf_table (
  139. created varchar(50),
  140. sql0 varchar(250),
  141. sql1 varchar(4000),
  142. params varchar(3000),
  143. tracer varchar(500),
  144. timer decimal(16,6))");
  145. }
  146. if (!$ok) {
  147. ADOConnection::outp( "<p><b>LOGSQL Insert Failed</b>: $isql<br>$err2</p>");
  148. $conn->_logsql = false;
  149. }
  150. }
  151. $conn->_errorMsg = $errM;
  152. $conn->_errorCode = $errN;
  153. }
  154. $conn->fnExecute = 'adodb_log_sql';
  155. return $rs;
  156. }
  157. /*
  158. The settings data structure is an associative array that database parameter per element.
  159. Each database parameter element in the array is itself an array consisting of:
  160. 0: category code, used to group related db parameters
  161. 1: either
  162. a. sql string to retrieve value, eg. "select value from v\$parameter where name='db_block_size'",
  163. b. array holding sql string and field to look for, e.g. array('show variables','table_cache'),
  164. c. a string prefixed by =, then a PHP method of the class is invoked,
  165. e.g. to invoke $this->GetIndexValue(), set this array element to '=GetIndexValue',
  166. 2: description of the database parameter
  167. */
  168. class adodb_perf {
  169. var $conn;
  170. var $color = '#F0F0F0';
  171. var $table = '<table border=1 bgcolor=white>';
  172. var $titles = '<tr><td><b>Parameter</b></td><td><b>Value</b></td><td><b>Description</b></td></tr>';
  173. var $warnRatio = 90;
  174. var $tablesSQL = false;
  175. var $cliFormat = "%32s => %s \r\n";
  176. var $sql1 = 'sql1'; // used for casting sql1 to text for mssql
  177. var $explain = true;
  178. var $helpurl = "<a href=http://phplens.com/adodb/reference.functions.fnexecute.and.fncacheexecute.properties.html#logsql>LogSQL help</a>";
  179. var $createTableSQL = false;
  180. var $maxLength = 2000;
  181. // Sets the tablename to be used
  182. function table($newtable = false)
  183. {
  184. static $_table;
  185. if (!empty($newtable)) $_table = $newtable;
  186. if (empty($_table)) $_table = 'adodb_logsql';
  187. return $_table;
  188. }
  189. // returns array with info to calculate CPU Load
  190. function _CPULoad()
  191. {
  192. /*
  193. cpu 524152 2662 2515228 336057010
  194. cpu0 264339 1408 1257951 168025827
  195. cpu1 259813 1254 1257277 168031181
  196. page 622307 25475680
  197. swap 24 1891
  198. intr 890153570 868093576 6 0 4 4 0 6 1 2 0 0 0 124 0 8098760 2 13961053 0 0 0 0 0 0 0 0 0 0 0 0 0 16 16 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
  199. disk_io: (3,0):(3144904,54369,610378,3090535,50936192) (3,1):(3630212,54097,633016,3576115,50951320)
  200. ctxt 66155838
  201. btime 1062315585
  202. processes 69293
  203. */
  204. // Algorithm is taken from
  205. // http://msdn.microsoft.com/library/default.asp?url=/library/en-us/wmisdk/wmi/example__obtaining_raw_performance_data.asp
  206. if (strncmp(PHP_OS,'WIN',3)==0) {
  207. if (PHP_VERSION == '5.0.0') return false;
  208. if (PHP_VERSION == '5.0.1') return false;
  209. if (PHP_VERSION == '5.0.2') return false;
  210. if (PHP_VERSION == '5.0.3') return false;
  211. if (PHP_VERSION == '4.3.10') return false; # see http://bugs.php.net/bug.php?id=31737
  212. @$c = new COM("WinMgmts:{impersonationLevel=impersonate}!Win32_PerfRawData_PerfOS_Processor.Name='_Total'");
  213. if (!$c) return false;
  214. $info[0] = $c->PercentProcessorTime;
  215. $info[1] = 0;
  216. $info[2] = 0;
  217. $info[3] = $c->TimeStamp_Sys100NS;
  218. //print_r($info);
  219. return $info;
  220. }
  221. // Algorithm - Steve Blinch (BlitzAffe Online, http://www.blitzaffe.com)
  222. $statfile = '/proc/stat';
  223. if (!file_exists($statfile)) return false;
  224. $fd = fopen($statfile,"r");
  225. if (!$fd) return false;
  226. $statinfo = explode("\n",fgets($fd, 1024));
  227. fclose($fd);
  228. foreach($statinfo as $line) {
  229. $info = explode(" ",$line);
  230. if($info[0]=="cpu") {
  231. array_shift($info); // pop off "cpu"
  232. if(!$info[0]) array_shift($info); // pop off blank space (if any)
  233. return $info;
  234. }
  235. }
  236. return false;
  237. }
  238. /* NOT IMPLEMENTED */
  239. function MemInfo()
  240. {
  241. /*
  242. total: used: free: shared: buffers: cached:
  243. Mem: 1055289344 917299200 137990144 0 165437440 599773184
  244. Swap: 2146775040 11055104 2135719936
  245. MemTotal: 1030556 kB
  246. MemFree: 134756 kB
  247. MemShared: 0 kB
  248. Buffers: 161560 kB
  249. Cached: 581384 kB
  250. SwapCached: 4332 kB
  251. Active: 494468 kB
  252. Inact_dirty: 322856 kB
  253. Inact_clean: 24256 kB
  254. Inact_target: 168316 kB
  255. HighTotal: 131064 kB
  256. HighFree: 1024 kB
  257. LowTotal: 899492 kB
  258. LowFree: 133732 kB
  259. SwapTotal: 2096460 kB
  260. SwapFree: 2085664 kB
  261. Committed_AS: 348732 kB
  262. */
  263. }
  264. /*
  265. Remember that this is client load, not db server load!
  266. */
  267. var $_lastLoad;
  268. function CPULoad()
  269. {
  270. $info = $this->_CPULoad();
  271. if (!$info) return false;
  272. if (empty($this->_lastLoad)) {
  273. sleep(1);
  274. $this->_lastLoad = $info;
  275. $info = $this->_CPULoad();
  276. }
  277. $last = $this->_lastLoad;
  278. $this->_lastLoad = $info;
  279. $d_user = $info[0] - $last[0];
  280. $d_nice = $info[1] - $last[1];
  281. $d_system = $info[2] - $last[2];
  282. $d_idle = $info[3] - $last[3];
  283. //printf("Delta - User: %f Nice: %f System: %f Idle: %f<br>",$d_user,$d_nice,$d_system,$d_idle);
  284. if (strncmp(PHP_OS,'WIN',3)==0) {
  285. if ($d_idle < 1) $d_idle = 1;
  286. return 100*(1-$d_user/$d_idle);
  287. }else {
  288. $total=$d_user+$d_nice+$d_system+$d_idle;
  289. if ($total<1) $total=1;
  290. return 100*($d_user+$d_nice+$d_system)/$total;
  291. }
  292. }
  293. function Tracer($sql)
  294. {
  295. $perf_table = adodb_perf::table();
  296. $saveE = $this->conn->fnExecute;
  297. $this->conn->fnExecute = false;
  298. global $ADODB_FETCH_MODE;
  299. $save = $ADODB_FETCH_MODE;
  300. $ADODB_FETCH_MODE = ADODB_FETCH_NUM;
  301. if ($this->conn->fetchMode !== false) $savem = $this->conn->SetFetchMode(false);
  302. $sqlq = $this->conn->qstr($sql);
  303. $arr = $this->conn->GetArray(
  304. "select count(*),tracer
  305. from $perf_table where sql1=$sqlq
  306. group by tracer
  307. order by 1 desc");
  308. $s = '';
  309. if ($arr) {
  310. $s .= '<h3>Scripts Affected</h3>';
  311. foreach($arr as $k) {
  312. $s .= sprintf("%4d",$k[0]).' &nbsp; '.strip_tags($k[1]).'<br>';
  313. }
  314. }
  315. if (isset($savem)) $this->conn->SetFetchMode($savem);
  316. $ADODB_CACHE_MODE = $save;
  317. $this->conn->fnExecute = $saveE;
  318. return $s;
  319. }
  320. /*
  321. Explain Plan for $sql.
  322. If only a snippet of the $sql is passed in, then $partial will hold the crc32 of the
  323. actual sql.
  324. */
  325. function Explain($sql,$partial=false)
  326. {
  327. return false;
  328. }
  329. function InvalidSQL($numsql = 10)
  330. {
  331. if (isset($_GET['sql'])) return;
  332. $s = '<h3>Invalid SQL</h3>';
  333. $saveE = $this->conn->fnExecute;
  334. $this->conn->fnExecute = false;
  335. $perf_table = adodb_perf::table();
  336. $rs = $this->conn->SelectLimit("select distinct count(*),sql1,tracer as error_msg from $perf_table where tracer like 'ERROR:%' group by sql1,tracer order by 1 desc",$numsql);//,$numsql);
  337. $this->conn->fnExecute = $saveE;
  338. if ($rs) {
  339. $s .= rs2html($rs,false,false,false,false);
  340. } else
  341. return "<p>$this->helpurl. ".$this->conn->ErrorMsg()."</p>";
  342. return $s;
  343. }
  344. /*
  345. This script identifies the longest running SQL
  346. */
  347. function _SuspiciousSQL($numsql = 10)
  348. {
  349. global $ADODB_FETCH_MODE;
  350. $perf_table = adodb_perf::table();
  351. $saveE = $this->conn->fnExecute;
  352. $this->conn->fnExecute = false;
  353. if (isset($_GET['exps']) && isset($_GET['sql'])) {
  354. $partial = !empty($_GET['part']);
  355. echo "<a name=explain></a>".$this->Explain($_GET['sql'],$partial)."\n";
  356. }
  357. if (isset($_GET['sql'])) return;
  358. $sql1 = $this->sql1;
  359. $save = $ADODB_FETCH_MODE;
  360. $ADODB_FETCH_MODE = ADODB_FETCH_NUM;
  361. if ($this->conn->fetchMode !== false) $savem = $this->conn->SetFetchMode(false);
  362. //$this->conn->debug=1;
  363. $rs = $this->conn->SelectLimit(
  364. "select avg(timer) as avg_timer,$sql1,count(*),max(timer) as max_timer,min(timer) as min_timer
  365. from $perf_table
  366. where {$this->conn->upperCase}({$this->conn->substr}(sql0,1,5)) not in ('DROP ','INSER','COMMI','CREAT')
  367. and (tracer is null or tracer not like 'ERROR:%')
  368. group by sql1
  369. order by 1 desc",$numsql);
  370. if (isset($savem)) $this->conn->SetFetchMode($savem);
  371. $ADODB_FETCH_MODE = $save;
  372. $this->conn->fnExecute = $saveE;
  373. if (!$rs) return "<p>$this->helpurl. ".$this->conn->ErrorMsg()."</p>";
  374. $s = "<h3>Suspicious SQL</h3>
  375. <font size=1>The following SQL have high average execution times</font><br>
  376. <table border=1 bgcolor=white><tr><td><b>Avg Time</b><td><b>Count</b><td><b>SQL</b><td><b>Max</b><td><b>Min</b></tr>\n";
  377. $max = $this->maxLength;
  378. while (!$rs->EOF) {
  379. $sql = $rs->fields[1];
  380. $raw = urlencode($sql);
  381. if (strlen($raw)>$max-100) {
  382. $sql2 = substr($sql,0,$max-500);
  383. $raw = urlencode($sql2).'&part='.crc32($sql);
  384. }
  385. $prefix = "<a target=sql".rand()." href=\"?hidem=1&exps=1&sql=".$raw."&x#explain\">";
  386. $suffix = "</a>";
  387. if ($this->explain == false || strlen($prefix)>$max) {
  388. $suffix = ' ... <i>String too long for GET parameter: '.strlen($prefix).'</i>';
  389. $prefix = '';
  390. }
  391. $s .= "<tr><td>".adodb_round($rs->fields[0],6)."<td align=right>".$rs->fields[2]."<td><font size=-1>".$prefix.htmlspecialchars($sql).$suffix."</font>".
  392. "<td>".$rs->fields[3]."<td>".$rs->fields[4]."</tr>";
  393. $rs->MoveNext();
  394. }
  395. return $s."</table>";
  396. }
  397. function CheckMemory()
  398. {
  399. return '';
  400. }
  401. function SuspiciousSQL($numsql=10)
  402. {
  403. return adodb_perf::_SuspiciousSQL($numsql);
  404. }
  405. function ExpensiveSQL($numsql=10)
  406. {
  407. return adodb_perf::_ExpensiveSQL($numsql);
  408. }
  409. /*
  410. This reports the percentage of load on the instance due to the most
  411. expensive few SQL statements. Tuning these statements can often
  412. make huge improvements in overall system performance.
  413. */
  414. function _ExpensiveSQL($numsql = 10)
  415. {
  416. global $ADODB_FETCH_MODE;
  417. $perf_table = adodb_perf::table();
  418. $saveE = $this->conn->fnExecute;
  419. $this->conn->fnExecute = false;
  420. if (isset($_GET['expe']) && isset($_GET['sql'])) {
  421. $partial = !empty($_GET['part']);
  422. echo "<a name=explain></a>".$this->Explain($_GET['sql'],$partial)."\n";
  423. }
  424. if (isset($_GET['sql'])) return;
  425. $sql1 = $this->sql1;
  426. $save = $ADODB_FETCH_MODE;
  427. $ADODB_FETCH_MODE = ADODB_FETCH_NUM;
  428. if ($this->conn->fetchMode !== false) $savem = $this->conn->SetFetchMode(false);
  429. $rs = $this->conn->SelectLimit(
  430. "select sum(timer) as total,$sql1,count(*),max(timer) as max_timer,min(timer) as min_timer
  431. from $perf_table
  432. where {$this->conn->upperCase}({$this->conn->substr}(sql0,1,5)) not in ('DROP ','INSER','COMMI','CREAT')
  433. and (tracer is null or tracer not like 'ERROR:%')
  434. group by sql1
  435. having count(*)>1
  436. order by 1 desc",$numsql);
  437. if (isset($savem)) $this->conn->SetFetchMode($savem);
  438. $this->conn->fnExecute = $saveE;
  439. $ADODB_FETCH_MODE = $save;
  440. if (!$rs) return "<p>$this->helpurl. ".$this->conn->ErrorMsg()."</p>";
  441. $s = "<h3>Expensive SQL</h3>
  442. <font size=1>Tuning the following SQL could reduce the server load substantially</font><br>
  443. <table border=1 bgcolor=white><tr><td><b>Load</b><td><b>Count</b><td><b>SQL</b><td><b>Max</b><td><b>Min</b></tr>\n";
  444. $max = $this->maxLength;
  445. while (!$rs->EOF) {
  446. $sql = $rs->fields[1];
  447. $raw = urlencode($sql);
  448. if (strlen($raw)>$max-100) {
  449. $sql2 = substr($sql,0,$max-500);
  450. $raw = urlencode($sql2).'&part='.crc32($sql);
  451. }
  452. $prefix = "<a target=sqle".rand()." href=\"?hidem=1&expe=1&sql=".$raw."&x#explain\">";
  453. $suffix = "</a>";
  454. if($this->explain == false || strlen($prefix>$max)) {
  455. $prefix = '';
  456. $suffix = '';
  457. }
  458. $s .= "<tr><td>".adodb_round($rs->fields[0],6)."<td align=right>".$rs->fields[2]."<td><font size=-1>".$prefix.htmlspecialchars($sql).$suffix."</font>".
  459. "<td>".$rs->fields[3]."<td>".$rs->fields[4]."</tr>";
  460. $rs->MoveNext();
  461. }
  462. return $s."</table>";
  463. }
  464. /*
  465. Raw function to return parameter value from $settings.
  466. */
  467. function DBParameter($param)
  468. {
  469. if (empty($this->settings[$param])) return false;
  470. $sql = $this->settings[$param][1];
  471. return $this->_DBParameter($sql);
  472. }
  473. /*
  474. Raw function returning array of poll paramters
  475. */
  476. function &PollParameters()
  477. {
  478. $arr[0] = (float)$this->DBParameter('data cache hit ratio');
  479. $arr[1] = (float)$this->DBParameter('data reads');
  480. $arr[2] = (float)$this->DBParameter('data writes');
  481. $arr[3] = (integer) $this->DBParameter('current connections');
  482. return $arr;
  483. }
  484. /*
  485. Low-level Get Database Parameter
  486. */
  487. function _DBParameter($sql)
  488. {
  489. $savelog = $this->conn->LogSQL(false);
  490. if (is_array($sql)) {
  491. global $ADODB_FETCH_MODE;
  492. $sql1 = $sql[0];
  493. $key = $sql[1];
  494. if (sizeof($sql)>2) $pos = $sql[2];
  495. else $pos = 1;
  496. if (sizeof($sql)>3) $coef = $sql[3];
  497. else $coef = false;
  498. $ret = false;
  499. $save = $ADODB_FETCH_MODE;
  500. $ADODB_FETCH_MODE = ADODB_FETCH_NUM;
  501. if ($this->conn->fetchMode !== false) $savem = $this->conn->SetFetchMode(false);
  502. $rs = $this->conn->Execute($sql1);
  503. if (isset($savem)) $this->conn->SetFetchMode($savem);
  504. $ADODB_FETCH_MODE = $save;
  505. if ($rs) {
  506. while (!$rs->EOF) {
  507. $keyf = reset($rs->fields);
  508. if (trim($keyf) == $key) {
  509. $ret = $rs->fields[$pos];
  510. if ($coef) $ret *= $coef;
  511. break;
  512. }
  513. $rs->MoveNext();
  514. }
  515. $rs->Close();
  516. }
  517. $this->conn->LogSQL($savelog);
  518. return $ret;
  519. } else {
  520. if (strncmp($sql,'=',1) == 0) {
  521. $fn = substr($sql,1);
  522. return $this->$fn();
  523. }
  524. $sql = str_replace('$DATABASE',$this->conn->database,$sql);
  525. $ret = $this->conn->GetOne($sql);
  526. $this->conn->LogSQL($savelog);
  527. return $ret;
  528. }
  529. }
  530. /*
  531. Warn if cache ratio falls below threshold. Displayed in "Description" column.
  532. */
  533. function WarnCacheRatio($val)
  534. {
  535. if ($val < $this->warnRatio)
  536. return '<font color=red><b>Cache ratio should be at least '.$this->warnRatio.'%</b></font>';
  537. else return '';
  538. }
  539. /***********************************************************************************************/
  540. // HIGH LEVEL UI FUNCTIONS
  541. /***********************************************************************************************/
  542. function UI($pollsecs=5)
  543. {
  544. $perf_table = adodb_perf::table();
  545. $conn = $this->conn;
  546. $app = $conn->host;
  547. if ($conn->host && $conn->database) $app .= ', db=';
  548. $app .= $conn->database;
  549. if ($app) $app .= ', ';
  550. $savelog = $this->conn->LogSQL(false);
  551. $info = $conn->ServerInfo();
  552. if (isset($_GET['clearsql'])) {
  553. $this->conn->Execute("delete from $perf_table");
  554. }
  555. $this->conn->LogSQL($savelog);
  556. // magic quotes
  557. if (isset($_GET['sql']) && get_magic_quotes_gpc()) {
  558. $_GET['sql'] = $_GET['sql'] = str_replace(array("\\'",'\"'),array("'",'"'),$_GET['sql']);
  559. }
  560. if (!isset($_SESSION['ADODB_PERF_SQL'])) $nsql = $_SESSION['ADODB_PERF_SQL'] = 10;
  561. else $nsql = $_SESSION['ADODB_PERF_SQL'];
  562. $app .= $info['description'];
  563. if (isset($_GET['do'])) $do = $_GET['do'];
  564. else if (isset($_POST['do'])) $do = $_POST['do'];
  565. else if (isset($_GET['sql'])) $do = 'viewsql';
  566. else $do = 'stats';
  567. if (isset($_GET['nsql'])) {
  568. if ($_GET['nsql'] > 0) $nsql = $_SESSION['ADODB_PERF_SQL'] = (integer) $_GET['nsql'];
  569. }
  570. echo "<title>ADOdb Performance Monitor on $app</title><body bgcolor=white>";
  571. if ($do == 'viewsql') $form = "<td><form># SQL:<input type=hidden value=viewsql name=do> <input type=text size=4 name=nsql value=$nsql><input type=submit value=Go></td></form>";
  572. else $form = "<td>&nbsp;</td>";
  573. $allowsql = !defined('ADODB_PERF_NO_RUN_SQL');
  574. if (empty($_GET['hidem']))
  575. echo "<table border=1 width=100% bgcolor=lightyellow><tr><td colspan=2>
  576. <b><a href=http://adodb.sourceforge.net/?perf=1>ADOdb</a> Performance Monitor</b> <font size=1>for $app</font></tr><tr><td>
  577. <a href=?do=stats><b>Performance Stats</b></a> &nbsp; <a href=?do=viewsql><b>View SQL</b></a>
  578. &nbsp; <a href=?do=tables><b>View Tables</b></a> &nbsp; <a href=?do=poll><b>Poll Stats</b></a>",
  579. $allowsql ? ' &nbsp; <a href=?do=dosql><b>Run SQL</b></a>' : '',
  580. "$form",
  581. "</tr></table>";
  582. switch ($do) {
  583. default:
  584. case 'stats':
  585. echo $this->HealthCheck();
  586. //$this->conn->debug=1;
  587. echo $this->CheckMemory();
  588. break;
  589. case 'poll':
  590. echo "<iframe width=720 height=80%
  591. src=\"{$_SERVER['PHP_SELF']}?do=poll2&hidem=1\"></iframe>";
  592. break;
  593. case 'poll2':
  594. echo "<pre>";
  595. $this->Poll($pollsecs);
  596. break;
  597. case 'dosql':
  598. if (!$allowsql) break;
  599. $this->DoSQLForm();
  600. break;
  601. case 'viewsql':
  602. if (empty($_GET['hidem']))
  603. echo "&nbsp; <a href=\"?do=viewsql&clearsql=1\">Clear SQL Log</a><br>";
  604. echo($this->SuspiciousSQL($nsql));
  605. echo($this->ExpensiveSQL($nsql));
  606. echo($this->InvalidSQL($nsql));
  607. break;
  608. case 'tables':
  609. echo $this->Tables(); break;
  610. }
  611. global $ADODB_vers;
  612. echo "<p><div align=center><font size=1>$ADODB_vers Sponsored by <a href=http://phplens.com/>phpLens</a></font></div>";
  613. }
  614. /*
  615. Runs in infinite loop, returning real-time statistics
  616. */
  617. function Poll($secs=5)
  618. {
  619. $this->conn->fnExecute = false;
  620. //$this->conn->debug=1;
  621. if ($secs <= 1) $secs = 1;
  622. echo "Accumulating statistics, every $secs seconds...\n";flush();
  623. $arro = $this->PollParameters();
  624. $cnt = 0;
  625. set_time_limit(0);
  626. sleep($secs);
  627. while (1) {
  628. $arr = $this->PollParameters();
  629. $hits = sprintf('%2.2f',$arr[0]);
  630. $reads = sprintf('%12.4f',($arr[1]-$arro[1])/$secs);
  631. $writes = sprintf('%12.4f',($arr[2]-$arro[2])/$secs);
  632. $sess = sprintf('%5d',$arr[3]);
  633. $load = $this->CPULoad();
  634. if ($load !== false) {
  635. $oslabel = 'WS-CPU%';
  636. $osval = sprintf(" %2.1f ",(float) $load);
  637. }else {
  638. $oslabel = '';
  639. $osval = '';
  640. }
  641. if ($cnt % 10 == 0) echo " Time ".$oslabel." Hit% Sess Reads/s Writes/s\n";
  642. $cnt += 1;
  643. echo date('H:i:s').' '.$osval."$hits $sess $reads $writes\n";
  644. flush();
  645. if (connection_aborted()) return;
  646. sleep($secs);
  647. $arro = $arr;
  648. }
  649. }
  650. /*
  651. Returns basic health check in a command line interface
  652. */
  653. function HealthCheckCLI()
  654. {
  655. return $this->HealthCheck(true);
  656. }
  657. /*
  658. Returns basic health check as HTML
  659. */
  660. function HealthCheck($cli=false)
  661. {
  662. $saveE = $this->conn->fnExecute;
  663. $this->conn->fnExecute = false;
  664. if ($cli) $html = '';
  665. else $html = $this->table.'<tr><td colspan=3><h3>'.$this->conn->databaseType.'</h3></td></tr>'.$this->titles;
  666. $oldc = false;
  667. $bgc = '';
  668. foreach($this->settings as $name => $arr) {
  669. if ($arr === false) break;
  670. if (!is_string($name)) {
  671. if ($cli) $html .= " -- $arr -- \n";
  672. else $html .= "<tr bgcolor=$this->color><td colspan=3><i>$arr</i> &nbsp;</td></tr>";
  673. continue;
  674. }
  675. if (!is_array($arr)) break;
  676. $category = $arr[0];
  677. $how = $arr[1];
  678. if (sizeof($arr)>2) $desc = $arr[2];
  679. else $desc = ' &nbsp; ';
  680. if ($category == 'HIDE') continue;
  681. $val = $this->_DBParameter($how);
  682. if ($desc && strncmp($desc,"=",1) === 0) {
  683. $fn = substr($desc,1);
  684. $desc = $this->$fn($val);
  685. }
  686. if ($val === false) {
  687. $m = $this->conn->ErrorMsg();
  688. $val = "Error: $m";
  689. } else {
  690. if (is_numeric($val) && $val >= 256*1024) {
  691. if ($val % (1024*1024) == 0) {
  692. $val /= (1024*1024);
  693. $val .= 'M';
  694. } else if ($val % 1024 == 0) {
  695. $val /= 1024;
  696. $val .= 'K';
  697. }
  698. //$val = htmlspecialchars($val);
  699. }
  700. }
  701. if ($category != $oldc) {
  702. $oldc = $category;
  703. //$bgc = ($bgc == ' bgcolor='.$this->color) ? ' bgcolor=white' : ' bgcolor='.$this->color;
  704. }
  705. if (strlen($desc)==0) $desc = '&nbsp;';
  706. if (strlen($val)==0) $val = '&nbsp;';
  707. if ($cli) {
  708. $html .= str_replace('&nbsp;','',sprintf($this->cliFormat,strip_tags($name),strip_tags($val),strip_tags($desc)));
  709. }else {
  710. $html .= "<tr$bgc><td>".$name.'</td><td>'.$val.'</td><td>'.$desc."</td></tr>\n";
  711. }
  712. }
  713. if (!$cli) $html .= "</table>\n";
  714. $this->conn->fnExecute = $saveE;
  715. return $html;
  716. }
  717. function Tables($orderby='1')
  718. {
  719. if (!$this->tablesSQL) return false;
  720. $savelog = $this->conn->LogSQL(false);
  721. $rs = $this->conn->Execute($this->tablesSQL.' order by '.$orderby);
  722. $this->conn->LogSQL($savelog);
  723. $html = rs2html($rs,false,false,false,false);
  724. return $html;
  725. }
  726. function CreateLogTable()
  727. {
  728. if (!$this->createTableSQL) return false;
  729. $table = $this->table();
  730. $sql = str_replace('adodb_logsql',$table,$this->createTableSQL);
  731. $savelog = $this->conn->LogSQL(false);
  732. $ok = $this->conn->Execute($sql);
  733. $this->conn->LogSQL($savelog);
  734. return ($ok) ? true : false;
  735. }
  736. function DoSQLForm()
  737. {
  738. $PHP_SELF = $_SERVER['PHP_SELF'];
  739. $sql = isset($_REQUEST['sql']) ? $_REQUEST['sql'] : '';
  740. if (isset($_SESSION['phplens_sqlrows'])) $rows = $_SESSION['phplens_sqlrows'];
  741. else $rows = 3;
  742. if (isset($_REQUEST['SMALLER'])) {
  743. $rows /= 2;
  744. if ($rows < 3) $rows = 3;
  745. $_SESSION['phplens_sqlrows'] = $rows;
  746. }
  747. if (isset($_REQUEST['BIGGER'])) {
  748. $rows *= 2;
  749. $_SESSION['phplens_sqlrows'] = $rows;
  750. }
  751. ?>
  752. <form method="POST" action="<?php echo $PHP_SELF ?>">
  753. <table><tr>
  754. <td> Form size: <input type="submit" value=" &lt; " name="SMALLER"><input type="submit" value=" &gt; &gt; " name="BIGGER">
  755. </td>
  756. <td align=right>
  757. <input type="submit" value=" Run SQL Below " name="RUN"><input type=hidden name=do value=dosql>
  758. </td></tr>
  759. <tr>
  760. <td colspan=2><textarea rows=<?php print $rows; ?> name="sql" cols="80"><?php print htmlspecialchars($sql) ?></textarea>
  761. </td>
  762. </tr>
  763. </table>
  764. </form>
  765. <?php
  766. if (!isset($_REQUEST['sql'])) return;
  767. $sql = $this->undomq(trim($sql));
  768. if (substr($sql,strlen($sql)-1) === ';') {
  769. $print = true;
  770. $sqla = $this->SplitSQL($sql);
  771. } else {
  772. $print = false;
  773. $sqla = array($sql);
  774. }
  775. foreach($sqla as $sqls) {
  776. if (!$sqls) continue;
  777. if ($print) {
  778. print "<p>".htmlspecialchars($sqls)."</p>";
  779. flush();
  780. }
  781. $savelog = $this->conn->LogSQL(false);
  782. $rs = $this->conn->Execute($sqls);
  783. $this->conn->LogSQL($savelog);
  784. if ($rs && is_object($rs) && !$rs->EOF) {
  785. rs2html($rs);
  786. while ($rs->NextRecordSet()) {
  787. print "<table width=98% bgcolor=#C0C0FF><tr><td>&nbsp;</td></tr></table>";
  788. rs2html($rs);
  789. }
  790. } else {
  791. $e1 = (integer) $this->conn->ErrorNo();
  792. $e2 = $this->conn->ErrorMsg();
  793. if (($e1) || ($e2)) {
  794. if (empty($e1)) $e1 = '-1'; // postgresql fix
  795. print ' &nbsp; '.$e1.': '.$e2;
  796. } else {
  797. print "<p>No Recordset returned<br></p>";
  798. }
  799. }
  800. } // foreach
  801. }
  802. function SplitSQL($sql)
  803. {
  804. $arr = explode(';',$sql);
  805. return $arr;
  806. }
  807. function undomq($m)
  808. {
  809. if (get_magic_quotes_gpc()) {
  810. // undo the damage
  811. $m = str_replace('\\\\','\\',$m);
  812. $m = str_replace('\"','"',$m);
  813. $m = str_replace('\\\'','\'',$m);
  814. }
  815. return $m;
  816. }
  817. /************************************************************************/
  818. /**
  819. * Reorganise multiple table-indices/statistics/..
  820. * OptimizeMode could be given by last Parameter
  821. *
  822. * @example
  823. * <pre>
  824. * optimizeTables( 'tableA');
  825. * </pre>
  826. * <pre>
  827. * optimizeTables( 'tableA', 'tableB', 'tableC');
  828. * </pre>
  829. * <pre>
  830. * optimizeTables( 'tableA', 'tableB', ADODB_OPT_LOW);
  831. * </pre>
  832. *
  833. * @param string table name of the table to optimize
  834. * @param int mode optimization-mode
  835. * <code>ADODB_OPT_HIGH</code> for full optimization
  836. * <code>ADODB_OPT_LOW</code> for CPU-less optimization
  837. * Default is LOW <code>ADODB_OPT_LOW</code>
  838. * @author Markus Staab
  839. * @return Returns <code>true</code> on success and <code>false</code> on error
  840. */
  841. function OptimizeTables()
  842. {
  843. $args = func_get_args();
  844. $numArgs = func_num_args();
  845. if ( $numArgs == 0) return false;
  846. $mode = ADODB_OPT_LOW;
  847. $lastArg = $args[ $numArgs - 1];
  848. if ( !is_string($lastArg)) {
  849. $mode = $lastArg;
  850. unset( $args[ $numArgs - 1]);
  851. }
  852. foreach( $args as $table) {
  853. $this->optimizeTable( $table, $mode);
  854. }
  855. }
  856. /**
  857. * Reorganise the table-indices/statistics/.. depending on the given mode.
  858. * Default Implementation throws an error.
  859. *
  860. * @param string table name of the table to optimize
  861. * @param int mode optimization-mode
  862. * <code>ADODB_OPT_HIGH</code> for full optimization
  863. * <code>ADODB_OPT_LOW</code> for CPU-less optimization
  864. * Default is LOW <code>ADODB_OPT_LOW</code>
  865. * @author Markus Staab
  866. * @return Returns <code>true</code> on success and <code>false</code> on error
  867. */
  868. function OptimizeTable( $table, $mode = ADODB_OPT_LOW)
  869. {
  870. ADOConnection::outp( sprintf( "<p>%s: '%s' not implemented for driver '%s'</p>", __CLASS__, __FUNCTION__, $this->conn->databaseType));
  871. return false;
  872. }
  873. /**
  874. * Reorganise current database.
  875. * Default implementation loops over all <code>MetaTables()</code> and
  876. * optimize each using <code>optmizeTable()</code>
  877. *
  878. * @author Markus Staab
  879. * @return Returns <code>true</code> on success and <code>false</code> on error
  880. */
  881. function optimizeDatabase()
  882. {
  883. $conn = $this->conn;
  884. if ( !$conn) return false;
  885. $tables = $conn->MetaTables( 'TABLES');
  886. if ( !$tables ) return false;
  887. foreach( $tables as $table) {
  888. if ( !$this->optimizeTable( $table)) {
  889. return false;
  890. }
  891. }
  892. return true;
  893. }
  894. // end hack
  895. }
  896. ?>