sqlquery.class.inc.php 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689
  1. <?php
  2. // Copyright (C) 2010-2012 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. /**
  19. * SQLQuery
  20. * build an mySQL compatible SQL query
  21. *
  22. * @copyright Copyright (C) 2010-2012 Combodo SARL
  23. * @license http://opensource.org/licenses/AGPL-3.0
  24. */
  25. /**
  26. * SQLQuery
  27. * build an mySQL compatible SQL query
  28. *
  29. * @package iTopORM
  30. */
  31. require_once('cmdbsource.class.inc.php');
  32. class SQLQuery
  33. {
  34. private $m_SourceOQL = '';
  35. private $m_sTable = '';
  36. private $m_sTableAlias = '';
  37. private $m_aFields = array();
  38. private $m_aGroupBy = array();
  39. private $m_oConditionExpr = null;
  40. private $m_bToDelete = true; // The current table must be listed for deletion ?
  41. private $m_aValues = array(); // Values to set in case of an update query
  42. private $m_oSelectedIdField = null;
  43. private $m_aJoinSelects = array();
  44. private $m_bBeautifulQuery = false;
  45. public function __construct($sTable, $sTableAlias, $aFields, $bToDelete = true, $aValues = array(), $oSelectedIdField = null)
  46. {
  47. // This check is not needed but for developping purposes
  48. //if (!CMDBSource::IsTable($sTable))
  49. //{
  50. // throw new CoreException("Unknown table '$sTable'");
  51. //}
  52. // $aFields must be an array of "alias"=>"expr"
  53. // $oConditionExpr must be a condition tree
  54. // $aValues is an array of "alias"=>value
  55. $this->m_sTable = $sTable;
  56. $this->m_sTableAlias = $sTableAlias;
  57. $this->m_aFields = $aFields;
  58. $this->m_aGroupBy = null;
  59. $this->m_oConditionExpr = null;
  60. $this->m_bToDelete = $bToDelete;
  61. $this->m_aValues = $aValues;
  62. $this->m_oSelectedIdField = $oSelectedIdField;
  63. }
  64. public function GetTableAlias()
  65. {
  66. return $this->m_sTableAlias;
  67. }
  68. public function SetSourceOQL($sOQL)
  69. {
  70. $this->m_SourceOQL = $sOQL;
  71. }
  72. public function GetSourceOQL()
  73. {
  74. return $this->m_SourceOQL;
  75. }
  76. public function DisplayHtml()
  77. {
  78. if (count($this->m_aFields) == 0) $sFields = "";
  79. else
  80. {
  81. $aFieldDesc = array();
  82. foreach ($this->m_aFields as $sAlias => $oExpression)
  83. {
  84. $aFieldDesc[] = $oExpression->Render()." as <em>$sAlias</em>";
  85. }
  86. $sFields = " =&gt; ".implode(', ', $aFieldDesc);
  87. }
  88. echo "<b>$this->m_sTable</b>$sFields<br/>\n";
  89. // #@# todo - display html of an expression tree
  90. //$this->m_oConditionExpr->DisplayHtml()
  91. if (count($this->m_aJoinSelects) > 0)
  92. {
  93. echo "Joined to...<br/>\n";
  94. echo "<ul class=\"treeview\">\n";
  95. foreach ($this->m_aJoinSelects as $aJoinInfo)
  96. {
  97. $sJoinType = $aJoinInfo["jointype"];
  98. $oSQLQuery = $aJoinInfo["select"];
  99. if (isset($aJoinInfo["on_expression"]))
  100. {
  101. $sOnCondition = $aJoinInfo["on_expression"]->Render();
  102. echo "<li>Join '$sJoinType', ON ($sOnCondition)".$oSQLQuery->DisplayHtml()."</li>\n";
  103. }
  104. else
  105. {
  106. $sLeftField = $aJoinInfo["leftfield"];
  107. $sRightField = $aJoinInfo["rightfield"];
  108. $sRightTableAlias = $aJoinInfo["righttablealias"];
  109. echo "<li>Join '$sJoinType', $sLeftField, $sRightTableAlias.$sRightField".$oSQLQuery->DisplayHtml()."</li>\n";
  110. }
  111. }
  112. echo "</ul>";
  113. }
  114. $aFrom = array();
  115. $aFields = array();
  116. $aGroupBy = array();
  117. $oCondition = null;
  118. $aDelTables = array();
  119. $aSetValues = array();
  120. $aSelectedIdFields = array();
  121. $this->privRender($aFrom, $aFields, $aGroupBy, $oCondition, $aDelTables, $aSetValues, $aSelectedIdFields);
  122. echo "From ...<br/>\n";
  123. echo "<pre style=\"font-size: smaller;\">\n";
  124. print_r($aFrom);
  125. echo "</pre>";
  126. }
  127. public function SetSelect($aExpressions)
  128. {
  129. $this->m_aFields = $aExpressions;
  130. }
  131. public function SetGroupBy($aExpressions)
  132. {
  133. $this->m_aGroupBy = $aExpressions;
  134. }
  135. public function SetCondition($oConditionExpr)
  136. {
  137. $this->m_oConditionExpr = $oConditionExpr;
  138. }
  139. public function AddCondition($oConditionExpr)
  140. {
  141. if (is_null($this->m_oConditionExpr))
  142. {
  143. $this->m_oConditionExpr = $oConditionExpr;
  144. }
  145. else
  146. {
  147. $this->m_oConditionExpr->LogAnd($oConditionExpr);
  148. }
  149. }
  150. private function AddJoin($sJoinType, $oSQLQuery, $sLeftField, $sRightField, $sRightTableAlias = '')
  151. {
  152. assert((get_class($oSQLQuery) == __CLASS__) || is_subclass_of($oSQLQuery, __CLASS__));
  153. // No need to check this here but for development purposes
  154. //if (!CMDBSource::IsField($this->m_sTable, $sLeftField))
  155. //{
  156. // throw new CoreException("Unknown field '$sLeftField' in table '".$this->m_sTable);
  157. //}
  158. if (empty($sRightTableAlias))
  159. {
  160. $sRightTableAlias = $oSQLQuery->m_sTableAlias;
  161. }
  162. // #@# Could not be verified here because the namespace is unknown - do we need to check it there?
  163. //
  164. // if (!CMDBSource::IsField($sRightTable, $sRightField))
  165. // {
  166. // throw new CoreException("Unknown field '$sRightField' in table '".$sRightTable."'");
  167. // }
  168. $this->m_aJoinSelects[] = array(
  169. "jointype" => $sJoinType,
  170. "select" => $oSQLQuery,
  171. "leftfield" => $sLeftField,
  172. "rightfield" => $sRightField,
  173. "righttablealias" => $sRightTableAlias
  174. );
  175. }
  176. public function AddInnerJoin($oSQLQuery, $sLeftField, $sRightField, $sRightTable = '')
  177. {
  178. $this->AddJoin("inner", $oSQLQuery, $sLeftField, $sRightField, $sRightTable);
  179. }
  180. public function AddInnerJoinTree($oSQLQuery, $sLeftFieldLeft, $sLeftFieldRight, $sRightFieldLeft, $sRightFieldRight, $sRightTableAlias = '', $iOperatorCode = TREE_OPERATOR_BELOW)
  181. {
  182. assert((get_class($oSQLQuery) == __CLASS__) || is_subclass_of($oSQLQuery, __CLASS__));
  183. if (empty($sRightTableAlias))
  184. {
  185. $sRightTableAlias = $oSQLQuery->m_sTableAlias;
  186. }
  187. $this->m_aJoinSelects[] = array(
  188. "jointype" => 'inner_tree',
  189. "select" => $oSQLQuery,
  190. "leftfield" => $sLeftFieldLeft,
  191. "rightfield" => $sLeftFieldRight,
  192. "rightfield_left" => $sRightFieldLeft,
  193. "rightfield_right" => $sRightFieldRight,
  194. "righttablealias" => $sRightTableAlias,
  195. "tree_operator" => $iOperatorCode);
  196. }
  197. public function AddLeftJoin($oSQLQuery, $sLeftField, $sRightField)
  198. {
  199. return $this->AddJoin("left", $oSQLQuery, $sLeftField, $sRightField);
  200. }
  201. public function AddInnerJoinEx(SQLQuery $oSQLQuery, Expression $oOnExpression)
  202. {
  203. $this->m_aJoinSelects[] = array(
  204. "jointype" => 'inner',
  205. "select" => $oSQLQuery,
  206. "on_expression" => $oOnExpression
  207. );
  208. }
  209. public function AddLeftJoinEx(SQLQuery $oSQLQuery, Expression $oOnExpression)
  210. {
  211. $this->m_aJoinSelects[] = array(
  212. "jointype" => 'left',
  213. "select" => $oSQLQuery,
  214. "on_expression" => $oOnExpression
  215. );
  216. }
  217. // Interface, build the SQL query
  218. public function RenderDelete($aArgs = array())
  219. {
  220. // The goal will be to complete the list as we build the Joins
  221. $aFrom = array();
  222. $aFields = array();
  223. $aGroupBy = array();
  224. $oCondition = null;
  225. $aDelTables = array();
  226. $aSetValues = array();
  227. $aSelectedIdFields = array();
  228. $this->privRender($aFrom, $aFields, $aGroupBy, $oCondition, $aDelTables, $aSetValues, $aSelectedIdFields);
  229. // Target: DELETE myAlias1, myAlias2 FROM t1 as myAlias1, t2 as myAlias2, t3 as topreserve WHERE ...
  230. $sDelete = self::ClauseDelete($aDelTables);
  231. $sFrom = self::ClauseFrom($aFrom);
  232. // #@# safety net to redo ?
  233. /*
  234. if ($this->m_oConditionExpr->IsAny())
  235. -- if (count($aConditions) == 0) --
  236. {
  237. throw new CoreException("Building a request wich will delete every object of a given table -looks suspicious- please use truncate instead...");
  238. }
  239. */
  240. if (is_null($oCondition))
  241. {
  242. // Delete all !!!
  243. }
  244. else
  245. {
  246. $sWhere = self::ClauseWhere($oCondition, $aArgs);
  247. return "DELETE $sDelete FROM $sFrom WHERE $sWhere";
  248. }
  249. }
  250. // Interface, build the SQL query
  251. public function RenderUpdate($aArgs = array())
  252. {
  253. // The goal will be to complete the list as we build the Joins
  254. $aFrom = array();
  255. $aFields = array();
  256. $aGroupBy = array();
  257. $oCondition = null;
  258. $aDelTables = array();
  259. $aSetValues = array();
  260. $aSelectedIdFields = array();
  261. $this->privRender($aFrom, $aFields, $aGroupBy, $oCondition, $aDelTables, $aSetValues, $aSelectedIdFields);
  262. $sFrom = self::ClauseFrom($aFrom);
  263. $sValues = self::ClauseValues($aSetValues);
  264. $sWhere = self::ClauseWhere($oCondition, $aArgs);
  265. return "UPDATE $sFrom SET $sValues WHERE $sWhere";
  266. }
  267. // Interface, build the SQL query
  268. public function RenderSelect($aOrderBy = array(), $aArgs = array(), $iLimitCount = 0, $iLimitStart = 0, $bGetCount = false, $bBeautifulQuery = false)
  269. {
  270. $this->m_bBeautifulQuery = $bBeautifulQuery;
  271. $sLineSep = $this->m_bBeautifulQuery ? "\n" : '';
  272. $sIndent = $this->m_bBeautifulQuery ? " " : null;
  273. // The goal will be to complete the lists as we build the Joins
  274. $aFrom = array();
  275. $aFields = array();
  276. $aGroupBy = array();
  277. $oCondition = null;
  278. $aDelTables = array();
  279. $aSetValues = array();
  280. $aSelectedIdFields = array();
  281. $this->privRender($aFrom, $aFields, $aGroupBy, $oCondition, $aDelTables, $aSetValues, $aSelectedIdFields);
  282. $sFrom = self::ClauseFrom($aFrom, $sIndent);
  283. $sWhere = self::ClauseWhere($oCondition, $aArgs);
  284. if ($bGetCount)
  285. {
  286. if (count($aSelectedIdFields) > 0)
  287. {
  288. $aCountFields = array();
  289. foreach ($aSelectedIdFields as $sFieldExpr)
  290. {
  291. $aCountFields[] = "COALESCE($sFieldExpr, 0)"; // Null values are excluded from the count
  292. }
  293. $sCountFields = implode(', ', $aCountFields);
  294. $sSQL = "SELECT$sLineSep COUNT(DISTINCT $sCountFields) AS COUNT$sLineSep FROM $sFrom$sLineSep WHERE $sWhere";
  295. }
  296. else
  297. {
  298. $sSQL = "SELECT$sLineSep COUNT(*) AS COUNT$sLineSep FROM $sFrom$sLineSep WHERE $sWhere";
  299. }
  300. }
  301. else
  302. {
  303. $sSelect = self::ClauseSelect($aFields);
  304. $sOrderBy = self::ClauseOrderBy($aOrderBy);
  305. if (!empty($sOrderBy))
  306. {
  307. $sOrderBy = "ORDER BY $sOrderBy";
  308. }
  309. if ($iLimitCount > 0)
  310. {
  311. $sLimit = 'LIMIT '.$iLimitStart.', '.$iLimitCount;
  312. }
  313. else
  314. {
  315. $sLimit = '';
  316. }
  317. $sSQL = "SELECT$sLineSep DISTINCT $sSelect$sLineSep FROM $sFrom$sLineSep WHERE $sWhere$sLineSep $sOrderBy$sLineSep $sLimit";
  318. }
  319. return $sSQL;
  320. }
  321. // Interface, build the SQL query
  322. public function RenderGroupBy($aArgs = array(), $bBeautifulQuery = false)
  323. {
  324. $this->m_bBeautifulQuery = $bBeautifulQuery;
  325. $sLineSep = $this->m_bBeautifulQuery ? "\n" : '';
  326. $sIndent = $this->m_bBeautifulQuery ? " " : null;
  327. // The goal will be to complete the lists as we build the Joins
  328. $aFrom = array();
  329. $aFields = array();
  330. $aGroupBy = array();
  331. $oCondition = null;
  332. $aDelTables = array();
  333. $aSetValues = array();
  334. $aSelectedIdFields = array();
  335. $this->privRender($aFrom, $aFields, $aGroupBy, $oCondition, $aDelTables, $aSetValues, $aSelectedIdFields);
  336. $sSelect = self::ClauseSelect($aFields);
  337. $sFrom = self::ClauseFrom($aFrom, $sIndent);
  338. $sWhere = self::ClauseWhere($oCondition, $aArgs);
  339. $sGroupBy = self::ClauseGroupBy($aGroupBy);
  340. $sSQL = "SELECT $sSelect,$sLineSep COUNT(*) AS _itop_count_$sLineSep FROM $sFrom$sLineSep WHERE $sWhere$sLineSep GROUP BY $sGroupBy";
  341. return $sSQL;
  342. }
  343. private static function ClauseSelect($aFields)
  344. {
  345. $aSelect = array();
  346. foreach ($aFields as $sFieldAlias => $sSQLExpr)
  347. {
  348. $aSelect[] = "$sSQLExpr AS $sFieldAlias";
  349. }
  350. $sSelect = implode(', ', $aSelect);
  351. return $sSelect;
  352. }
  353. private static function ClauseGroupBy($aGroupBy)
  354. {
  355. $sRes = implode(', ', $aGroupBy);
  356. return $sRes;
  357. }
  358. private static function ClauseDelete($aDelTableAliases)
  359. {
  360. $aDelTables = array();
  361. foreach ($aDelTableAliases as $sTableAlias)
  362. {
  363. $aDelTables[] = "$sTableAlias";
  364. }
  365. $sDelTables = implode(', ', $aDelTables);
  366. return $sDelTables;
  367. }
  368. private static function ClauseFrom($aFrom, $sIndent = null, $iIndentLevel = 0)
  369. {
  370. $sLineBreakLong = $sIndent ? "\n".str_repeat($sIndent, $iIndentLevel + 1) : '';
  371. $sLineBreak = $sIndent ? "\n".str_repeat($sIndent, $iIndentLevel) : '';
  372. $sFrom = "";
  373. foreach ($aFrom as $sTableAlias => $aJoinInfo)
  374. {
  375. switch ($aJoinInfo["jointype"])
  376. {
  377. case "first":
  378. $sFrom .= $sLineBreakLong."`".$aJoinInfo["tablename"]."` AS `$sTableAlias`";
  379. $sFrom .= self::ClauseFrom($aJoinInfo["subfrom"], $sIndent, $iIndentLevel + 1);
  380. break;
  381. case "inner":
  382. case "inner_tree":
  383. $sFrom .= $sLineBreak."INNER JOIN ($sLineBreakLong`".$aJoinInfo["tablename"]."` AS `$sTableAlias`";
  384. $sFrom .= " ".self::ClauseFrom($aJoinInfo["subfrom"], $sIndent, $iIndentLevel + 1);
  385. $sFrom .= $sLineBreak.") ON ".$aJoinInfo["joincondition"];
  386. break;
  387. case "left":
  388. $sFrom .= $sLineBreak."LEFT JOIN ($sLineBreakLong`".$aJoinInfo["tablename"]."` AS `$sTableAlias`";
  389. $sFrom .= " ".self::ClauseFrom($aJoinInfo["subfrom"], $sIndent, $iIndentLevel + 1);
  390. $sFrom .= $sLineBreak.") ON ".$aJoinInfo["joincondition"];
  391. break;
  392. default:
  393. throw new CoreException("Unknown jointype: '".$aJoinInfo["jointype"]."'");
  394. }
  395. }
  396. return $sFrom;
  397. }
  398. private static function ClauseValues($aValues)
  399. {
  400. $aSetValues = array();
  401. foreach ($aValues as $sFieldSpec => $value)
  402. {
  403. $aSetValues[] = "$sFieldSpec = ".CMDBSource::Quote($value);
  404. }
  405. $sSetValues = implode(', ', $aSetValues);
  406. return $sSetValues;
  407. }
  408. private static function ClauseWhere($oConditionExpr, $aArgs = array())
  409. {
  410. if (is_null($oConditionExpr))
  411. {
  412. return '1';
  413. }
  414. else
  415. {
  416. return $oConditionExpr->Render($aArgs);
  417. }
  418. }
  419. private static function ClauseOrderBy($aOrderBy)
  420. {
  421. $aOrderBySpec = array();
  422. foreach($aOrderBy as $sFieldAlias => $bAscending)
  423. {
  424. // Note: sFieldAlias must have backticks around column aliases
  425. $aOrderBySpec[] = $sFieldAlias.($bAscending ? " ASC" : " DESC");
  426. }
  427. $sOrderBy = implode(", ", $aOrderBySpec);
  428. return $sOrderBy;
  429. }
  430. // Purpose: prepare the query data, once for all
  431. private function privRender(&$aFrom, &$aFields, &$aGroupBy, &$oCondition, &$aDelTables, &$aSetValues, &$aSelectedIdFields)
  432. {
  433. $sTableAlias = $this->privRenderSingleTable($aFrom, $aFields, $aGroupBy, $aDelTables, $aSetValues, $aSelectedIdFields, '', array('jointype' => 'first'));
  434. $oCondition = $this->m_oConditionExpr;
  435. return $sTableAlias;
  436. }
  437. private function privRenderSingleTable(&$aFrom, &$aFields, &$aGroupBy, &$aDelTables, &$aSetValues, &$aSelectedIdFields, $sCallerAlias = '', $aJoinData)
  438. {
  439. $aActualTableFields = CMDBSource::GetTableFieldsList($this->m_sTable);
  440. $aTranslationTable[$this->m_sTable]['*'] = $this->m_sTableAlias;
  441. // Handle the various kinds of join (or first table in the list)
  442. //
  443. if (empty($aJoinData['righttablealias']))
  444. {
  445. $sRightTableAlias = $this->m_sTableAlias;
  446. }
  447. else
  448. {
  449. $sRightTableAlias = $aJoinData['righttablealias'];
  450. }
  451. switch ($aJoinData['jointype'])
  452. {
  453. case "first":
  454. $aFrom[$this->m_sTableAlias] = array("jointype"=>"first", "tablename"=>$this->m_sTable, "joincondition"=>"");
  455. break;
  456. case "inner":
  457. case "left":
  458. if (isset($aJoinData["on_expression"]))
  459. {
  460. $sJoinCond = $aJoinData["on_expression"]->Render();
  461. }
  462. else
  463. {
  464. $sJoinCond = "`$sCallerAlias`.`{$aJoinData['leftfield']}` = `$sRightTableAlias`.`{$aJoinData['rightfield']}`";
  465. }
  466. $aFrom[$this->m_sTableAlias] = array("jointype"=>$aJoinData['jointype'], "tablename"=>$this->m_sTable, "joincondition"=>"$sJoinCond");
  467. break;
  468. case "inner_tree":
  469. $sNodeLeft = "`$sCallerAlias`.`{$aJoinData['leftfield']}`";
  470. $sNodeRight = "`$sCallerAlias`.`{$aJoinData['rightfield']}`";
  471. $sRootLeft = "`$sRightTableAlias`.`{$aJoinData['rightfield_left']}`";
  472. $sRootRight = "`$sRightTableAlias`.`{$aJoinData['rightfield_right']}`";
  473. switch($aJoinData['tree_operator'])
  474. {
  475. case TREE_OPERATOR_BELOW:
  476. $sJoinCond = "$sNodeLeft >= $sRootLeft AND $sNodeLeft <= $sRootRight";
  477. break;
  478. case TREE_OPERATOR_BELOW_STRICT:
  479. $sJoinCond = "$sNodeLeft > $sRootLeft AND $sNodeLeft < $sRootRight";
  480. break;
  481. case TREE_OPERATOR_NOT_BELOW: // Complementary of 'BELOW'
  482. $sJoinCond = "$sNodeLeft < $sRootLeft OR $sNodeLeft > $sRootRight";
  483. break;
  484. case TREE_OPERATOR_NOT_BELOW_STRICT: // Complementary of BELOW_STRICT
  485. $sJoinCond = "$sNodeLeft <= $sRootLeft OR $sNodeLeft >= $sRootRight";
  486. break;
  487. case TREE_OPERATOR_ABOVE:
  488. $sJoinCond = "$sNodeLeft <= $sRootLeft AND $sNodeRight >= $sRootRight";
  489. break;
  490. case TREE_OPERATOR_ABOVE_STRICT:
  491. $sJoinCond = "$sNodeLeft < $sRootLeft AND $sNodeRight > $sRootRight";
  492. break;
  493. case TREE_OPERATOR_NOT_ABOVE: // Complementary of 'ABOVE'
  494. $sJoinCond = "$sNodeLeft > $sRootLeft OR $sNodeRight < $sRootRight";
  495. break;
  496. case TREE_OPERATOR_NOT_ABOVE_STRICT: // Complementary of ABOVE_STRICT
  497. $sJoinCond = "$sNodeLeft >= $sRootLeft OR $sNodeRight <= $sRootRight";
  498. break;
  499. }
  500. $aFrom[$this->m_sTableAlias] = array("jointype"=>$aJoinData['jointype'], "tablename"=>$this->m_sTable, "joincondition"=>"$sJoinCond");
  501. break;
  502. }
  503. // Given the alias, modify the fields and conditions
  504. // before adding them into the current lists
  505. //
  506. foreach($this->m_aFields as $sAlias => $oExpression)
  507. {
  508. $aFields["`$sAlias`"] = $oExpression->Render();
  509. }
  510. if ($this->m_aGroupBy)
  511. {
  512. foreach($this->m_aGroupBy as $sAlias => $oExpression)
  513. {
  514. $aGroupBy["`$sAlias`"] = $oExpression->Render();
  515. }
  516. }
  517. if ($this->m_bToDelete)
  518. {
  519. $aDelTables[] = "`{$this->m_sTableAlias}`";
  520. }
  521. foreach($this->m_aValues as $sFieldName=>$value)
  522. {
  523. $aSetValues["`{$this->m_sTableAlias}`.`$sFieldName`"] = $value; // quoted further!
  524. }
  525. if (!is_null($this->m_oSelectedIdField))
  526. {
  527. $aSelectedIdFields[] = $this->m_oSelectedIdField->Render();
  528. }
  529. // loop on joins, to complete the list of tables/fields/conditions
  530. //
  531. $aTempFrom = array(); // temporary subset of 'from' specs, to be grouped in the final query
  532. foreach ($this->m_aJoinSelects as $aJoinData)
  533. {
  534. $oRightSelect = $aJoinData["select"];
  535. $sJoinTableAlias = $oRightSelect->privRenderSingleTable($aTempFrom, $aFields, $aGroupBy, $aDelTables, $aSetValues, $aSelectedIdFields, $this->m_sTableAlias, $aJoinData);
  536. }
  537. $aFrom[$this->m_sTableAlias]['subfrom'] = $aTempFrom;
  538. return $this->m_sTableAlias;
  539. }
  540. public function OptimizeJoins($aUsedTables = null)
  541. {
  542. if (is_null($aUsedTables))
  543. {
  544. // Top call: build the list of tables absolutely required to perform the query
  545. $aUsedTables = $this->CollectUsedTables();
  546. }
  547. $aToDiscard = array();
  548. foreach ($this->m_aJoinSelects as $i => $aJoinInfo)
  549. {
  550. $oSQLQuery = $aJoinInfo["select"];
  551. $sTableAlias = $oSQLQuery->GetTableAlias();
  552. if ($oSQLQuery->OptimizeJoins($aUsedTables) && !array_key_exists($sTableAlias, $aUsedTables))
  553. {
  554. $aToDiscard[] = $i;
  555. }
  556. }
  557. foreach ($aToDiscard as $i)
  558. {
  559. unset($this->m_aJoinSelects[$i]);
  560. }
  561. return (count($this->m_aJoinSelects) == 0);
  562. }
  563. protected function CollectUsedTables(&$aTables = null)
  564. {
  565. if (is_null($aTables))
  566. {
  567. $aTables = array();
  568. $this->m_oConditionExpr->CollectUsedParents($aTables);
  569. foreach($this->m_aFields as $sFieldAlias => $oField)
  570. {
  571. $oField->CollectUsedParents($aTables);
  572. }
  573. if ($this->m_aGroupBy)
  574. {
  575. foreach($this->m_aGroupBy as $sAlias => $oExpression)
  576. {
  577. $oExpression->CollectUsedParents($aTables);
  578. }
  579. }
  580. if (!is_null($this->m_oSelectedIdField))
  581. {
  582. $this->m_oSelectedIdField->CollectUsedParents($aTables);
  583. }
  584. }
  585. foreach ($this->m_aJoinSelects as $i => $aJoinInfo)
  586. {
  587. $oSQLQuery = $aJoinInfo["select"];
  588. if ($oSQLQuery->HasRequiredTables($aTables))
  589. {
  590. // There is something required in the branch, then this node is a MUST
  591. if (isset($aJoinInfo['righttablealias']))
  592. {
  593. $aTables[$aJoinInfo['righttablealias']] = true;
  594. }
  595. if (isset($aJoinInfo["on_expression"]))
  596. {
  597. $sJoinCond = $aJoinInfo["on_expression"]->CollectUsedParents($aTables);
  598. }
  599. }
  600. }
  601. return $aTables;
  602. }
  603. // Is required in the JOIN, and therefore we must ensure that the join expression will be valid
  604. protected function HasRequiredTables($aTables)
  605. {
  606. if (array_key_exists($this->m_sTableAlias, $aTables))
  607. {
  608. return true;
  609. }
  610. foreach ($this->m_aJoinSelects as $i => $aJoinInfo)
  611. {
  612. $oSQLQuery = $aJoinInfo["select"];
  613. if ($oSQLQuery->HasRequiredTables($aTables))
  614. {
  615. return true;
  616. }
  617. }
  618. // None of the tables is in the list of required tables
  619. return false;
  620. }
  621. }
  622. ?>