sqlquery.class.inc.php 13 KB

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