sqlquery.class.inc.php 21 KB

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