PageRenderTime 30ms CodeModel.GetById 1ms RepoModel.GetById 0ms app.codeStats 0ms

/bluebox/libraries/doctrine/lib/Doctrine/RawSql.php

https://github.com/robertleeplummerjr/bluebox
PHP | 450 lines | 245 code | 63 blank | 142 comment | 39 complexity | 3694301423130b9f9ef90fc89f5870ed MD5 | raw file
  1. <?php
  2. /*
  3. * $Id: RawSql.php 5901 2009-06-22 15:44:45Z 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.phpdoctrine.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.phpdoctrine.org
  34. * @since 1.0
  35. * @version $Revision: 5901 $
  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. foreach ($this->fields as $field) {
  186. $e = explode('.', $field);
  187. if ( ! isset($e[1])) {
  188. throw new Doctrine_RawSql_Exception('All selected fields in Sql query must be in format tableAlias.fieldName');
  189. }
  190. // try to auto-add component
  191. if ( ! $this->hasSqlTableAlias($e[0])) {
  192. try {
  193. $this->addComponent($e[0], ucwords($e[0]));
  194. } catch (Doctrine_Exception $exception) {
  195. throw new Doctrine_RawSql_Exception('The associated component for table alias ' . $e[0] . ' couldn\'t be found.');
  196. }
  197. }
  198. $componentAlias = $this->getComponentAlias($e[0]);
  199. if ($e[1] == '*') {
  200. foreach ($this->_queryComponents[$componentAlias]['table']->getColumnNames() as $name) {
  201. $field = $e[0] . '.' . $name;
  202. $select[$componentAlias][$field] = $field . ' AS ' . $e[0] . '__' . $name;
  203. }
  204. } else {
  205. $field = $e[0] . '.' . $e[1];
  206. $select[$componentAlias][$field] = $field . ' AS ' . $e[0] . '__' . $e[1];
  207. }
  208. }
  209. // force-add all primary key fields
  210. if ( ! isset($this->_sqlParts['distinct']) || $this->_sqlParts['distinct'] != true) {
  211. foreach ($this->getTableAliasMap() as $tableAlias => $componentAlias) {
  212. $map = $this->_queryComponents[$componentAlias];
  213. foreach ((array) $map['table']->getIdentifierColumnNames() as $key) {
  214. $field = $tableAlias . '.' . $key;
  215. if ( ! isset($this->_sqlParts['select'][$field])) {
  216. $select[$componentAlias][$field] = $field . ' AS ' . $tableAlias . '__' . $key;
  217. }
  218. }
  219. }
  220. }
  221. $q = 'SELECT ';
  222. if (isset($this->_sqlParts['distinct']) && $this->_sqlParts['distinct'] == true) {
  223. $q .= 'DISTINCT ';
  224. }
  225. // first add the fields of the root component
  226. reset($this->_queryComponents);
  227. $componentAlias = key($this->_queryComponents);
  228. $this->_rootAlias = $componentAlias;
  229. $q .= implode(', ', $select[$componentAlias]);
  230. unset($select[$componentAlias]);
  231. foreach ($select as $component => $fields) {
  232. if ( ! empty($fields)) {
  233. $q .= ', ' . implode(', ', $fields);
  234. }
  235. }
  236. $string = $this->getInheritanceCondition($this->getRootAlias());
  237. if ( ! empty($string)) {
  238. $this->_sqlParts['where'][] = $string;
  239. }
  240. $q .= ( ! empty($this->_sqlParts['from']))? ' FROM ' . implode(' ', $this->_sqlParts['from']) : '';
  241. $q .= ( ! empty($this->_sqlParts['where']))? ' WHERE ' . implode(' AND ', $this->_sqlParts['where']) : '';
  242. $q .= ( ! empty($this->_sqlParts['groupby']))? ' GROUP BY ' . implode(', ', $this->_sqlParts['groupby']) : '';
  243. $q .= ( ! empty($this->_sqlParts['having']))? ' HAVING ' . implode(' AND ', $this->_sqlParts['having']) : '';
  244. $q .= ( ! empty($this->_sqlParts['orderby']))? ' ORDER BY ' . implode(', ', $this->_sqlParts['orderby']) : '';
  245. $q .= ( ! empty($this->_sqlParts['limit']))? ' LIMIT ' . implode(' ', $this->_sqlParts['limit']) : '';
  246. $q .= ( ! empty($this->_sqlParts['offset']))? ' OFFSET ' . implode(' ', $this->_sqlParts['offset']) : '';
  247. if ( ! empty($string)) {
  248. array_pop($this->_sqlParts['where']);
  249. }
  250. return $q;
  251. }
  252. /**
  253. * getCountQuery
  254. * builds the count query.
  255. *
  256. * @return string the built sql query
  257. */
  258. public function getCountSqlQuery($params = array())
  259. {
  260. //Doing COUNT( DISTINCT rootComponent.id )
  261. //This is not correct, if the result is not hydrated by doctrine, but it mimics the behaviour of Doctrine_Query::getCountQuery
  262. reset($this->_queryComponents);
  263. $componentAlias = key($this->_queryComponents);
  264. $this->_rootAlias = $componentAlias;
  265. $tableAlias = $this->getSqlTableAlias($componentAlias);
  266. $fields = array();
  267. foreach ((array) $this->_queryComponents[$componentAlias]['table']->getIdentifierColumnNames() as $key) {
  268. $fields[] = $tableAlias . '.' . $key;
  269. }
  270. $q = 'SELECT COUNT( DISTINCT '.implode(',',$fields).') as num_results';
  271. $string = $this->getInheritanceCondition($this->getRootAlias());
  272. if ( ! empty($string)) {
  273. $this->_sqlParts['where'][] = $string;
  274. }
  275. $q .= ( ! empty($this->_sqlParts['from']))? ' FROM ' . implode(' ', $this->_sqlParts['from']) : '';
  276. $q .= ( ! empty($this->_sqlParts['where']))? ' WHERE ' . implode(' AND ', $this->_sqlParts['where']) : '';
  277. $q .= ( ! empty($this->_sqlParts['groupby']))? ' GROUP BY ' . implode(', ', $this->_sqlParts['groupby']) : '';
  278. $q .= ( ! empty($this->_sqlParts['having']))? ' HAVING ' . implode(' AND ', $this->_sqlParts['having']) : '';
  279. if ( ! empty($string)) {
  280. array_pop($this->_sqlParts['where']);
  281. }
  282. return $q;
  283. }
  284. /**
  285. * count
  286. * fetches the count of the query
  287. *
  288. * This method executes the main query without all the
  289. * selected fields, ORDER BY part, LIMIT part and OFFSET part.
  290. *
  291. * This is an exact copy of the Dql Version
  292. *
  293. * @see Doctrine_Query::count()
  294. * @param array $params an array of prepared statement parameters
  295. * @return integer the count of this query
  296. */
  297. public function count($params = array())
  298. {
  299. $sql = $this->getCountSqlQuery();
  300. $params = $this->getCountQueryParams($params);
  301. $results = $this->getConnection()->fetchAll($sql, $params);
  302. if (count($results) > 1) {
  303. $count = count($results);
  304. } else {
  305. if (isset($results[0])) {
  306. $results[0] = array_change_key_case($results[0], CASE_LOWER);
  307. $count = $results[0]['num_results'];
  308. } else {
  309. $count = 0;
  310. }
  311. }
  312. return (int) $count;
  313. }
  314. /**
  315. * getFields
  316. * returns the fields associated with this parser
  317. *
  318. * @return array all the fields associated with this parser
  319. */
  320. public function getFields()
  321. {
  322. return $this->fields;
  323. }
  324. /**
  325. * addComponent
  326. *
  327. * @param string $tableAlias
  328. * @param string $componentName
  329. * @return Doctrine_RawSql
  330. */
  331. public function addComponent($tableAlias, $path)
  332. {
  333. $tmp = explode(' ', $path);
  334. $originalAlias = (count($tmp) > 1) ? end($tmp) : null;
  335. $e = explode('.', $tmp[0]);
  336. $fullPath = $tmp[0];
  337. $fullLength = strlen($fullPath);
  338. $table = null;
  339. $currPath = '';
  340. if (isset($this->_queryComponents[$e[0]])) {
  341. $table = $this->_queryComponents[$e[0]]['table'];
  342. $currPath = $parent = array_shift($e);
  343. }
  344. foreach ($e as $k => $component) {
  345. // get length of the previous path
  346. $length = strlen($currPath);
  347. // build the current component path
  348. $currPath = ($currPath) ? $currPath . '.' . $component : $component;
  349. $delimeter = substr($fullPath, $length, 1);
  350. // if an alias is not given use the current path as an alias identifier
  351. if (strlen($currPath) === $fullLength && isset($originalAlias)) {
  352. $componentAlias = $originalAlias;
  353. } else {
  354. $componentAlias = $currPath;
  355. }
  356. if ( ! isset($table)) {
  357. $conn = Doctrine_Manager::getInstance()
  358. ->getConnectionForComponent($component);
  359. $table = $conn->getTable($component);
  360. $this->_queryComponents[$componentAlias] = array('table' => $table);
  361. } else {
  362. $relation = $table->getRelation($component);
  363. $this->_queryComponents[$componentAlias] = array('table' => $relation->getTable(),
  364. 'parent' => $parent,
  365. 'relation' => $relation);
  366. }
  367. $this->addSqlTableAlias($tableAlias, $componentAlias);
  368. $parent = $currPath;
  369. }
  370. return $this;
  371. }
  372. /**
  373. * calculateResultCacheHash
  374. * calculate hash key for result cache
  375. *
  376. * @param array $params
  377. * @return string the hash
  378. */
  379. public function calculateResultCacheHash($params = array())
  380. {
  381. $sql = $this->getSql();
  382. $conn = $this->getConnection();
  383. $params = $this->getFlattenedParams($params);
  384. $hash = md5($this->_hydrator->getHydrationMode() . $conn->getName() . $conn->getOption('dsn') . $sql . var_export($params, true));
  385. return $hash;
  386. }
  387. }