dbsearch.class.php 24 KB

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