PageRenderTime 42ms CodeModel.GetById 9ms RepoModel.GetById 1ms app.codeStats 0ms

/system/application/plugins/doctrine/lib/Doctrine/RawSql.php

https://github.com/cawago/ci_campusync_auth
PHP | 457 lines | 248 code | 64 blank | 145 comment | 39 complexity | 65356a074f4c800c154b5f4a650b1551 MD5 | raw file
  1. <?php
  2. /*
  3. * $Id: RawSql.php 6369 2009-09-15 20:54:58Z kriswallsmith $
  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: 6369 $
  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. * @deprecated
  63. */
  64. public function parseQueryPart($queryPartName, $queryPart, $append = false)
  65. {
  66. return $this->parseDqlQueryPart($queryPartName, $queryPart, $append);
  67. }
  68. /**
  69. * parseDqlQueryPart
  70. * parses given DQL query part. Overrides Doctrine_Query_Abstract::parseDqlQueryPart().
  71. * This implementation does no parsing at all, except of the SELECT portion of the query
  72. * which is special in RawSql queries. The entire remaining parts are used "as is", so
  73. * the user of the RawSql query is responsible for writing SQL that is portable between
  74. * different DBMS.
  75. *
  76. * @param string $queryPartName the name of the query part
  77. * @param string $queryPart query part to be parsed
  78. * @param boolean $append whether or not to append the query part to its stack
  79. * if false is given, this method will overwrite
  80. * the given query part stack with $queryPart
  81. * @return Doctrine_Query this object
  82. */
  83. public function parseDqlQueryPart($queryPartName, $queryPart, $append = false)
  84. {
  85. if ($queryPartName == 'select') {
  86. $this->_parseSelectFields($queryPart);
  87. return $this;
  88. }
  89. if ( ! isset($this->_sqlParts[$queryPartName])) {
  90. $this->_sqlParts[$queryPartName] = array();
  91. }
  92. if ( ! $append) {
  93. $this->_sqlParts[$queryPartName] = array($queryPart);
  94. } else {
  95. $this->_sqlParts[$queryPartName][] = $queryPart;
  96. }
  97. return $this;
  98. }
  99. /**
  100. * Adds a DQL query part. Overrides Doctrine_Query_Abstract::_addDqlQueryPart().
  101. * This implementation for RawSql parses the new parts right away, generating the SQL.
  102. */
  103. protected function _addDqlQueryPart($queryPartName, $queryPart, $append = false)
  104. {
  105. return $this->parseQueryPart($queryPartName, $queryPart, $append);
  106. }
  107. /**
  108. * Add select parts to fields.
  109. *
  110. * @param $queryPart sting The name of the querypart
  111. */
  112. private function _parseSelectFields($queryPart){
  113. preg_match_all('/{([^}{]*)}/U', $queryPart, $m);
  114. $this->fields = $m[1];
  115. $this->_sqlParts['select'] = array();
  116. }
  117. /**
  118. * parseDqlQuery
  119. * parses an sql query and adds the parts to internal array.
  120. * Overrides Doctrine_Query_Abstract::parseDqlQuery().
  121. * This implementation simply tokenizes the provided query string and uses them
  122. * as SQL parts right away.
  123. *
  124. * @param string $query query to be parsed
  125. * @return Doctrine_RawSql this object
  126. */
  127. public function parseDqlQuery($query)
  128. {
  129. $this->_parseSelectFields($query);
  130. $this->clear();
  131. $tokens = $this->_tokenizer->sqlExplode($query, ' ');
  132. $parts = array();
  133. foreach ($tokens as $key => $part) {
  134. $partLowerCase = strtolower($part);
  135. switch ($partLowerCase) {
  136. case 'select':
  137. case 'from':
  138. case 'where':
  139. case 'limit':
  140. case 'offset':
  141. case 'having':
  142. $type = $partLowerCase;
  143. if ( ! isset($parts[$partLowerCase])) {
  144. $parts[$partLowerCase] = array();
  145. }
  146. break;
  147. case 'order':
  148. case 'group':
  149. $i = $key + 1;
  150. if (isset($tokens[$i]) && strtolower($tokens[$i]) === 'by') {
  151. $type = $partLowerCase . 'by';
  152. $parts[$type] = array();
  153. } else {
  154. //not a keyword so we add it to the previous type
  155. $parts[$type][] = $part;
  156. }
  157. break;
  158. case 'by':
  159. continue;
  160. default:
  161. //not a keyword so we add it to the previous type.
  162. if ( ! isset($parts[$type][0])) {
  163. $parts[$type][0] = $part;
  164. } else {
  165. // why does this add to index 0 and not append to the
  166. // array. If it had done that one could have used
  167. // parseQueryPart.
  168. $parts[$type][0] .= ' '.$part;
  169. }
  170. }
  171. }
  172. $this->_sqlParts = $parts;
  173. $this->_sqlParts['select'] = array();
  174. return $this;
  175. }
  176. /**
  177. * getSqlQuery
  178. * builds the sql query.
  179. *
  180. * @return string the built sql query
  181. */
  182. public function getSqlQuery($params = array())
  183. {
  184. // Assign building/execution specific params
  185. $this->_params['exec'] = $params;
  186. // Initialize prepared parameters array
  187. $this->_execParams = $this->getFlattenedParams();
  188. // Initialize prepared parameters array
  189. $this->fixArrayParameterValues($this->_execParams);
  190. $select = array();
  191. foreach ($this->fields as $field) {
  192. $e = explode('.', $field);
  193. if ( ! isset($e[1])) {
  194. throw new Doctrine_RawSql_Exception('All selected fields in Sql query must be in format tableAlias.fieldName');
  195. }
  196. // try to auto-add component
  197. if ( ! $this->hasSqlTableAlias($e[0])) {
  198. try {
  199. $this->addComponent($e[0], ucwords($e[0]));
  200. } catch (Doctrine_Exception $exception) {
  201. throw new Doctrine_RawSql_Exception('The associated component for table alias ' . $e[0] . ' couldn\'t be found.');
  202. }
  203. }
  204. $componentAlias = $this->getComponentAlias($e[0]);
  205. if ($e[1] == '*') {
  206. foreach ($this->_queryComponents[$componentAlias]['table']->getColumnNames() as $name) {
  207. $field = $e[0] . '.' . $name;
  208. $select[$componentAlias][$field] = $field . ' AS ' . $e[0] . '__' . $name;
  209. }
  210. } else {
  211. $field = $e[0] . '.' . $e[1];
  212. $select[$componentAlias][$field] = $field . ' AS ' . $e[0] . '__' . $e[1];
  213. }
  214. }
  215. // force-add all primary key fields
  216. if ( ! isset($this->_sqlParts['distinct']) || $this->_sqlParts['distinct'] != true) {
  217. foreach ($this->getTableAliasMap() as $tableAlias => $componentAlias) {
  218. $map = $this->_queryComponents[$componentAlias];
  219. foreach ((array) $map['table']->getIdentifierColumnNames() as $key) {
  220. $field = $tableAlias . '.' . $key;
  221. if ( ! isset($this->_sqlParts['select'][$field])) {
  222. $select[$componentAlias][$field] = $field . ' AS ' . $tableAlias . '__' . $key;
  223. }
  224. }
  225. }
  226. }
  227. $q = 'SELECT ';
  228. if (isset($this->_sqlParts['distinct']) && $this->_sqlParts['distinct'] == true) {
  229. $q .= 'DISTINCT ';
  230. }
  231. // first add the fields of the root component
  232. reset($this->_queryComponents);
  233. $componentAlias = key($this->_queryComponents);
  234. $this->_rootAlias = $componentAlias;
  235. $q .= implode(', ', $select[$componentAlias]);
  236. unset($select[$componentAlias]);
  237. foreach ($select as $component => $fields) {
  238. if ( ! empty($fields)) {
  239. $q .= ', ' . implode(', ', $fields);
  240. }
  241. }
  242. $string = $this->getInheritanceCondition($this->getRootAlias());
  243. if ( ! empty($string)) {
  244. $this->_sqlParts['where'][] = $string;
  245. }
  246. $q .= ( ! empty($this->_sqlParts['from']))? ' FROM ' . implode(' ', $this->_sqlParts['from']) : '';
  247. $q .= ( ! empty($this->_sqlParts['where']))? ' WHERE ' . implode(' AND ', $this->_sqlParts['where']) : '';
  248. $q .= ( ! empty($this->_sqlParts['groupby']))? ' GROUP BY ' . implode(', ', $this->_sqlParts['groupby']) : '';
  249. $q .= ( ! empty($this->_sqlParts['having']))? ' HAVING ' . implode(' AND ', $this->_sqlParts['having']) : '';
  250. $q .= ( ! empty($this->_sqlParts['orderby']))? ' ORDER BY ' . implode(', ', $this->_sqlParts['orderby']) : '';
  251. $q .= ( ! empty($this->_sqlParts['limit']))? ' LIMIT ' . implode(' ', $this->_sqlParts['limit']) : '';
  252. $q .= ( ! empty($this->_sqlParts['offset']))? ' OFFSET ' . implode(' ', $this->_sqlParts['offset']) : '';
  253. if ( ! empty($string)) {
  254. array_pop($this->_sqlParts['where']);
  255. }
  256. return $q;
  257. }
  258. /**
  259. * getCountQuery
  260. * builds the count query.
  261. *
  262. * @return string the built sql query
  263. */
  264. public function getCountQuery($params = array())
  265. {
  266. //Doing COUNT( DISTINCT rootComponent.id )
  267. //This is not correct, if the result is not hydrated by doctrine, but it mimics the behaviour of Doctrine_Query::getCountQuery
  268. reset($this->_queryComponents);
  269. $componentAlias = key($this->_queryComponents);
  270. $this->_rootAlias = $componentAlias;
  271. $tableAlias = $this->getSqlTableAlias($componentAlias);
  272. $fields = array();
  273. foreach ((array) $this->_queryComponents[$componentAlias]['table']->getIdentifierColumnNames() as $key) {
  274. $fields[] = $tableAlias . '.' . $key;
  275. }
  276. $q = 'SELECT COUNT( DISTINCT '.implode(',',$fields).') as num_results';
  277. $string = $this->getInheritanceCondition($this->getRootAlias());
  278. if ( ! empty($string)) {
  279. $this->_sqlParts['where'][] = $string;
  280. }
  281. $q .= ( ! empty($this->_sqlParts['from']))? ' FROM ' . implode(' ', $this->_sqlParts['from']) : '';
  282. $q .= ( ! empty($this->_sqlParts['where']))? ' WHERE ' . implode(' AND ', $this->_sqlParts['where']) : '';
  283. $q .= ( ! empty($this->_sqlParts['groupby']))? ' GROUP BY ' . implode(', ', $this->_sqlParts['groupby']) : '';
  284. $q .= ( ! empty($this->_sqlParts['having']))? ' HAVING ' . implode(' AND ', $this->_sqlParts['having']) : '';
  285. if ( ! empty($string)) {
  286. array_pop($this->_sqlParts['where']);
  287. }
  288. return $q;
  289. }
  290. /**
  291. * count
  292. * fetches the count of the query
  293. *
  294. * This method executes the main query without all the
  295. * selected fields, ORDER BY part, LIMIT part and OFFSET part.
  296. *
  297. * This is an exact copy of the Dql Version
  298. *
  299. * @see Doctrine_Query::count()
  300. * @param array $params an array of prepared statement parameters
  301. * @return integer the count of this query
  302. */
  303. public function count($params = array())
  304. {
  305. $q = $this->getCountQuery();
  306. $params = $this->getCountQueryParams($params);
  307. $results = $this->getConnection()->fetchAll($q, $params);
  308. if (count($results) > 1) {
  309. $count = count($results);
  310. } else {
  311. if (isset($results[0])) {
  312. $results[0] = array_change_key_case($results[0], CASE_LOWER);
  313. $count = $results[0]['num_results'];
  314. } else {
  315. $count = 0;
  316. }
  317. }
  318. return (int) $count;
  319. }
  320. /**
  321. * getFields
  322. * returns the fields associated with this parser
  323. *
  324. * @return array all the fields associated with this parser
  325. */
  326. public function getFields()
  327. {
  328. return $this->fields;
  329. }
  330. /**
  331. * addComponent
  332. *
  333. * @param string $tableAlias
  334. * @param string $componentName
  335. * @return Doctrine_RawSql
  336. */
  337. public function addComponent($tableAlias, $path)
  338. {
  339. $tmp = explode(' ', $path);
  340. $originalAlias = (count($tmp) > 1) ? end($tmp) : null;
  341. $e = explode('.', $tmp[0]);
  342. $fullPath = $tmp[0];
  343. $fullLength = strlen($fullPath);
  344. $table = null;
  345. $currPath = '';
  346. if (isset($this->_queryComponents[$e[0]])) {
  347. $table = $this->_queryComponents[$e[0]]['table'];
  348. $currPath = $parent = array_shift($e);
  349. }
  350. foreach ($e as $k => $component) {
  351. // get length of the previous path
  352. $length = strlen($currPath);
  353. // build the current component path
  354. $currPath = ($currPath) ? $currPath . '.' . $component : $component;
  355. $delimeter = substr($fullPath, $length, 1);
  356. // if an alias is not given use the current path as an alias identifier
  357. if (strlen($currPath) === $fullLength && isset($originalAlias)) {
  358. $componentAlias = $originalAlias;
  359. } else {
  360. $componentAlias = $currPath;
  361. }
  362. if ( ! isset($table)) {
  363. $conn = Doctrine_Manager::getInstance()
  364. ->getConnectionForComponent($component);
  365. $table = $conn->getTable($component);
  366. $this->_queryComponents[$componentAlias] = array('table' => $table);
  367. } else {
  368. $relation = $table->getRelation($component);
  369. $this->_queryComponents[$componentAlias] = array('table' => $relation->getTable(),
  370. 'parent' => $parent,
  371. 'relation' => $relation);
  372. }
  373. $this->addSqlTableAlias($tableAlias, $componentAlias);
  374. $parent = $currPath;
  375. }
  376. return $this;
  377. }
  378. /**
  379. * calculateResultCacheHash
  380. * calculate hash key for result cache
  381. *
  382. * @param array $params
  383. * @return string the hash
  384. */
  385. public function calculateResultCacheHash($params = array())
  386. {
  387. $sql = $this->getSql();
  388. $conn = $this->getConnection();
  389. $params = $this->getFlattenedParams($params);
  390. $hash = md5($this->_hydrator->getHydrationMode() . $conn->getName() . $conn->getOption('dsn') . $sql . var_export($params, true));
  391. return $hash;
  392. }
  393. }