dbsearch.class.php 26 KB

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