dbsearch.class.php 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740
  1. <?php
  2. // Copyright (C) 2015 Combodo SARL
  3. //
  4. // This file is part of iTop.
  5. //
  6. // iTop is free software; you can redistribute it and/or modify
  7. // it under the terms of the GNU Affero General Public License as published by
  8. // the Free Software Foundation, either version 3 of the License, or
  9. // (at your option) any later version.
  10. //
  11. // iTop is distributed in the hope that it will be useful,
  12. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. // GNU Affero General Public License for more details.
  15. //
  16. // You should have received a copy of the GNU Affero General Public License
  17. // along with iTop. If not, see <http://www.gnu.org/licenses/>
  18. require_once('dbobjectsearch.class.php');
  19. require_once('dbunionsearch.class.php');
  20. /**
  21. * An object search
  22. *
  23. * Note: in the ancient times of iTop, a search was named after DBObjectSearch.
  24. * When the UNION has been introduced, it has been decided to:
  25. * - declare a hierarchy of search classes, with two leafs :
  26. * - one class to cope with a single query (A JOIN B... WHERE...)
  27. * - and the other to cope with several queries (query1 UNION query2)
  28. * - in order to preserve forward/backward compatibility of the existing modules
  29. * - keep the name of DBObjectSearch even if it a little bit confusing
  30. * - do not provide a type-hint for function parameters defined in the modules
  31. * - leave the statements DBObjectSearch::FromOQL in the modules, though DBSearch is more relevant
  32. *
  33. * @copyright Copyright (C) 2015 Combodo SARL
  34. * @license http://opensource.org/licenses/AGPL-3.0
  35. */
  36. abstract class DBSearch
  37. {
  38. protected $m_bDataFiltered = false;
  39. protected $m_aModifierProperties = array();
  40. // By default, some information may be hidden to the current user
  41. // But it may happen that we need to disable that feature
  42. protected $m_bAllowAllData = false;
  43. public function __construct()
  44. {
  45. }
  46. /**
  47. * Perform a deep clone (as opposed to "clone" which does copy a reference to the underlying objects)
  48. **/
  49. public function DeepClone()
  50. {
  51. return unserialize(serialize($this)); // Beware this serializes/unserializes the search and its parameters as well
  52. }
  53. public function AllowAllData() {$this->m_bAllowAllData = true;}
  54. public function IsAllDataAllowed() {return $this->m_bAllowAllData;}
  55. public function IsDataFiltered() {return $this->m_bDataFiltered; }
  56. public function SetDataFiltered() {$this->m_bDataFiltered = true;}
  57. public function SetModifierProperty($sPluginClass, $sProperty, $value)
  58. {
  59. $this->m_aModifierProperties[$sPluginClass][$sProperty] = $value;
  60. }
  61. public function GetModifierProperties($sPluginClass)
  62. {
  63. if (array_key_exists($sPluginClass, $this->m_aModifierProperties))
  64. {
  65. return $this->m_aModifierProperties[$sPluginClass];
  66. }
  67. else
  68. {
  69. return array();
  70. }
  71. }
  72. abstract public function GetClassName($sAlias);
  73. abstract public function GetClass();
  74. abstract public function GetClassAlias();
  75. /**
  76. * Change the class (only subclasses are supported as of now, because the conditions must fit the new class)
  77. * Defaults to the first selected class (most of the time it is also the first joined class
  78. */
  79. abstract public function ChangeClass($sNewClass, $sAlias = null);
  80. abstract public function GetSelectedClasses();
  81. abstract public function IsAny();
  82. public function Describe(){return 'deprecated - use ToOQL() instead';}
  83. public function DescribeConditionPointTo($sExtKeyAttCode, $aPointingTo){return 'deprecated - use ToOQL() instead';}
  84. public function DescribeConditionRefBy($sForeignClass, $sForeignExtKeyAttCode){return 'deprecated - use ToOQL() instead';}
  85. public function DescribeConditionRelTo($aRelInfo){return 'deprecated - use ToOQL() instead';}
  86. public function DescribeConditions(){return 'deprecated - use ToOQL() instead';}
  87. public function __DescribeHTML(){return 'deprecated - use ToOQL() instead';}
  88. abstract public function ResetCondition();
  89. abstract public function MergeConditionExpression($oExpression);
  90. abstract public function AddConditionExpression($oExpression);
  91. abstract public function AddNameCondition($sName);
  92. abstract public function AddCondition($sFilterCode, $value, $sOpCode = null);
  93. /**
  94. * Specify a condition on external keys or link sets
  95. * @param sAttSpec Can be either an attribute code or extkey->[sAttSpec] or linkset->[sAttSpec] and so on, recursively
  96. * Example: infra_list->ci_id->location_id->country
  97. * @param value The value to match (can be an array => IN(val1, val2...)
  98. * @return void
  99. */
  100. abstract public function AddConditionAdvanced($sAttSpec, $value);
  101. abstract public function AddCondition_FullText($sFullText);
  102. abstract public function AddCondition_PointingTo(DBObjectSearch $oFilter, $sExtKeyAttCode, $iOperatorCode = TREE_OPERATOR_EQUALS);
  103. abstract public function AddCondition_ReferencedBy(DBObjectSearch $oFilter, $sForeignExtKeyAttCode);
  104. abstract public function Intersect(DBSearch $oFilter);
  105. abstract public function SetInternalParams($aParams);
  106. abstract public function GetInternalParams();
  107. abstract public function GetQueryParams();
  108. abstract public function ListConstantFields();
  109. /**
  110. * Turn the parameters (:xxx) into scalar values in order to easily
  111. * serialize a search
  112. */
  113. abstract public function ApplyParameters($aArgs);
  114. public function serialize($bDevelopParams = false, $aContextParams = null)
  115. {
  116. $sOql = $this->ToOql($bDevelopParams, $aContextParams);
  117. return base64_encode(serialize(array($sOql, $this->GetInternalParams(), $this->m_aModifierProperties)));
  118. }
  119. static public function unserialize($sValue)
  120. {
  121. $aData = unserialize(base64_decode($sValue));
  122. $sOql = $aData[0];
  123. $aParams = $aData[1];
  124. // We've tried to use gzcompress/gzuncompress, but for some specific queries
  125. // it was not working at all (See Trac #193)
  126. // gzuncompress was issuing a warning "data error" and the return object was null
  127. $oRetFilter = self::FromOQL($sOql, $aParams);
  128. $oRetFilter->m_aModifierProperties = $aData[2];
  129. return $oRetFilter;
  130. }
  131. abstract public function ToOQL($bDevelopParams = false, $aContextParams = null);
  132. static protected $m_aOQLQueries = array();
  133. // Do not filter out depending on user rights
  134. // In particular when we are currently in the process of evaluating the user rights...
  135. static public function FromOQL_AllData($sQuery, $aParams = null)
  136. {
  137. $oRes = self::FromOQL($sQuery, $aParams);
  138. $oRes->AllowAllData();
  139. return $oRes;
  140. }
  141. static public function FromOQL($sQuery, $aParams = null)
  142. {
  143. if (empty($sQuery)) return null;
  144. // Query caching
  145. $sQueryId = md5($sQuery);
  146. $bOQLCacheEnabled = true;
  147. if ($bOQLCacheEnabled)
  148. {
  149. if (array_key_exists($sQueryId, self::$m_aOQLQueries))
  150. {
  151. // hit!
  152. $oResultFilter = self::$m_aOQLQueries[$sQueryId]->DeepClone();
  153. }
  154. elseif (self::$m_bUseAPCCache)
  155. {
  156. // Note: For versions of APC older than 3.0.17, fetch() accepts only one parameter
  157. //
  158. $sAPCCacheId = 'itop-'.MetaModel::GetEnvironmentId().'-dbsearch-cache-'.$sQueryId;
  159. $oKPI = new ExecutionKPI();
  160. $result = apc_fetch($sAPCCacheId);
  161. $oKPI->ComputeStats('Search APC (fetch)', $sQuery);
  162. if (is_object($result))
  163. {
  164. $oResultFilter = $result;
  165. self::$m_aOQLQueries[$sQueryId] = $oResultFilter->DeepClone();
  166. }
  167. }
  168. }
  169. if (!isset($oResultFilter))
  170. {
  171. $oKPI = new ExecutionKPI();
  172. $oOql = new OqlInterpreter($sQuery);
  173. $oOqlQuery = $oOql->ParseQuery();
  174. $oMetaModel = new ModelReflectionRuntime();
  175. $oOqlQuery->Check($oMetaModel, $sQuery); // Exceptions thrown in case of issue
  176. $oResultFilter = $oOqlQuery->ToDBSearch($sQuery);
  177. $oKPI->ComputeStats('Parse OQL', $sQuery);
  178. if ($bOQLCacheEnabled)
  179. {
  180. self::$m_aOQLQueries[$sQueryId] = $oResultFilter->DeepClone();
  181. if (self::$m_bUseAPCCache)
  182. {
  183. $oKPI = new ExecutionKPI();
  184. apc_store($sAPCCacheId, $oResultFilter, self::$m_iQueryCacheTTL);
  185. $oKPI->ComputeStats('Search APC (store)', $sQueryId);
  186. }
  187. }
  188. }
  189. if (!is_null($aParams))
  190. {
  191. $oResultFilter->SetInternalParams($aParams);
  192. }
  193. return $oResultFilter;
  194. }
  195. // Alternative to object mapping: the data are transfered directly into an array
  196. // This is 10 times faster than creating a set of objects, and makes sense when optimization is required
  197. /**
  198. * @param hash $aOrderBy Array of '[<classalias>.]attcode' => bAscending
  199. */
  200. public function ToDataArray($aColumns = array(), $aOrderBy = array(), $aArgs = array())
  201. {
  202. $sSQL = $this->MakeSelectQuery($aOrderBy, $aArgs);
  203. $resQuery = CMDBSource::Query($sSQL);
  204. if (!$resQuery) return;
  205. if (count($aColumns) == 0)
  206. {
  207. $aColumns = array_keys(MetaModel::ListAttributeDefs($this->GetClass()));
  208. // Add the standard id (as first column)
  209. array_unshift($aColumns, 'id');
  210. }
  211. $aQueryCols = CMDBSource::GetColumns($resQuery);
  212. $sClassAlias = $this->GetClassAlias();
  213. $aColMap = array();
  214. foreach ($aColumns as $sAttCode)
  215. {
  216. $sColName = $sClassAlias.$sAttCode;
  217. if (in_array($sColName, $aQueryCols))
  218. {
  219. $aColMap[$sAttCode] = $sColName;
  220. }
  221. }
  222. $aRes = array();
  223. while ($aRow = CMDBSource::FetchArray($resQuery))
  224. {
  225. $aMappedRow = array();
  226. foreach ($aColMap as $sAttCode => $sColName)
  227. {
  228. $aMappedRow[$sAttCode] = $aRow[$sColName];
  229. }
  230. $aRes[] = $aMappedRow;
  231. }
  232. CMDBSource::FreeResult($resQuery);
  233. return $aRes;
  234. }
  235. ////////////////////////////////////////////////////////////////////////////
  236. //
  237. // Construction of the SQL queries
  238. //
  239. ////////////////////////////////////////////////////////////////////////////
  240. protected static $m_aQueryStructCache = array();
  241. public function MakeGroupByQuery($aArgs, $aGroupByExpr, $bExcludeNullValues = false)
  242. {
  243. if ($bExcludeNullValues)
  244. {
  245. // Null values are not handled (though external keys set to 0 are allowed)
  246. $oQueryFilter = $this->DeepClone();
  247. foreach ($aGroupByExpr as $oGroupByExp)
  248. {
  249. $oNull = new FunctionExpression('ISNULL', array($oGroupByExp));
  250. $oNotNull = new BinaryExpression($oNull, '!=', new TrueExpression());
  251. $oQueryFilter->AddConditionExpression($oNotNull);
  252. }
  253. }
  254. else
  255. {
  256. $oQueryFilter = $this;
  257. }
  258. $aAttToLoad = array();
  259. $oSQLQuery = $oQueryFilter->GetSQLQuery(array(), $aArgs, $aAttToLoad, null, 0, 0, false, $aGroupByExpr);
  260. $aScalarArgs = array_merge(MetaModel::PrepareQueryArguments($aArgs), $this->GetInternalParams());
  261. try
  262. {
  263. $bBeautifulSQL = self::$m_bTraceQueries || self::$m_bDebugQuery || self::$m_bIndentQueries;
  264. $sRes = $oSQLQuery->RenderGroupBy($aScalarArgs, $bBeautifulSQL);
  265. }
  266. catch (MissingQueryArgument $e)
  267. {
  268. // Add some information...
  269. $e->addInfo('OQL', $this->ToOQL());
  270. throw $e;
  271. }
  272. $this->AddQueryTraceGroupBy($aArgs, $aGroupByExpr, $sRes);
  273. return $sRes;
  274. }
  275. /**
  276. * @param hash $aOrderBy Array of '[<classalias>.]attcode' => bAscending
  277. */
  278. public function MakeSelectQuery($aOrderBy = array(), $aArgs = array(), $aAttToLoad = null, $aExtendedDataSpec = null, $iLimitCount = 0, $iLimitStart = 0, $bGetCount = false)
  279. {
  280. // Check the order by specification, and prefix with the class alias
  281. // and make sure that the ordering columns are going to be selected
  282. //
  283. $sClass = $this->GetClass();
  284. $sClassAlias = $this->GetClassAlias();
  285. $aOrderSpec = array();
  286. foreach ($aOrderBy as $sFieldAlias => $bAscending)
  287. {
  288. if (!is_bool($bAscending))
  289. {
  290. throw new CoreException("Wrong direction in ORDER BY spec, found '$bAscending' and expecting a boolean value");
  291. }
  292. $iDotPos = strpos($sFieldAlias, '.');
  293. if ($iDotPos === false)
  294. {
  295. $sAttClass = $sClass;
  296. $sAttClassAlias = $sClassAlias;
  297. $sAttCode = $sFieldAlias;
  298. }
  299. else
  300. {
  301. $sAttClassAlias = substr($sFieldAlias, 0, $iDotPos);
  302. $sAttClass = $this->GetClassName($sAttClassAlias);
  303. $sAttCode = substr($sFieldAlias, $iDotPos + 1);
  304. }
  305. if ($sAttCode != 'id')
  306. {
  307. MyHelpers::CheckValueInArray('field name in ORDER BY spec', $sAttCode, MetaModel::GetAttributesList($sAttClass));
  308. $oAttDef = MetaModel::GetAttributeDef($sAttClass, $sAttCode);
  309. foreach($oAttDef->GetOrderBySQLExpressions($sAttClassAlias) as $sSQLExpression)
  310. {
  311. $aOrderSpec[$sSQLExpression] = $bAscending;
  312. }
  313. }
  314. else
  315. {
  316. $aOrderSpec['`'.$sAttClassAlias.$sAttCode.'`'] = $bAscending;
  317. }
  318. // Make sure that the columns used for sorting are present in the loaded columns
  319. if (!is_null($aAttToLoad) && !isset($aAttToLoad[$sAttClassAlias][$sAttCode]))
  320. {
  321. $aAttToLoad[$sAttClassAlias][$sAttCode] = MetaModel::GetAttributeDef($sAttClass, $sAttCode);
  322. }
  323. }
  324. $oSQLQuery = $this->GetSQLQuery($aOrderBy, $aArgs, $aAttToLoad, $aExtendedDataSpec, $iLimitCount, $iLimitStart, $bGetCount);
  325. $aScalarArgs = array_merge(MetaModel::PrepareQueryArguments($aArgs), $this->GetInternalParams());
  326. try
  327. {
  328. $bBeautifulSQL = self::$m_bTraceQueries || self::$m_bDebugQuery || self::$m_bIndentQueries;
  329. $sRes = $oSQLQuery->RenderSelect($aOrderSpec, $aScalarArgs, $iLimitCount, $iLimitStart, $bGetCount, $bBeautifulSQL);
  330. if ($sClassAlias == '_itop_')
  331. {
  332. IssueLog::Info('SQL Query (_itop_): '.$sRes);
  333. }
  334. }
  335. catch (MissingQueryArgument $e)
  336. {
  337. // Add some information...
  338. $e->addInfo('OQL', $this->ToOQL());
  339. throw $e;
  340. }
  341. $this->AddQueryTraceSelect($aOrderBy, $aArgs, $aAttToLoad, $aExtendedDataSpec, $iLimitCount, $iLimitStart, $bGetCount, $sRes);
  342. return $sRes;
  343. }
  344. protected function GetSQLQuery($aOrderBy, $aArgs, $aAttToLoad, $aExtendedDataSpec, $iLimitCount, $iLimitStart, $bGetCount, $aGroupByExpr = null)
  345. {
  346. // Hide objects that are not visible to the current user
  347. //
  348. $oSearch = $this;
  349. if (!$this->IsAllDataAllowed() && !$this->IsDataFiltered())
  350. {
  351. $oVisibleObjects = UserRights::GetSelectFilter($this->GetClass(), $this->GetModifierProperties('UserRightsGetSelectFilter'));
  352. if ($oVisibleObjects === false)
  353. {
  354. // Make sure this is a valid search object, saying NO for all
  355. $oVisibleObjects = DBObjectSearch::FromEmptySet($this->GetClass());
  356. }
  357. if (is_object($oVisibleObjects))
  358. {
  359. $oSearch = $this->Intersect($oVisibleObjects);
  360. $oSearch->SetDataFiltered();
  361. }
  362. else
  363. {
  364. // should be true at this point, meaning that no additional filtering
  365. // is required
  366. }
  367. }
  368. // Compute query modifiers properties (can be set in the search itself, by the context, etc.)
  369. //
  370. $aModifierProperties = MetaModel::MakeModifierProperties($oSearch);
  371. // Create a unique cache id
  372. //
  373. if (self::$m_bQueryCacheEnabled || self::$m_bTraceQueries)
  374. {
  375. // Need to identify the query
  376. $sOqlQuery = $oSearch->ToOql();
  377. if (count($aModifierProperties))
  378. {
  379. array_multisort($aModifierProperties);
  380. $sModifierProperties = json_encode($aModifierProperties);
  381. }
  382. else
  383. {
  384. $sModifierProperties = '';
  385. }
  386. $sRawId = $sOqlQuery.$sModifierProperties;
  387. if (!is_null($aAttToLoad))
  388. {
  389. $sRawId .= json_encode($aAttToLoad);
  390. }
  391. if (!is_null($aGroupByExpr))
  392. {
  393. foreach($aGroupByExpr as $sAlias => $oExpr)
  394. {
  395. $sRawId .= 'g:'.$sAlias.'!'.$oExpr->Render();
  396. }
  397. }
  398. $sRawId .= $bGetCount;
  399. $sOqlId = md5($sRawId);
  400. }
  401. else
  402. {
  403. $sOqlQuery = "SELECTING... ".$oSearch->GetClass();
  404. $sOqlId = "query id ? n/a";
  405. }
  406. // Query caching
  407. //
  408. if (self::$m_bQueryCacheEnabled)
  409. {
  410. // Warning: using directly the query string as the key to the hash array can FAIL if the string
  411. // is long and the differences are only near the end... so it's safer (but not bullet proof?)
  412. // to use a hash (like md5) of the string as the key !
  413. //
  414. // Example of two queries that were found as similar by the hash array:
  415. // SELECT SLT JOIN lnkSLTToSLA AS L1 ON L1.slt_id=SLT.id JOIN SLA ON L1.sla_id = SLA.id JOIN lnkContractToSLA AS L2 ON L2.sla_id = SLA.id JOIN CustomerContract ON L2.contract_id = CustomerContract.id WHERE SLT.ticket_priority = 1 AND SLA.service_id = 3 AND SLT.metric = 'TTO' AND CustomerContract.customer_id = 2
  416. // and
  417. // SELECT SLT JOIN lnkSLTToSLA AS L1 ON L1.slt_id=SLT.id JOIN SLA ON L1.sla_id = SLA.id JOIN lnkContractToSLA AS L2 ON L2.sla_id = SLA.id JOIN CustomerContract ON L2.contract_id = CustomerContract.id WHERE SLT.ticket_priority = 1 AND SLA.service_id = 3 AND SLT.metric = 'TTR' AND CustomerContract.customer_id = 2
  418. // the only difference is R instead or O at position 285 (TTR instead of TTO)...
  419. //
  420. if (array_key_exists($sOqlId, self::$m_aQueryStructCache))
  421. {
  422. // hit!
  423. $oSQLQuery = unserialize(serialize(self::$m_aQueryStructCache[$sOqlId]));
  424. // Note: cloning is not enough because the subtree is made of objects
  425. }
  426. elseif (self::$m_bUseAPCCache)
  427. {
  428. // Note: For versions of APC older than 3.0.17, fetch() accepts only one parameter
  429. //
  430. $sOqlAPCCacheId = 'itop-'.MetaModel::GetEnvironmentId().'-query-cache-'.$sOqlId;
  431. $oKPI = new ExecutionKPI();
  432. $result = apc_fetch($sOqlAPCCacheId);
  433. $oKPI->ComputeStats('Query APC (fetch)', $sOqlQuery);
  434. if (is_object($result))
  435. {
  436. $oSQLQuery = $result;
  437. self::$m_aQueryStructCache[$sOqlId] = $oSQLQuery;
  438. }
  439. }
  440. }
  441. if (!isset($oSQLQuery))
  442. {
  443. $oKPI = new ExecutionKPI();
  444. $oSQLQuery = $oSearch->MakeSQLQuery($aAttToLoad, $bGetCount, $aModifierProperties, $aGroupByExpr);
  445. $oSQLQuery->SetSourceOQL($sOqlQuery);
  446. $oKPI->ComputeStats('MakeSQLQuery', $sOqlQuery);
  447. if (self::$m_bQueryCacheEnabled)
  448. {
  449. if (self::$m_bUseAPCCache)
  450. {
  451. $oKPI = new ExecutionKPI();
  452. apc_store($sOqlAPCCacheId, $oSQLQuery, self::$m_iQueryCacheTTL);
  453. $oKPI->ComputeStats('Query APC (store)', $sOqlQuery);
  454. }
  455. self::$m_aQueryStructCache[$sOqlId] = $oSQLQuery->DeepClone();
  456. }
  457. }
  458. // Join to an additional table, if required...
  459. //
  460. if ($aExtendedDataSpec != null)
  461. {
  462. $sTableAlias = '_extended_data_';
  463. $aExtendedFields = array();
  464. foreach($aExtendedDataSpec['fields'] as $sColumn)
  465. {
  466. $sColRef = $oSearch->GetClassAlias().'_extdata_'.$sColumn;
  467. $aExtendedFields[$sColRef] = new FieldExpressionResolved($sColumn, $sTableAlias);
  468. }
  469. $oSQLQueryExt = new SQLObjectQuery($aExtendedDataSpec['table'], $sTableAlias, $aExtendedFields);
  470. $oSQLQuery->AddInnerJoin($oSQLQueryExt, 'id', $aExtendedDataSpec['join_key'] /*, $sTableAlias*/);
  471. }
  472. return $oSQLQuery;
  473. }
  474. ////////////////////////////////////////////////////////////////////////////
  475. //
  476. // Cache/Trace/Log queries
  477. //
  478. ////////////////////////////////////////////////////////////////////////////
  479. protected static $m_bDebugQuery = false;
  480. protected static $m_aQueriesLog = array();
  481. protected static $m_bQueryCacheEnabled = false;
  482. protected static $m_bUseAPCCache = false;
  483. protected static $m_iQueryCacheTTL = 3600;
  484. protected static $m_bTraceQueries = false;
  485. protected static $m_bIndentQueries = false;
  486. protected static $m_bOptimizeQueries = false;
  487. public static function StartDebugQuery()
  488. {
  489. $aBacktrace = debug_backtrace();
  490. self::$m_bDebugQuery = true;
  491. }
  492. public static function StopDebugQuery()
  493. {
  494. self::$m_bDebugQuery = false;
  495. }
  496. public static function EnableQueryCache($bEnabled, $bUseAPC, $iTimeToLive = 3600)
  497. {
  498. self::$m_bQueryCacheEnabled = $bEnabled;
  499. self::$m_bUseAPCCache = $bUseAPC;
  500. self::$m_iQueryCacheTTL = $iTimeToLive;
  501. }
  502. public static function EnableQueryTrace($bEnabled)
  503. {
  504. self::$m_bTraceQueries = $bEnabled;
  505. }
  506. public static function EnableQueryIndentation($bEnabled)
  507. {
  508. self::$m_bIndentQueries = $bEnabled;
  509. }
  510. public static function EnableOptimizeQuery($bEnabled)
  511. {
  512. self::$m_bOptimizeQueries = $bEnabled;
  513. }
  514. protected function AddQueryTraceSelect($aOrderBy, $aArgs, $aAttToLoad, $aExtendedDataSpec, $iLimitCount, $iLimitStart, $bGetCount, $sSql)
  515. {
  516. if (self::$m_bTraceQueries)
  517. {
  518. $aQueryData = array(
  519. 'type' => 'select',
  520. 'filter' => $this,
  521. 'order_by' => $aOrderBy,
  522. 'args' => $aArgs,
  523. 'att_to_load' => $aAttToLoad,
  524. 'extended_data_spec' => $aExtendedDataSpec,
  525. 'limit_count' => $iLimitCount,
  526. 'limit_start' => $iLimitStart,
  527. 'is_count' => $bGetCount
  528. );
  529. $sOql = $this->ToOQL(true, $aArgs);
  530. self::AddQueryTrace($aQueryData, $sOql, $sSql);
  531. }
  532. }
  533. protected function AddQueryTraceGroupBy($aArgs, $aGroupByExpr, $sSql)
  534. {
  535. if (self::$m_bTraceQueries)
  536. {
  537. $aQueryData = array(
  538. 'type' => 'group_by',
  539. 'filter' => $this,
  540. 'args' => $aArgs,
  541. 'group_by_expr' => $aGroupByExpr
  542. );
  543. $sOql = $this->ToOQL(true, $aArgs);
  544. self::AddQueryTrace($aQueryData, $sOql, $sSql);
  545. }
  546. }
  547. protected static function AddQueryTrace($aQueryData, $sOql, $sSql)
  548. {
  549. if (self::$m_bTraceQueries)
  550. {
  551. $sQueryId = md5(serialize($aQueryData));
  552. $sMySQLQueryId = md5($sSql);
  553. if(!isset(self::$m_aQueriesLog[$sQueryId]))
  554. {
  555. self::$m_aQueriesLog[$sQueryId]['data'] = serialize($aQueryData);
  556. self::$m_aQueriesLog[$sQueryId]['oql'] = $sOql;
  557. self::$m_aQueriesLog[$sQueryId]['hits'] = 1;
  558. }
  559. else
  560. {
  561. self::$m_aQueriesLog[$sQueryId]['hits']++;
  562. }
  563. if(!isset(self::$m_aQueriesLog[$sQueryId]['queries'][$sMySQLQueryId]))
  564. {
  565. self::$m_aQueriesLog[$sQueryId]['queries'][$sMySQLQueryId]['sql'] = $sSql;
  566. self::$m_aQueriesLog[$sQueryId]['queries'][$sMySQLQueryId]['count'] = 1;
  567. $iTableCount = count(CMDBSource::ExplainQuery($sSql));
  568. self::$m_aQueriesLog[$sQueryId]['queries'][$sMySQLQueryId]['table_count'] = $iTableCount;
  569. }
  570. else
  571. {
  572. self::$m_aQueriesLog[$sQueryId]['queries'][$sMySQLQueryId]['count']++;
  573. }
  574. }
  575. }
  576. public static function RecordQueryTrace()
  577. {
  578. if (!self::$m_bTraceQueries) return;
  579. $iOqlCount = count(self::$m_aQueriesLog);
  580. $iSqlCount = 0;
  581. foreach (self::$m_aQueriesLog as $sQueryId => $aOqlData)
  582. {
  583. $iSqlCount += $aOqlData['hits'];
  584. }
  585. $sHtml = "<h2>Stats on SELECT queries: OQL=$iOqlCount, SQL=$iSqlCount</h2>\n";
  586. foreach (self::$m_aQueriesLog as $sQueryId => $aOqlData)
  587. {
  588. $sOql = $aOqlData['oql'];
  589. $sHits = $aOqlData['hits'];
  590. $sHtml .= "<p><b>$sHits</b> hits for OQL query: $sOql</p>\n";
  591. $sHtml .= "<ul id=\"ClassesRelationships\" class=\"treeview\">\n";
  592. foreach($aOqlData['queries'] as $aSqlData)
  593. {
  594. $sQuery = $aSqlData['sql'];
  595. $sSqlHits = $aSqlData['count'];
  596. $iTableCount = $aSqlData['table_count'];
  597. $sHtml .= "<li><b>$sSqlHits</b> hits for SQL ($iTableCount tables): <pre style=\"font-size:60%\">$sQuery</pre></li>\n";
  598. }
  599. $sHtml .= "</ul>\n";
  600. }
  601. $sLogFile = 'queries.latest';
  602. file_put_contents(APPROOT.'data/'.$sLogFile.'.html', $sHtml);
  603. $sLog = "<?php\n\$aQueriesLog = ".var_export(self::$m_aQueriesLog, true).";";
  604. file_put_contents(APPROOT.'data/'.$sLogFile.'.log', $sLog);
  605. // Cumulate the queries
  606. $sAllQueries = APPROOT.'data/queries.log';
  607. if (file_exists($sAllQueries))
  608. {
  609. // Merge the new queries into the existing log
  610. include($sAllQueries);
  611. foreach (self::$m_aQueriesLog as $sQueryId => $aOqlData)
  612. {
  613. if (!array_key_exists($sQueryId, $aQueriesLog))
  614. {
  615. $aQueriesLog[$sQueryId] = $aOqlData;
  616. }
  617. }
  618. }
  619. else
  620. {
  621. $aQueriesLog = self::$m_aQueriesLog;
  622. }
  623. $sLog = "<?php\n\$aQueriesLog = ".var_export($aQueriesLog, true).";";
  624. file_put_contents($sAllQueries, $sLog);
  625. }
  626. protected static function DbgTrace($value)
  627. {
  628. if (!self::$m_bDebugQuery) return;
  629. $aBacktrace = debug_backtrace();
  630. $iCallStackPos = count($aBacktrace) - self::$m_bDebugQuery;
  631. $sIndent = "";
  632. for ($i = 0 ; $i < $iCallStackPos ; $i++)
  633. {
  634. $sIndent .= " .-=^=-. ";
  635. }
  636. $aCallers = array();
  637. foreach($aBacktrace as $aStackInfo)
  638. {
  639. $aCallers[] = $aStackInfo["function"];
  640. }
  641. $sCallers = "Callstack: ".implode(', ', $aCallers);
  642. $sFunction = "<b title=\"$sCallers\">".$aBacktrace[1]["function"]."</b>";
  643. if (is_string($value))
  644. {
  645. echo "$sIndent$sFunction: $value<br/>\n";
  646. }
  647. else if (is_object($value))
  648. {
  649. echo "$sIndent$sFunction:\n<pre>\n";
  650. print_r($value);
  651. echo "</pre>\n";
  652. }
  653. else
  654. {
  655. echo "$sIndent$sFunction: $value<br/>\n";
  656. }
  657. }
  658. }