dbsearch.class.php 26 KB

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