dbsearch.class.php 25 KB

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