sqlquery.class.inc.php 14 KB

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