PageRenderTime 35ms CodeModel.GetById 16ms RepoModel.GetById 1ms app.codeStats 0ms

/lib/Doctrine/RawSql.php

https://github.com/xdade/doctrine1
PHP | 454 lines | 247 code | 65 blank | 142 comment | 39 complexity | fd146a417d69ff55540b1b513a3a745c MD5 | raw file
  1. <?php
  2. /*
  3. * $Id: RawSql.php 7490 2010-03-29 19:53:27Z jwage $
  4. *
  5. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  6. * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  7. * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  8. * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  9. * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  10. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  11. * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  12. * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  13. * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  14. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  15. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  16. *
  17. * This software consists of voluntary contributions made by many individuals
  18. * and is licensed under the LGPL. For more information, see
  19. * <http://www.doctrine-project.org>.
  20. */
  21. /**
  22. * Doctrine_RawSql
  23. *
  24. * Doctrine_RawSql is an implementation of Doctrine_Query_Abstract that skips the entire
  25. * DQL parsing procedure. The "DQL" that is passed to a RawSql query object for execution
  26. * is considered to be plain SQL and will be used "as is". The only query part that is special
  27. * in a RawSql query is the SELECT part, which has a special syntax that provides Doctrine
  28. * with the necessary information to properly hydrate the query results.
  29. *
  30. * @package Doctrine
  31. * @subpackage RawSql
  32. * @license http://www.opensource.org/licenses/lgpl-license.php LGPL
  33. * @link www.doctrine-project.org
  34. * @since 1.0
  35. * @version $Revision: 7490 $
  36. * @author Konsta Vesterinen <kvesteri@cc.hut.fi>
  37. */
  38. class Doctrine_RawSql extends Doctrine_Query_Abstract
  39. {
  40. /**
  41. * @var array $fields
  42. */
  43. private $fields = array();
  44. /**
  45. * Constructor.
  46. *
  47. * @param Doctrine_Connection The connection object the query will use.
  48. * @param Doctrine_Hydrator_Abstract The hydrator that will be used for generating result sets.
  49. */
  50. function __construct(Doctrine_Connection $connection = null, Doctrine_Hydrator_Abstract $hydrator = null) {
  51. parent::__construct($connection, $hydrator);
  52. // Fix #1472. It's alid to disable QueryCache since there's no DQL for RawSql.
  53. // RawSql expects to be plain SQL + syntax for SELECT part. It is used as is in query execution.
  54. $this->useQueryCache(false);
  55. }
  56. protected function clear()
  57. {
  58. $this->_preQuery = false;
  59. $this->_pendingJoinConditions = array();
  60. }
  61. /**
  62. * parseDqlQueryPart
  63. * parses given DQL query part. Overrides Doctrine_Query_Abstract::parseDqlQueryPart().
  64. * This implementation does no parsing at all, except of the SELECT portion of the query
  65. * which is special in RawSql queries. The entire remaining parts are used "as is", so
  66. * the user of the RawSql query is responsible for writing SQL that is portable between
  67. * different DBMS.
  68. *
  69. * @param string $queryPartName the name of the query part
  70. * @param string $queryPart query part to be parsed
  71. * @param boolean $append whether or not to append the query part to its stack
  72. * if false is given, this method will overwrite
  73. * the given query part stack with $queryPart
  74. * @return Doctrine_Query this object
  75. */
  76. public function parseDqlQueryPart($queryPartName, $queryPart, $append = false)
  77. {
  78. if ($queryPartName == 'select') {
  79. $this->_parseSelectFields($queryPart);
  80. return $this;
  81. }
  82. if ( ! isset($this->_sqlParts[$queryPartName])) {
  83. $this->_sqlParts[$queryPartName] = array();
  84. }
  85. if ( ! $append) {
  86. $this->_sqlParts[$queryPartName] = array($queryPart);
  87. } else {
  88. $this->_sqlParts[$queryPartName][] = $queryPart;
  89. }
  90. return $this;
  91. }
  92. /**
  93. * Adds a DQL query part. Overrides Doctrine_Query_Abstract::_addDqlQueryPart().
  94. * This implementation for RawSql parses the new parts right away, generating the SQL.
  95. */
  96. protected function _addDqlQueryPart($queryPartName, $queryPart, $append = false)
  97. {
  98. return $this->parseDqlQueryPart($queryPartName, $queryPart, $append);
  99. }
  100. /**
  101. * Add select parts to fields.
  102. *
  103. * @param $queryPart sting The name of the querypart
  104. */
  105. private function _parseSelectFields($queryPart)
  106. {
  107. preg_match_all('/{([^}{]*)}/U', $queryPart, $m);
  108. $this->fields = $m[1];
  109. $this->_sqlParts['select'] = array();
  110. }
  111. /**
  112. * parseDqlQuery
  113. * parses an sql query and adds the parts to internal array.
  114. * Overrides Doctrine_Query_Abstract::parseDqlQuery().
  115. * This implementation simply tokenizes the provided query string and uses them
  116. * as SQL parts right away.
  117. *
  118. * @param string $query query to be parsed
  119. * @return Doctrine_RawSql this object
  120. */
  121. public function parseDqlQuery($query)
  122. {
  123. $this->_parseSelectFields($query);
  124. $this->clear();
  125. $tokens = $this->_tokenizer->sqlExplode($query, ' ');
  126. $parts = array();
  127. foreach ($tokens as $key => $part) {
  128. $partLowerCase = strtolower($part);
  129. switch ($partLowerCase) {
  130. case 'select':
  131. case 'from':
  132. case 'where':
  133. case 'limit':
  134. case 'offset':
  135. case 'having':
  136. $type = $partLowerCase;
  137. if ( ! isset($parts[$partLowerCase])) {
  138. $parts[$partLowerCase] = array();
  139. }
  140. break;
  141. case 'order':
  142. case 'group':
  143. $i = $key + 1;
  144. if (isset($tokens[$i]) && strtolower($tokens[$i]) === 'by') {
  145. $type = $partLowerCase . 'by';
  146. $parts[$type] = array();
  147. } else {
  148. //not a keyword so we add it to the previous type
  149. $parts[$type][] = $part;
  150. }
  151. break;
  152. case 'by':
  153. continue;
  154. default:
  155. //not a keyword so we add it to the previous type.
  156. if ( ! isset($parts[$type][0])) {
  157. $parts[$type][0] = $part;
  158. } else {
  159. // why does this add to index 0 and not append to the
  160. // array. If it had done that one could have used
  161. // parseQueryPart.
  162. $parts[$type][0] .= ' '.$part;
  163. }
  164. }
  165. }
  166. $this->_sqlParts = $parts;
  167. $this->_sqlParts['select'] = array();
  168. return $this;
  169. }
  170. /**
  171. * getSqlQuery
  172. * builds the sql query.
  173. *
  174. * @return string the built sql query
  175. */
  176. public function getSqlQuery($params = array())
  177. {
  178. // Assign building/execution specific params
  179. $this->_params['exec'] = $params;
  180. // Initialize prepared parameters array
  181. $this->_execParams = $this->getFlattenedParams();
  182. // Initialize prepared parameters array
  183. $this->fixArrayParameterValues($this->_execParams);
  184. $select = array();
  185. $formatter = $this->getConnection()->formatter;
  186. foreach ($this->fields as $field) {
  187. $e = explode('.', $field);
  188. if ( ! isset($e[1])) {
  189. throw new Doctrine_RawSql_Exception('All selected fields in Sql query must be in format tableAlias.fieldName');
  190. }
  191. // try to auto-add component
  192. if ( ! $this->hasSqlTableAlias($e[0])) {
  193. try {
  194. $this->addComponent($e[0], ucwords($e[0]));
  195. } catch (Doctrine_Exception $exception) {
  196. throw new Doctrine_RawSql_Exception('The associated component for table alias ' . $e[0] . ' couldn\'t be found.');
  197. }
  198. }
  199. $componentAlias = $this->getComponentAlias($e[0]);
  200. if ($e[1] == '*') {
  201. foreach ($this->_queryComponents[$componentAlias]['table']->getColumnNames() as $name) {
  202. $field = $formatter->quoteIdentifier($e[0]) . '.' . $formatter->quoteIdentifier($name);
  203. $select[$componentAlias][$field] = $field . ' AS ' . $formatter->quoteIdentifier($e[0] . '__' . $name);
  204. }
  205. } else {
  206. $field = $formatter->quoteIdentifier($e[0]) . '.' . $formatter->quoteIdentifier($e[1]);
  207. $select[$componentAlias][$field] = $field . ' AS ' . $formatter->quoteIdentifier($e[0] . '__' . $e[1]);
  208. }
  209. }
  210. // force-add all primary key fields
  211. if ( ! isset($this->_sqlParts['distinct']) || $this->_sqlParts['distinct'] != true) {
  212. foreach ($this->getTableAliasMap() as $tableAlias => $componentAlias) {
  213. $map = $this->_queryComponents[$componentAlias];
  214. foreach ((array) $map['table']->getIdentifierColumnNames() as $key) {
  215. $field = $formatter->quoteIdentifier($tableAlias) . '.' . $formatter->quoteIdentifier($key);
  216. if ( ! isset($this->_sqlParts['select'][$field])) {
  217. $select[$componentAlias][$field] = $field . ' AS ' . $formatter->quoteIdentifier($tableAlias . '__' . $key);
  218. }
  219. }
  220. }
  221. }
  222. $q = 'SELECT ';
  223. if (isset($this->_sqlParts['distinct']) && $this->_sqlParts['distinct'] == true) {
  224. $q .= 'DISTINCT ';
  225. }
  226. // first add the fields of the root component
  227. reset($this->_queryComponents);
  228. $componentAlias = key($this->_queryComponents);
  229. $this->_rootAlias = $componentAlias;
  230. $q .= implode(', ', $select[$componentAlias]);
  231. unset($select[$componentAlias]);
  232. foreach ($select as $component => $fields) {
  233. if ( ! empty($fields)) {
  234. $q .= ', ' . implode(', ', $fields);
  235. }
  236. }
  237. $string = $this->getInheritanceCondition($this->getRootAlias());
  238. if ( ! empty($string)) {
  239. $this->_sqlParts['where'][] = $string;
  240. }
  241. $q .= ( ! empty($this->_sqlParts['from']))? ' FROM ' . implode(' ', $this->_sqlParts['from']) : '';
  242. $q .= ( ! empty($this->_sqlParts['where']))? ' WHERE ' . implode(' AND ', $this->_sqlParts['where']) : '';
  243. $q .= ( ! empty($this->_sqlParts['groupby']))? ' GROUP BY ' . implode(', ', $this->_sqlParts['groupby']) : '';
  244. $q .= ( ! empty($this->_sqlParts['having']))? ' HAVING ' . implode(' AND ', $this->_sqlParts['having']) : '';
  245. $q .= ( ! empty($this->_sqlParts['orderby']))? ' ORDER BY ' . implode(', ', $this->_sqlParts['orderby']) : '';
  246. $q .= ( ! empty($this->_sqlParts['limit']))? ' LIMIT ' . implode(' ', $this->_sqlParts['limit']) : '';
  247. $q .= ( ! empty($this->_sqlParts['offset']))? ' OFFSET ' . implode(' ', $this->_sqlParts['offset']) : '';
  248. if ( ! empty($string)) {
  249. array_pop($this->_sqlParts['where']);
  250. }
  251. return $q;
  252. }
  253. /**
  254. * getCountQuery
  255. * builds the count query.
  256. *
  257. * @return string the built sql query
  258. */
  259. public function getCountSqlQuery($params = array())
  260. {
  261. //Doing COUNT( DISTINCT rootComponent.id )
  262. //This is not correct, if the result is not hydrated by doctrine, but it mimics the behaviour of Doctrine_Query::getCountQuery
  263. reset($this->_queryComponents);
  264. $componentAlias = key($this->_queryComponents);
  265. $this->_rootAlias = $componentAlias;
  266. $tableAlias = $this->getSqlTableAlias($componentAlias);
  267. $fields = array();
  268. foreach ((array) $this->_queryComponents[$componentAlias]['table']->getIdentifierColumnNames() as $key) {
  269. $fields[] = $tableAlias . '.' . $key;
  270. }
  271. $q = 'SELECT COUNT(*) as num_results FROM (SELECT DISTINCT '.implode(', ',$fields);
  272. $string = $this->getInheritanceCondition($this->getRootAlias());
  273. if ( ! empty($string)) {
  274. $this->_sqlParts['where'][] = $string;
  275. }
  276. $q .= ( ! empty($this->_sqlParts['from']))? ' FROM ' . implode(' ', $this->_sqlParts['from']) : '';
  277. $q .= ( ! empty($this->_sqlParts['where']))? ' WHERE ' . implode(' AND ', $this->_sqlParts['where']) : '';
  278. $q .= ( ! empty($this->_sqlParts['groupby']))? ' GROUP BY ' . implode(', ', $this->_sqlParts['groupby']) : '';
  279. $q .= ( ! empty($this->_sqlParts['having']))? ' HAVING ' . implode(' AND ', $this->_sqlParts['having']) : '';
  280. $q .= ') as results';
  281. if ( ! empty($string)) {
  282. array_pop($this->_sqlParts['where']);
  283. }
  284. return $q;
  285. }
  286. /**
  287. * count
  288. * fetches the count of the query
  289. *
  290. * This method executes the main query without all the
  291. * selected fields, ORDER BY part, LIMIT part and OFFSET part.
  292. *
  293. * This is an exact copy of the Dql Version
  294. *
  295. * @see Doctrine_Query::count()
  296. * @param array $params an array of prepared statement parameters
  297. * @return integer the count of this query
  298. */
  299. public function count($params = array())
  300. {
  301. $sql = $this->getCountSqlQuery();
  302. $params = $this->getCountQueryParams($params);
  303. $results = $this->getConnection()->fetchAll($sql, $params);
  304. if (count($results) > 1) {
  305. $count = count($results);
  306. } else {
  307. if (isset($results[0])) {
  308. $results[0] = array_change_key_case($results[0], CASE_LOWER);
  309. $count = $results[0]['num_results'];
  310. } else {
  311. $count = 0;
  312. }
  313. }
  314. return (int) $count;
  315. }
  316. /**
  317. * getFields
  318. * returns the fields associated with this parser
  319. *
  320. * @return array all the fields associated with this parser
  321. */
  322. public function getFields()
  323. {
  324. return $this->fields;
  325. }
  326. /**
  327. * addComponent
  328. *
  329. * @param string $tableAlias
  330. * @param string $componentName
  331. * @return Doctrine_RawSql
  332. */
  333. public function addComponent($tableAlias, $path)
  334. {
  335. $tmp = explode(' ', $path);
  336. $originalAlias = (count($tmp) > 1) ? end($tmp) : null;
  337. $e = explode('.', $tmp[0]);
  338. $fullPath = $tmp[0];
  339. $fullLength = strlen($fullPath);
  340. $table = null;
  341. $currPath = '';
  342. if (isset($this->_queryComponents[$e[0]])) {
  343. $table = $this->_queryComponents[$e[0]]['table'];
  344. $currPath = $parent = array_shift($e);
  345. }
  346. foreach ($e as $k => $component) {
  347. // get length of the previous path
  348. $length = strlen($currPath);
  349. // build the current component path
  350. $currPath = ($currPath) ? $currPath . '.' . $component : $component;
  351. $delimeter = substr($fullPath, $length, 1);
  352. // if an alias is not given use the current path as an alias identifier
  353. if (strlen($currPath) === $fullLength && isset($originalAlias)) {
  354. $componentAlias = $originalAlias;
  355. } else {
  356. $componentAlias = $currPath;
  357. }
  358. if ( ! isset($table)) {
  359. $conn = Doctrine_Manager::getInstance()
  360. ->getConnectionForComponent($component);
  361. $table = $conn->getTable($component);
  362. $this->_queryComponents[$componentAlias] = array('table' => $table);
  363. } else {
  364. $relation = $table->getRelation($component);
  365. $this->_queryComponents[$componentAlias] = array('table' => $relation->getTable(),
  366. 'parent' => $parent,
  367. 'relation' => $relation);
  368. }
  369. $this->addSqlTableAlias($tableAlias, $componentAlias);
  370. $parent = $currPath;
  371. }
  372. return $this;
  373. }
  374. /**
  375. * calculateResultCacheHash
  376. * calculate hash key for result cache
  377. *
  378. * @param array $params
  379. * @return string the hash
  380. */
  381. public function calculateResultCacheHash($params = array())
  382. {
  383. $sql = $this->getSqlQuery();
  384. $conn = $this->getConnection();
  385. $params = $this->getFlattenedParams($params);
  386. $hash = md5($this->_hydrator->getHydrationMode() . $conn->getName() . $conn->getOption('dsn') . $sql . var_export($params, true));
  387. return $hash;
  388. }
  389. }