public function testNeedsSelectAliases() { $c = new Criteria(); $this->assertFalse(BasePeer::needsSelectAliases($c), 'Empty Criterias dont need aliases'); $c = new Criteria(); $c->addSelectColumn(BookPeer::ID); $c->addSelectColumn(BookPeer::TITLE); $this->assertFalse(BasePeer::needsSelectAliases($c), 'Criterias with distinct column names dont need aliases'); $c = new Criteria(); BookPeer::addSelectColumns($c); $this->assertFalse(BasePeer::needsSelectAliases($c), 'Criterias with only the columns of a model dont need aliases'); $c = new Criteria(); $c->addSelectColumn(BookPeer::ID); $c->addSelectColumn(AuthorPeer::ID); $this->assertTrue(BasePeer::needsSelectAliases($c), 'Criterias with common column names do need aliases'); }
/** * @see DBAdapter::applyLimit() * * @param string $sql * @param integer $offset * @param integer $limit * @param null|Criteria $criteria */ public function applyLimit(&$sql, $offset, $limit, $criteria = null) { if (BasePeer::needsSelectAliases($criteria)) { $crit = clone $criteria; $selectSql = $this->createSelectSqlPart($crit, $params, true); $sql = $selectSql . substr($sql, strpos($sql, 'FROM') - 1); } $sql = 'SELECT B.* FROM (' . 'SELECT A.*, rownum AS PROPEL_ROWNUM FROM (' . $sql . ') A ' . ') B WHERE '; if ($offset > 0) { $sql .= ' B.PROPEL_ROWNUM > ' . $offset; if ($limit > 0) { $sql .= ' AND B.PROPEL_ROWNUM <= ' . ($offset + $limit); } } else { $sql .= ' B.PROPEL_ROWNUM <= ' . $limit; } }
protected function doCount($con) { $dbMap = Propel::getServiceContainer()->getDatabaseMap($this->getDbName()); $db = Propel::getServiceContainer()->getAdapter($this->getDbName()); // check that the columns of the main class are already added (if this is the primary ModelCriteria) if (!$this->hasSelectClause() && !$this->getPrimaryCriteria()) { $this->addSelfSelectColumns(); } $this->configureSelectColumns(); $needsComplexCount = $this->getGroupByColumns() || $this->getOffset() || $this->getLimit() || $this->getHaving() || in_array(Criteria::DISTINCT, $this->getSelectModifiers()); $params = array(); if ($needsComplexCount) { if (BasePeer::needsSelectAliases($this)) { if ($this->getHaving()) { throw new PropelException('Propel cannot create a COUNT query when using HAVING and duplicate column names in the SELECT part'); } $db->turnSelectColumnsToAliases($this); } $selectSql = BasePeer::createSelectSql($this, $params); $sql = 'SELECT COUNT(*) FROM (' . $selectSql . ') propelmatch4cnt'; } else { // Replace SELECT columns with COUNT(*) $this->clearSelectColumns()->addSelectColumn('COUNT(*)'); $sql = BasePeer::createSelectSql($this, $params); } try { $stmt = $con->prepare($sql); $db->bindValues($stmt, $params, $dbMap); $stmt->execute(); } catch (Exception $e) { Propel::log($e->getMessage(), Propel::LOG_ERR); throw new PropelException(sprintf('Unable to execute COUNT statement [%s]', $sql), $e); } return $stmt; }