sqlquery.class.inc.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482
  1. <?php
  2. // Copyright (C) 2010 Combodo SARL
  3. //
  4. // This program is free software; you can redistribute it and/or modify
  5. // it under the terms of the GNU General Public License as published by
  6. // the Free Software Foundation; version 3 of the License.
  7. //
  8. // This program is distributed in the hope that it will be useful,
  9. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. // GNU General Public License for more details.
  12. //
  13. // You should have received a copy of the GNU General Public License
  14. // along with this program; if not, write to the Free Software
  15. // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
  16. /**
  17. * SQLQuery
  18. * build an mySQL compatible SQL query
  19. *
  20. * @author Erwan Taloc <erwan.taloc@combodo.com>
  21. * @author Romain Quetiez <romain.quetiez@combodo.com>
  22. * @author Denis Flaven <denis.flaven@combodo.com>
  23. * @license http://www.opensource.org/licenses/gpl-3.0.html LGPL
  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_oConditionExpr = null;
  39. private $m_aFullTextNeedles = array();
  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. public function __construct($sTable, $sTableAlias, $aFields, $aFullTextNeedles = array(), $bToDelete = true, $aValues = array(), $oSelectedIdField = null)
  45. {
  46. // This check is not needed but for developping purposes
  47. //if (!CMDBSource::IsTable($sTable))
  48. //{
  49. // throw new CoreException("Unknown table '$sTable'");
  50. //}
  51. // $aFields must be an array of "alias"=>"expr"
  52. // $oConditionExpr must be a condition tree
  53. // $aValues is an array of "alias"=>value
  54. $this->m_sTable = $sTable;
  55. $this->m_sTableAlias = $sTableAlias;
  56. $this->m_aFields = $aFields;
  57. $this->m_oConditionExpr = null;
  58. $this->m_aFullTextNeedles = $aFullTextNeedles;
  59. $this->m_bToDelete = $bToDelete;
  60. $this->m_aValues = $aValues;
  61. $this->m_oSelectedIdField = $oSelectedIdField;
  62. }
  63. public function SetSourceOQL($sOQL)
  64. {
  65. $this->m_SourceOQL = $sOQL;
  66. }
  67. public function GetSourceOQL()
  68. {
  69. return $this->m_SourceOQL;
  70. }
  71. public function DisplayHtml()
  72. {
  73. if (count($this->m_aFields) == 0) $sFields = "";
  74. else
  75. {
  76. $aFieldDesc = array();
  77. foreach ($this->m_aFields as $sAlias => $oExpression)
  78. {
  79. $aFieldDesc[] = $oExpression->Render()." as <em>$sAlias</em>";
  80. }
  81. $sFields = " =&gt; ".implode(', ', $aFieldDesc);
  82. }
  83. echo "<b>$this->m_sTable</b>$sFields<br/>\n";
  84. // #@# todo - display html of an expression tree
  85. //$this->m_oConditionExpr->DisplayHtml()
  86. if (count($this->m_aFullTextNeedles) > 0)
  87. {
  88. echo "Full text criteria...<br/>\n";
  89. echo "<ul class=\"treeview\">\n";
  90. foreach ($this->m_aFullTextNeedles as $sFTNeedle)
  91. {
  92. echo "<li>$sFTNeedle</li>\n";
  93. }
  94. echo "</ul>";
  95. }
  96. if (count($this->m_aJoinSelects) > 0)
  97. {
  98. echo "Joined to...<br/>\n";
  99. echo "<ul class=\"treeview\">\n";
  100. foreach ($this->m_aJoinSelects as $aJoinInfo)
  101. {
  102. $sJoinType = $aJoinInfo["jointype"];
  103. $oSQLQuery = $aJoinInfo["select"];
  104. $sLeftField = $aJoinInfo["leftfield"];
  105. $sRightField = $aJoinInfo["rightfield"];
  106. $sRightTableAlias = $aJoinInfo["righttablealias"];
  107. echo "<li>Join '$sJoinType', $sLeftField, $sRightTableAlias.$sRightField".$oSQLQuery->DisplayHtml()."</li>\n";
  108. }
  109. echo "</ul>";
  110. }
  111. $aFrom = array();
  112. $aFields = array();
  113. $oCondition = null;
  114. $aDelTables = array();
  115. $aSetValues = array();
  116. $aSelectedIdFields = array();
  117. $this->privRender($aFrom, $aFields, $oCondition, $aDelTables, $aSetValues, $aSelectedIdFields);
  118. echo "From ...<br/>\n";
  119. echo "<pre style=\"font-size: smaller;\">\n";
  120. print_r($aFrom);
  121. echo "</pre>";
  122. }
  123. public function SetSelect($aExpressions)
  124. {
  125. $this->m_aFields = $aExpressions;
  126. }
  127. public function SetCondition($oConditionExpr)
  128. {
  129. $this->m_oConditionExpr = $oConditionExpr;
  130. }
  131. public function AddCondition($oConditionExpr)
  132. {
  133. if (is_null($this->m_oConditionExpr))
  134. {
  135. $this->m_oConditionExpr = $oConditionExpr;
  136. }
  137. else
  138. {
  139. $this->m_oConditionExpr->LogAnd($oConditionExpr);
  140. }
  141. }
  142. private function AddJoin($sJoinType, $oSQLQuery, $sLeftField, $sRightField, $sRightTableAlias = '')
  143. {
  144. assert((get_class($oSQLQuery) == __CLASS__) || is_subclass_of($oSQLQuery, __CLASS__));
  145. // No need to check this here but for development purposes
  146. //if (!CMDBSource::IsField($this->m_sTable, $sLeftField))
  147. //{
  148. // throw new CoreException("Unknown field '$sLeftField' in table '".$this->m_sTable);
  149. //}
  150. if (empty($sRightTableAlias))
  151. {
  152. $sRightTableAlias = $oSQLQuery->m_sTableAlias;
  153. }
  154. // #@# Could not be verified here because the namespace is unknown - do we need to check it there?
  155. //
  156. // if (!CMDBSource::IsField($sRightTable, $sRightField))
  157. // {
  158. // throw new CoreException("Unknown field '$sRightField' in table '".$sRightTable."'");
  159. // }
  160. $this->m_aJoinSelects[] = array(
  161. "jointype" => $sJoinType,
  162. "select" => $oSQLQuery,
  163. "leftfield" => $sLeftField,
  164. "rightfield" => $sRightField,
  165. "righttablealias" => $sRightTableAlias
  166. );
  167. }
  168. public function AddInnerJoin($oSQLQuery, $sLeftField, $sRightField, $sRigthtTable = '')
  169. {
  170. $this->AddJoin("inner", $oSQLQuery, $sLeftField, $sRightField, $sRigthtTable);
  171. }
  172. public function AddLeftJoin($oSQLQuery, $sLeftField, $sRightField)
  173. {
  174. return $this->AddJoin("left", $oSQLQuery, $sLeftField, $sRightField);
  175. }
  176. // Interface, build the SQL query
  177. public function RenderDelete($aArgs = array())
  178. {
  179. // The goal will be to complete the list as we build the Joins
  180. $aFrom = array();
  181. $aFields = array();
  182. $oCondition = null;
  183. $aDelTables = array();
  184. $aSetValues = array();
  185. $aSelectedIdFields = array();
  186. $this->privRender($aFrom, $aFields, $oCondition, $aDelTables, $aSetValues, $aSelectedIdFields);
  187. // Target: DELETE myAlias1, myAlias2 FROM t1 as myAlias1, t2 as myAlias2, t3 as topreserve WHERE ...
  188. $sDelete = self::ClauseDelete($aDelTables);
  189. $sFrom = self::ClauseFrom($aFrom);
  190. // #@# safety net to redo ?
  191. /*
  192. if ($this->m_oConditionExpr->IsAny())
  193. -- if (count($aConditions) == 0) --
  194. {
  195. throw new CoreException("Building a request wich will delete every object of a given table -looks suspicious- please use truncate instead...");
  196. }
  197. */
  198. if (is_null($oCondition))
  199. {
  200. // Delete all !!!
  201. }
  202. else
  203. {
  204. $sWhere = self::ClauseWhere($oCondition, $aArgs);
  205. return "DELETE $sDelete FROM $sFrom WHERE $sWhere";
  206. }
  207. }
  208. // Interface, build the SQL query
  209. public function RenderUpdate($aArgs = array())
  210. {
  211. // The goal will be to complete the list as we build the Joins
  212. $aFrom = array();
  213. $aFields = array();
  214. $oCondition = null;
  215. $aDelTables = array();
  216. $aSetValues = array();
  217. $aSelectedIdFields = array();
  218. $this->privRender($aFrom, $aFields, $oCondition, $aDelTables, $aSetValues, $aSelectedIdFields);
  219. $sFrom = self::ClauseFrom($aFrom);
  220. $sValues = self::ClauseValues($aSetValues);
  221. $sWhere = self::ClauseWhere($oCondition, $aArgs);
  222. return "UPDATE $sFrom SET $sValues WHERE $sWhere";
  223. }
  224. // Interface, build the SQL query
  225. public function RenderSelect($aOrderBy = array(), $aArgs = array(), $iLimitCount = 0, $iLimitStart = 0, $bGetCount = false)
  226. {
  227. // The goal will be to complete the lists as we build the Joins
  228. $aFrom = array();
  229. $aFields = array();
  230. $oCondition = null;
  231. $aDelTables = array();
  232. $aSetValues = array();
  233. $aSelectedIdFields = array();
  234. $this->privRender($aFrom, $aFields, $oCondition, $aDelTables, $aSetValues, $aSelectedIdFields);
  235. $sFrom = self::ClauseFrom($aFrom);
  236. $sWhere = self::ClauseWhere($oCondition, $aArgs);
  237. if ($bGetCount)
  238. {
  239. if (count($aSelectedIdFields) > 0)
  240. {
  241. $sIDFields = implode(', ', $aSelectedIdFields);
  242. $sSQL = "SELECT COUNT(DISTINCT $sIDFields) AS COUNT FROM $sFrom WHERE $sWhere";
  243. }
  244. else
  245. {
  246. $sSQL = "SELECT COUNT(*) AS COUNT FROM $sFrom WHERE $sWhere";
  247. }
  248. }
  249. else
  250. {
  251. $sSelect = self::ClauseSelect($aFields);
  252. $sOrderBy = self::ClauseOrderBy($aOrderBy);
  253. if (!empty($sOrderBy))
  254. {
  255. $sOrderBy = "ORDER BY $sOrderBy";
  256. }
  257. if ($iLimitCount > 0)
  258. {
  259. $sLimit = 'LIMIT '.$iLimitStart.', '.$iLimitCount;
  260. }
  261. else
  262. {
  263. $sLimit = '';
  264. }
  265. $sSQL = "SELECT DISTINCT $sSelect FROM $sFrom WHERE $sWhere $sOrderBy $sLimit";
  266. }
  267. return $sSQL;
  268. }
  269. private static function ClauseSelect($aFields)
  270. {
  271. $aSelect = array();
  272. foreach ($aFields as $sFieldAlias => $sSQLExpr)
  273. {
  274. $aSelect[] = "$sSQLExpr AS $sFieldAlias";
  275. }
  276. $sSelect = implode(', ', $aSelect);
  277. return $sSelect;
  278. }
  279. private static function ClauseDelete($aDelTableAliases)
  280. {
  281. $aDelTables = array();
  282. foreach ($aDelTableAliases as $sTableAlias)
  283. {
  284. $aDelTables[] = "$sTableAlias";
  285. }
  286. $sDelTables = implode(', ', $aDelTables);
  287. return $sDelTables;
  288. }
  289. private static function ClauseFrom($aFrom)
  290. {
  291. $sFrom = "";
  292. foreach ($aFrom as $sTableAlias => $aJoinInfo)
  293. {
  294. switch ($aJoinInfo["jointype"])
  295. {
  296. case "first":
  297. $sFrom .= "`".$aJoinInfo["tablename"]."` AS `$sTableAlias`";
  298. $sFrom .= " ".self::ClauseFrom($aJoinInfo["subfrom"]);
  299. break;
  300. case "inner":
  301. $sFrom .= " INNER JOIN (`".$aJoinInfo["tablename"]."` AS `$sTableAlias`";
  302. $sFrom .= " ".self::ClauseFrom($aJoinInfo["subfrom"]);
  303. $sFrom .= ") ON ".$aJoinInfo["joincondition"];
  304. break;
  305. case "left":
  306. $sFrom .= " LEFT JOIN (`".$aJoinInfo["tablename"]."` AS `$sTableAlias`";
  307. $sFrom .= " ".self::ClauseFrom($aJoinInfo["subfrom"]);
  308. $sFrom .= ") ON ".$aJoinInfo["joincondition"];
  309. break;
  310. default:
  311. throw new CoreException("Unknown jointype: '".$aJoinInfo["jointype"]."'");
  312. }
  313. }
  314. return $sFrom;
  315. }
  316. private static function ClauseValues($aValues)
  317. {
  318. $aSetValues = array();
  319. foreach ($aValues as $sFieldSpec => $value)
  320. {
  321. $aSetValues[] = "$sFieldSpec = ".CMDBSource::Quote($value);
  322. }
  323. $sSetValues = implode(', ', $aSetValues);
  324. return $sSetValues;
  325. }
  326. private static function ClauseWhere($oConditionExpr, $aArgs = array())
  327. {
  328. if (is_null($oConditionExpr))
  329. {
  330. return '1';
  331. }
  332. else
  333. {
  334. return $oConditionExpr->Render($aArgs);
  335. }
  336. }
  337. private static function ClauseOrderBy($aOrderBy)
  338. {
  339. $aOrderBySpec = array();
  340. foreach($aOrderBy as $sFieldAlias => $bAscending)
  341. {
  342. $aOrderBySpec[] = '`'.$sFieldAlias.'`'.($bAscending ? " ASC" : " DESC");
  343. }
  344. $sOrderBy = implode(", ", $aOrderBySpec);
  345. return $sOrderBy;
  346. }
  347. // Purpose: prepare the query data, once for all
  348. private function privRender(&$aFrom, &$aFields, &$oCondition, &$aDelTables, &$aSetValues, &$aSelectedIdFields)
  349. {
  350. $sTableAlias = $this->privRenderSingleTable($aFrom, $aFields, $aDelTables, $aSetValues, $aSelectedIdFields);
  351. // Add the full text search condition, based on each and every requested field
  352. //
  353. // To be updated with a real full text search based on the mySQL settings
  354. // (then it might move somewhere else !)
  355. //
  356. $oCondition = $this->m_oConditionExpr;
  357. if ((count($aFields) > 0) && (count($this->m_aFullTextNeedles) > 0))
  358. {
  359. $sFields = implode(', ', $aFields);
  360. $oFullTextExpr = Expression::FromSQL("CONCAT_WS(' ', $sFields)");
  361. // The cast is necessary because the CONCAT result in a binary string:
  362. // if any of the field is a binary string => case sensitive comparison
  363. //
  364. foreach($this->m_aFullTextNeedles as $sFTNeedle)
  365. {
  366. $oNewCond = new BinaryExpression($oFullTextExpr, 'LIKE', new ScalarExpression("%$sFTNeedle%"));
  367. if (is_null($oCondition))
  368. {
  369. $oCondition = $oNewCond;
  370. }
  371. else
  372. {
  373. $oCondition = $oCondition->LogAnd($oNewCond);
  374. }
  375. }
  376. }
  377. return $sTableAlias;
  378. }
  379. private function privRenderSingleTable(&$aFrom, &$aFields, &$aDelTables, &$aSetValues, &$aSelectedIdFields, $sJoinType = 'first', $sCallerAlias = '', $sLeftField = '', $sRightField = '', $sRightTableAlias = '')
  380. {
  381. $aActualTableFields = CMDBSource::GetTableFieldsList($this->m_sTable);
  382. $aTranslationTable[$this->m_sTable]['*'] = $this->m_sTableAlias;
  383. // Handle the various kinds of join (or first table in the list)
  384. //
  385. if (empty($sRightTableAlias))
  386. {
  387. $sRightTableAlias = $this->m_sTableAlias;
  388. }
  389. $sJoinCond = "`$sCallerAlias`.`$sLeftField` = `$sRightTableAlias`.`$sRightField`";
  390. switch ($sJoinType)
  391. {
  392. case "first":
  393. $aFrom[$this->m_sTableAlias] = array("jointype"=>"first", "tablename"=>$this->m_sTable, "joincondition"=>"");
  394. break;
  395. case "inner":
  396. case "left":
  397. // table or tablealias ???
  398. $aFrom[$this->m_sTableAlias] = array("jointype"=>$sJoinType, "tablename"=>$this->m_sTable, "joincondition"=>"$sJoinCond");
  399. break;
  400. }
  401. // Given the alias, modify the fields and conditions
  402. // before adding them into the current lists
  403. //
  404. foreach($this->m_aFields as $sAlias => $oExpression)
  405. {
  406. $aFields["`$sAlias`"] = $oExpression->Render();
  407. }
  408. if ($this->m_bToDelete)
  409. {
  410. $aDelTables[] = "`{$this->m_sTableAlias}`";
  411. }
  412. foreach($this->m_aValues as $sFieldName=>$value)
  413. {
  414. $aSetValues["`{$this->m_sTableAlias}`.`$sFieldName`"] = $value; // quoted further!
  415. }
  416. if (!is_null($this->m_oSelectedIdField))
  417. {
  418. $aSelectedIdFields[] = $this->m_oSelectedIdField->Render();
  419. }
  420. // loop on joins, to complete the list of tables/fields/conditions
  421. //
  422. $aTempFrom = array(); // temporary subset of 'from' specs, to be grouped in the final query
  423. foreach ($this->m_aJoinSelects as $aJoinData)
  424. {
  425. $sJoinType = $aJoinData["jointype"];
  426. $oRightSelect = $aJoinData["select"];
  427. $sLeftField = $aJoinData["leftfield"];
  428. $sRightField = $aJoinData["rightfield"];
  429. $sRightTableAlias = $aJoinData["righttablealias"];
  430. $sJoinTableAlias = $oRightSelect->privRenderSingleTable($aTempFrom, $aFields, $aDelTables, $aSetValues, $aSelectedIdFields, $sJoinType, $this->m_sTableAlias, $sLeftField, $sRightField, $sRightTableAlias);
  431. }
  432. $aFrom[$this->m_sTableAlias]['subfrom'] = $aTempFrom;
  433. return $this->m_sTableAlias;
  434. }
  435. }
  436. ?>