sqlquery.class.inc.php 14 KB

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