dbsearch.class.php 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788
  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. 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 array|hash $aOrderBy Array of '[<classalias>.]attcode' => bAscending
  303. * @param array $aArgs
  304. * @param null $aAttToLoad
  305. * @param null $aExtendedDataSpec
  306. * @param int $iLimitCount
  307. * @param int $iLimitStart
  308. * @param bool $bGetCount
  309. * @param bool $bNoArguments
  310. * @return string
  311. * @throws CoreException
  312. * @throws Exception
  313. * @throws MissingQueryArgument
  314. */
  315. public function MakeSelectQuery($aOrderBy = array(), $aArgs = array(), $aAttToLoad = null, $aExtendedDataSpec = null, $iLimitCount = 0, $iLimitStart = 0, $bGetCount = false, $bNoArguments = false)
  316. {
  317. // Check the order by specification, and prefix with the class alias
  318. // and make sure that the ordering columns are going to be selected
  319. //
  320. $sClass = $this->GetClass();
  321. $sClassAlias = $this->GetClassAlias();
  322. $aOrderSpec = array();
  323. foreach ($aOrderBy as $sFieldAlias => $bAscending)
  324. {
  325. if (!is_bool($bAscending))
  326. {
  327. throw new CoreException("Wrong direction in ORDER BY spec, found '$bAscending' and expecting a boolean value");
  328. }
  329. $iDotPos = strpos($sFieldAlias, '.');
  330. if ($iDotPos === false)
  331. {
  332. $sAttClass = $sClass;
  333. $sAttClassAlias = $sClassAlias;
  334. $sAttCode = $sFieldAlias;
  335. }
  336. else
  337. {
  338. $sAttClassAlias = substr($sFieldAlias, 0, $iDotPos);
  339. $sAttClass = $this->GetClassName($sAttClassAlias);
  340. $sAttCode = substr($sFieldAlias, $iDotPos + 1);
  341. }
  342. if ($sAttCode != 'id')
  343. {
  344. MyHelpers::CheckValueInArray('field name in ORDER BY spec', $sAttCode, MetaModel::GetAttributesList($sAttClass));
  345. $oAttDef = MetaModel::GetAttributeDef($sAttClass, $sAttCode);
  346. foreach($oAttDef->GetOrderBySQLExpressions($sAttClassAlias) as $sSQLExpression)
  347. {
  348. $aOrderSpec[$sSQLExpression] = $bAscending;
  349. }
  350. }
  351. else
  352. {
  353. $aOrderSpec['`'.$sAttClassAlias.$sAttCode.'`'] = $bAscending;
  354. }
  355. // Make sure that the columns used for sorting are present in the loaded columns
  356. if (!is_null($aAttToLoad) && !isset($aAttToLoad[$sAttClassAlias][$sAttCode]))
  357. {
  358. $aAttToLoad[$sAttClassAlias][$sAttCode] = MetaModel::GetAttributeDef($sAttClass, $sAttCode);
  359. }
  360. }
  361. $oSQLQuery = $this->GetSQLQuery($aOrderBy, $aArgs, $aAttToLoad, $aExtendedDataSpec, $iLimitCount, $iLimitStart, $bGetCount);
  362. if ($bNoArguments)
  363. {
  364. // Only internal parameters
  365. $aScalarArgs = $this->GetInternalParams();
  366. }
  367. else
  368. {
  369. // The complete list of arguments will include magic arguments (e.g. current_user->attcode)
  370. $aScalarArgs = MetaModel::PrepareQueryArguments($aArgs, $this->GetInternalParams());
  371. }
  372. try
  373. {
  374. $bBeautifulSQL = self::$m_bTraceQueries || self::$m_bDebugQuery || self::$m_bIndentQueries;
  375. $sRes = $oSQLQuery->RenderSelect($aOrderSpec, $aScalarArgs, $iLimitCount, $iLimitStart, $bGetCount, $bBeautifulSQL);
  376. if ($sClassAlias == '_itop_')
  377. {
  378. IssueLog::Info('SQL Query (_itop_): '.$sRes);
  379. }
  380. }
  381. catch (MissingQueryArgument $e)
  382. {
  383. // Add some information...
  384. $e->addInfo('OQL', $this->ToOQL());
  385. throw $e;
  386. }
  387. $this->AddQueryTraceSelect($aOrderBy, $aArgs, $aAttToLoad, $aExtendedDataSpec, $iLimitCount, $iLimitStart, $bGetCount, $sRes);
  388. return $sRes;
  389. }
  390. protected function GetSQLQuery($aOrderBy, $aArgs, $aAttToLoad, $aExtendedDataSpec, $iLimitCount, $iLimitStart, $bGetCount, $aGroupByExpr = null)
  391. {
  392. // Hide objects that are not visible to the current user
  393. //
  394. $oSearch = $this;
  395. if (!$this->IsAllDataAllowed() && !$this->IsDataFiltered())
  396. {
  397. $oVisibleObjects = UserRights::GetSelectFilter($this->GetClass(), $this->GetModifierProperties('UserRightsGetSelectFilter'));
  398. if ($oVisibleObjects === false)
  399. {
  400. // Make sure this is a valid search object, saying NO for all
  401. $oVisibleObjects = DBObjectSearch::FromEmptySet($this->GetClass());
  402. }
  403. if (is_object($oVisibleObjects))
  404. {
  405. $oSearch = $this->Intersect($oVisibleObjects);
  406. $oSearch->SetDataFiltered();
  407. }
  408. else
  409. {
  410. // should be true at this point, meaning that no additional filtering
  411. // is required
  412. }
  413. }
  414. // Compute query modifiers properties (can be set in the search itself, by the context, etc.)
  415. //
  416. $aModifierProperties = MetaModel::MakeModifierProperties($oSearch);
  417. // Create a unique cache id
  418. //
  419. if (self::$m_bQueryCacheEnabled || self::$m_bTraceQueries)
  420. {
  421. // Need to identify the query
  422. $sOqlQuery = $oSearch->ToOql();
  423. if (count($aModifierProperties))
  424. {
  425. array_multisort($aModifierProperties);
  426. $sModifierProperties = json_encode($aModifierProperties);
  427. }
  428. else
  429. {
  430. $sModifierProperties = '';
  431. }
  432. $sRawId = $sOqlQuery.$sModifierProperties;
  433. if (!is_null($aAttToLoad))
  434. {
  435. $sRawId .= json_encode($aAttToLoad);
  436. }
  437. if (!is_null($aGroupByExpr))
  438. {
  439. foreach($aGroupByExpr as $sAlias => $oExpr)
  440. {
  441. $sRawId .= 'g:'.$sAlias.'!'.$oExpr->Render();
  442. }
  443. }
  444. $sRawId .= $bGetCount;
  445. $sOqlId = md5($sRawId);
  446. }
  447. else
  448. {
  449. $sOqlQuery = "SELECTING... ".$oSearch->GetClass();
  450. $sOqlId = "query id ? n/a";
  451. }
  452. // Query caching
  453. //
  454. if (self::$m_bQueryCacheEnabled)
  455. {
  456. // Warning: using directly the query string as the key to the hash array can FAIL if the string
  457. // is long and the differences are only near the end... so it's safer (but not bullet proof?)
  458. // to use a hash (like md5) of the string as the key !
  459. //
  460. // Example of two queries that were found as similar by the hash array:
  461. // 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
  462. // and
  463. // 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
  464. // the only difference is R instead or O at position 285 (TTR instead of TTO)...
  465. //
  466. if (array_key_exists($sOqlId, self::$m_aQueryStructCache))
  467. {
  468. // hit!
  469. $oSQLQuery = unserialize(serialize(self::$m_aQueryStructCache[$sOqlId]));
  470. // Note: cloning is not enough because the subtree is made of objects
  471. }
  472. elseif (self::$m_bUseAPCCache)
  473. {
  474. // Note: For versions of APC older than 3.0.17, fetch() accepts only one parameter
  475. //
  476. $sOqlAPCCacheId = 'itop-'.MetaModel::GetEnvironmentId().'-query-cache-'.$sOqlId;
  477. $oKPI = new ExecutionKPI();
  478. $result = apc_fetch($sOqlAPCCacheId);
  479. $oKPI->ComputeStats('Query APC (fetch)', $sOqlQuery);
  480. if (is_object($result))
  481. {
  482. $oSQLQuery = $result;
  483. self::$m_aQueryStructCache[$sOqlId] = $oSQLQuery;
  484. }
  485. }
  486. }
  487. if (!isset($oSQLQuery))
  488. {
  489. $oKPI = new ExecutionKPI();
  490. $oSQLQuery = $oSearch->MakeSQLQuery($aAttToLoad, $bGetCount, $aModifierProperties, $aGroupByExpr);
  491. $oSQLQuery->SetSourceOQL($sOqlQuery);
  492. $oKPI->ComputeStats('MakeSQLQuery', $sOqlQuery);
  493. if (self::$m_bQueryCacheEnabled)
  494. {
  495. if (self::$m_bUseAPCCache)
  496. {
  497. $oKPI = new ExecutionKPI();
  498. apc_store($sOqlAPCCacheId, $oSQLQuery, self::$m_iQueryCacheTTL);
  499. $oKPI->ComputeStats('Query APC (store)', $sOqlQuery);
  500. }
  501. self::$m_aQueryStructCache[$sOqlId] = $oSQLQuery->DeepClone();
  502. }
  503. }
  504. // Join to an additional table, if required...
  505. //
  506. if ($aExtendedDataSpec != null)
  507. {
  508. $sTableAlias = '_extended_data_';
  509. $aExtendedFields = array();
  510. foreach($aExtendedDataSpec['fields'] as $sColumn)
  511. {
  512. $sColRef = $oSearch->GetClassAlias().'_extdata_'.$sColumn;
  513. $aExtendedFields[$sColRef] = new FieldExpressionResolved($sColumn, $sTableAlias);
  514. }
  515. $oSQLQueryExt = new SQLObjectQuery($aExtendedDataSpec['table'], $sTableAlias, $aExtendedFields);
  516. $oSQLQuery->AddInnerJoin($oSQLQueryExt, 'id', $aExtendedDataSpec['join_key'] /*, $sTableAlias*/);
  517. }
  518. return $oSQLQuery;
  519. }
  520. ////////////////////////////////////////////////////////////////////////////
  521. //
  522. // Cache/Trace/Log queries
  523. //
  524. ////////////////////////////////////////////////////////////////////////////
  525. protected static $m_bDebugQuery = false;
  526. protected static $m_aQueriesLog = array();
  527. protected static $m_bQueryCacheEnabled = false;
  528. protected static $m_bUseAPCCache = false;
  529. protected static $m_iQueryCacheTTL = 3600;
  530. protected static $m_bTraceQueries = false;
  531. protected static $m_bIndentQueries = false;
  532. protected static $m_bOptimizeQueries = false;
  533. public static function StartDebugQuery()
  534. {
  535. $aBacktrace = debug_backtrace();
  536. self::$m_bDebugQuery = true;
  537. }
  538. public static function StopDebugQuery()
  539. {
  540. self::$m_bDebugQuery = false;
  541. }
  542. public static function EnableQueryCache($bEnabled, $bUseAPC, $iTimeToLive = 3600)
  543. {
  544. self::$m_bQueryCacheEnabled = $bEnabled;
  545. self::$m_bUseAPCCache = $bUseAPC;
  546. self::$m_iQueryCacheTTL = $iTimeToLive;
  547. }
  548. public static function EnableQueryTrace($bEnabled)
  549. {
  550. self::$m_bTraceQueries = $bEnabled;
  551. }
  552. public static function EnableQueryIndentation($bEnabled)
  553. {
  554. self::$m_bIndentQueries = $bEnabled;
  555. }
  556. public static function EnableOptimizeQuery($bEnabled)
  557. {
  558. self::$m_bOptimizeQueries = $bEnabled;
  559. }
  560. protected function AddQueryTraceSelect($aOrderBy, $aArgs, $aAttToLoad, $aExtendedDataSpec, $iLimitCount, $iLimitStart, $bGetCount, $sSql)
  561. {
  562. if (self::$m_bTraceQueries)
  563. {
  564. $aQueryData = array(
  565. 'type' => 'select',
  566. 'filter' => $this,
  567. 'order_by' => $aOrderBy,
  568. 'args' => $aArgs,
  569. 'att_to_load' => $aAttToLoad,
  570. 'extended_data_spec' => $aExtendedDataSpec,
  571. 'limit_count' => $iLimitCount,
  572. 'limit_start' => $iLimitStart,
  573. 'is_count' => $bGetCount
  574. );
  575. $sOql = $this->ToOQL(true, $aArgs);
  576. self::AddQueryTrace($aQueryData, $sOql, $sSql);
  577. }
  578. }
  579. protected function AddQueryTraceGroupBy($aArgs, $aGroupByExpr, $sSql)
  580. {
  581. if (self::$m_bTraceQueries)
  582. {
  583. $aQueryData = array(
  584. 'type' => 'group_by',
  585. 'filter' => $this,
  586. 'args' => $aArgs,
  587. 'group_by_expr' => $aGroupByExpr
  588. );
  589. $sOql = $this->ToOQL(true, $aArgs);
  590. self::AddQueryTrace($aQueryData, $sOql, $sSql);
  591. }
  592. }
  593. protected static function AddQueryTrace($aQueryData, $sOql, $sSql)
  594. {
  595. if (self::$m_bTraceQueries)
  596. {
  597. $sQueryId = md5(serialize($aQueryData));
  598. $sMySQLQueryId = md5($sSql);
  599. if(!isset(self::$m_aQueriesLog[$sQueryId]))
  600. {
  601. self::$m_aQueriesLog[$sQueryId]['data'] = serialize($aQueryData);
  602. self::$m_aQueriesLog[$sQueryId]['oql'] = $sOql;
  603. self::$m_aQueriesLog[$sQueryId]['hits'] = 1;
  604. }
  605. else
  606. {
  607. self::$m_aQueriesLog[$sQueryId]['hits']++;
  608. }
  609. if(!isset(self::$m_aQueriesLog[$sQueryId]['queries'][$sMySQLQueryId]))
  610. {
  611. self::$m_aQueriesLog[$sQueryId]['queries'][$sMySQLQueryId]['sql'] = $sSql;
  612. self::$m_aQueriesLog[$sQueryId]['queries'][$sMySQLQueryId]['count'] = 1;
  613. $iTableCount = count(CMDBSource::ExplainQuery($sSql));
  614. self::$m_aQueriesLog[$sQueryId]['queries'][$sMySQLQueryId]['table_count'] = $iTableCount;
  615. }
  616. else
  617. {
  618. self::$m_aQueriesLog[$sQueryId]['queries'][$sMySQLQueryId]['count']++;
  619. }
  620. }
  621. }
  622. public static function RecordQueryTrace()
  623. {
  624. if (!self::$m_bTraceQueries) return;
  625. $iOqlCount = count(self::$m_aQueriesLog);
  626. $iSqlCount = 0;
  627. foreach (self::$m_aQueriesLog as $sQueryId => $aOqlData)
  628. {
  629. $iSqlCount += $aOqlData['hits'];
  630. }
  631. $sHtml = "<h2>Stats on SELECT queries: OQL=$iOqlCount, SQL=$iSqlCount</h2>\n";
  632. foreach (self::$m_aQueriesLog as $sQueryId => $aOqlData)
  633. {
  634. $sOql = $aOqlData['oql'];
  635. $sHits = $aOqlData['hits'];
  636. $sHtml .= "<p><b>$sHits</b> hits for OQL query: $sOql</p>\n";
  637. $sHtml .= "<ul id=\"ClassesRelationships\" class=\"treeview\">\n";
  638. foreach($aOqlData['queries'] as $aSqlData)
  639. {
  640. $sQuery = $aSqlData['sql'];
  641. $sSqlHits = $aSqlData['count'];
  642. $iTableCount = $aSqlData['table_count'];
  643. $sHtml .= "<li><b>$sSqlHits</b> hits for SQL ($iTableCount tables): <pre style=\"font-size:60%\">$sQuery</pre></li>\n";
  644. }
  645. $sHtml .= "</ul>\n";
  646. }
  647. $sLogFile = 'queries.latest';
  648. file_put_contents(APPROOT.'data/'.$sLogFile.'.html', $sHtml);
  649. $sLog = "<?php\n\$aQueriesLog = ".var_export(self::$m_aQueriesLog, true).";";
  650. file_put_contents(APPROOT.'data/'.$sLogFile.'.log', $sLog);
  651. // Cumulate the queries
  652. $sAllQueries = APPROOT.'data/queries.log';
  653. if (file_exists($sAllQueries))
  654. {
  655. // Merge the new queries into the existing log
  656. include($sAllQueries);
  657. foreach (self::$m_aQueriesLog as $sQueryId => $aOqlData)
  658. {
  659. if (!array_key_exists($sQueryId, $aQueriesLog))
  660. {
  661. $aQueriesLog[$sQueryId] = $aOqlData;
  662. }
  663. }
  664. }
  665. else
  666. {
  667. $aQueriesLog = self::$m_aQueriesLog;
  668. }
  669. $sLog = "<?php\n\$aQueriesLog = ".var_export($aQueriesLog, true).";";
  670. file_put_contents($sAllQueries, $sLog);
  671. }
  672. protected static function DbgTrace($value)
  673. {
  674. if (!self::$m_bDebugQuery) return;
  675. $aBacktrace = debug_backtrace();
  676. $iCallStackPos = count($aBacktrace) - self::$m_bDebugQuery;
  677. $sIndent = "";
  678. for ($i = 0 ; $i < $iCallStackPos ; $i++)
  679. {
  680. $sIndent .= " .-=^=-. ";
  681. }
  682. $aCallers = array();
  683. foreach($aBacktrace as $aStackInfo)
  684. {
  685. $aCallers[] = $aStackInfo["function"];
  686. }
  687. $sCallers = "Callstack: ".implode(', ', $aCallers);
  688. $sFunction = "<b title=\"$sCallers\">".$aBacktrace[1]["function"]."</b>";
  689. if (is_string($value))
  690. {
  691. echo "$sIndent$sFunction: $value<br/>\n";
  692. }
  693. else if (is_object($value))
  694. {
  695. echo "$sIndent$sFunction:\n<pre>\n";
  696. print_r($value);
  697. echo "</pre>\n";
  698. }
  699. else
  700. {
  701. echo "$sIndent$sFunction: $value<br/>\n";
  702. }
  703. }
  704. }