sqlquery.class.inc.php 13 KB

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