dbsearch.class.php 26 KB

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