dbsearch.class.php 24 KB

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