sqlquery.class.inc.php 14 KB

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