Skip to content

Commit

Permalink
Merge branch 'master' of git://github.com/yiisoft/yii into oci-unit-t…
Browse files Browse the repository at this point in the history
…ests
  • Loading branch information
resurtm committed Sep 8, 2012
2 parents dcaed42 + f6a351c commit 126722f
Show file tree
Hide file tree
Showing 15 changed files with 133 additions and 18 deletions.
12 changes: 6 additions & 6 deletions .travis.yml
Expand Up @@ -5,13 +5,13 @@ php:
- 5.3
- 5.4

services:
- memcached

before_script:
- ./tests/travis/mysql-setup.sh
- ./tests/travis/postgresql-setup.sh
- ./tests/travis/memcache-setup.sh
- cd tests
- mysql -u root -e 'CREATE SCHEMA `yii` CHARACTER SET utf8 COLLATE utf8_general_ci; GRANT ALL ON `yii`.* TO test@localhost IDENTIFIED BY "test"; FLUSH PRIVILEGES;'
- psql -q -c "CREATE ROLE test WITH PASSWORD 'test' LOGIN;" -U postgres
- psql -q -c 'CREATE DATABASE yii WITH OWNER = test;' -U postgres
- psql -q -c 'GRANT ALL PRIVILEGES ON DATABASE yii TO test;' -U postgres
- echo 'y' | pecl install memcache > ~/memcache.log || ( echo "=== MEMCACHE BUILD FAILED ==="; cat ~/memcache.log )
- if [ $TRAVIS_PHP_VERSION \< 5.4 ]; then echo "extension=memcache.so" >> `php --ini | grep "Loaded Configuration" | sed -e "s|.*:\s*||"`; fi

script: phpunit --colors --coverage-text --exclude-group mssql,oci framework
1 change: 1 addition & 0 deletions CHANGELOG
Expand Up @@ -4,6 +4,7 @@
Version 1.1.13 work in progress
-------------------------------
- Bug #93: Criteria modification in CActiveRecord::beforeFind() did not apply when record was loaded in relational context. See UPGRADE instructions for details on behavior change. (cebe)
- Bug #110: MSSQL: fixed empty $primaryKey value after saving CActiveRecord model (resurtm)
- Bug #112: MSSQL: database abstraction layer now uses native transaction support of the SQLSRV driver (resurtm)
- Bug #124: Added CMysqlCommandBuilder to handle JOIN directive on update commands correctly (cebe, DaSourcerer)
- Bug #962: Fixed handling of negative timestamps in CDateFormatter::format() (johnmendonca)
Expand Down
7 changes: 3 additions & 4 deletions UPGRADE
@@ -1,4 +1,3 @@

Upgrading Instructions for Yii Framework v1.1.13
================================================

Expand Down Expand Up @@ -28,13 +27,13 @@ Upgrading from v1.1.12
Since version 1.1.13 changes to query criteria made in beforeFind() now also apply to the query when model is loaded in a relational context.
The main problem here is that you can not use the `t`-alias for your table anymore, you have to change your code to
use the table alias currently in use as this it different in relational context.
You can get that alias by calling `$this->getTableAlias(false, false);` in your active record class
or `$this->owner->getTableAlias(false, false)` in behavior context.
You can get that alias by calling `$this->getTableAlias();` in your active record class
or `$this->owner->getTableAlias()` in behavior context.

Example:
$criteria->condition = 't.myfield = 1';
You need to change that to:
$alias = $this->owner->getTableAlias(false, false);
$alias = $this->owner->getTableAlias();
$criteria->condition = $alias.'.myfield = 1';

Upgrading from v1.1.11
Expand Down
2 changes: 1 addition & 1 deletion framework/db/ar/CActiveFinder.php
Expand Up @@ -233,9 +233,9 @@ private function buildJoinTree($parent,$with,$options=null)
$scopes=array_merge($scopes,(array)$options['scopes']); // no need for complex merging

$model->resetScope(false);
$model->beforeFindInternal();
$criteria=$model->getDbCriteria();
$criteria->scopes=$scopes;
$model->beforeFindInternal();
$model->applyScopes($criteria);
$relation->mergeWith($criteria,true);

Expand Down
17 changes: 12 additions & 5 deletions framework/db/ar/CActiveRecord.php
Expand Up @@ -860,10 +860,15 @@ public function onAfterDelete($event)

/**
* This event is raised before an AR finder performs a find call.
* In this event, the {@link CModelEvent::criteria} property contains the query criteria
* passed as parameters to those find methods. If you want to access
* the query criteria specified in scopes, please use {@link getDbCriteria()}.
* You can modify either criteria to customize them based on needs.
* This can be either a call to CActiveRecords find methods or a find call
* when model is loaded in relational context via lazy or eager loading.
* If you want to access or modify the query criteria used for the
* find call, you can use {@link getDbCriteria()} to customize it based on your needs.
* When modifying criteria in beforeFind you have to make sure you are using the right
* table alias which is different on normal find and relational call.
* You can use {@link getTableAlias()} to get the alias used for the upcoming find call.
* Please note that modification of criteria is fully supported as of version 1.1.13.
* Earlier versions had some problems with relational context and applying changes correctly.
* @param CModelEvent $event the event parameter
* @see beforeFind
*/
Expand Down Expand Up @@ -948,10 +953,12 @@ protected function afterDelete()
/**
* This method is invoked before an AR finder executes a find call.
* The find calls include {@link find}, {@link findAll}, {@link findByPk},
* {@link findAllByPk}, {@link findByAttributes} and {@link findAllByAttributes}.
* {@link findAllByPk}, {@link findByAttributes}, {@link findAllByAttributes},
* {@link findBySql} and {@link findAllBySql}.
* The default implementation raises the {@link onBeforeFind} event.
* If you override this method, make sure you call the parent implementation
* so that the event is raised properly.
* For details on modifying query criteria see {@link onBeforeFind} event.
*/
protected function beforeFind()
{
Expand Down
2 changes: 1 addition & 1 deletion framework/messages/pt/yii.php
Expand Up @@ -138,7 +138,7 @@
'Invalid MO file: {file} (magic: {magic}).' => 'Arquivo MO inválido: {file} (magic: {magic}).',
'Invalid enumerable value "{value}". Please make sure it is among ({enum}).' => 'Valor enumerável "{value}" inválido. Por favor, verifique se ele está entre ({enum}).',
'Invalid operator "{operator}".' => 'Operador inválido: "{opeator}".',
'Last &gt;&gt;' => 'Último Last &gt;&gt;',
'Last &gt;&gt;' => 'Último &gt;&gt;',
'List data must be an array or an object implementing Traversable.' => 'Dados da lista devem ser um array ou objetos que implemente a interface Trasversable.',
'List index "{index}" is out of bound.' => 'Índice "{index}" da lista está fora dos limites.',
'Login Required' => 'Login requerido',
Expand Down
25 changes: 25 additions & 0 deletions tests/framework/db/ar/CActiveRecordEventWrappersTest.php
Expand Up @@ -56,6 +56,7 @@ public function postCriteriaProvider()
array(new CDbCriteria(array('select'=>"'changedTitle' AS title")), 3, array('title'=>'changedTitle')),
array(new CDbCriteria(array('condition'=>"title='post 2'")), 1, array()),
array(new CDbCriteria(array('with'=>'comments')), 3, array()),
array(new CDbCriteria(array('scopes'=>'rename')), 3, array('title'=>'renamed post')),
);
}

Expand Down Expand Up @@ -356,6 +357,30 @@ public function testBeforeFindRelationalLazyCriteriaModification($criteria, $cou
}
}

/**
* tests if criteria modification in beforeFind() does not overide scopes defined by already applied criteria
* @dataProvider postCriteriaProviderLazy
*/
public function testBeforeFindRelationalLazyCriteriaScopes($criteria, $count, $assertations)
{
PostWithWrappers::setBeforeFindCriteria($criteria);

$user=UserWithWrappers::model()->findByPk(2);
$posts = $user->postsWithScope;
$this->assertCriteriaApplied($posts, $criteria, $count, $assertations);
foreach($posts as $post) {
$this->assertEquals('replaced content', $post->content);
}

$user=UserWithWrappers::model()->findByPk(2);
$posts = $user->posts(array('with'=>'comments','scopes'=>array('replaceContent')));
$this->assertCriteriaApplied($posts, $criteria, $count, $assertations);
foreach($posts as $post) {
$this->assertTrue($post->hasRelated('comments'));
$this->assertEquals('replaced content', $post->content);
}
}

/**
* tests number of calls to afterFind() on normal find*() method call
*/
Expand Down
10 changes: 10 additions & 0 deletions tests/framework/db/ar/CActiveRecordTest.php
Expand Up @@ -1391,4 +1391,14 @@ public function testIssue1070()
$this->assertTrue($result);
}
}

/**
* https://github.com/yiisoft/yii/issues/507
*/
public function testIssue507()
{
$this->assertEquals(2, count(UserWithDefaultScope::model()->findAll()));

}

}
14 changes: 14 additions & 0 deletions tests/framework/db/data/models.php
Expand Up @@ -551,6 +551,7 @@ public function relations()
{
return array(
'posts'=>array(self::HAS_MANY,'PostWithWrappers','author_id'),
'postsWithScope'=>array(self::HAS_MANY,'PostWithWrappers','author_id','scopes'=>array('replaceContent')),
'postCount'=>array(self::STAT,'PostWithWrappers','author_id'),
'comments'=>array(self::HAS_MANY,'CommentWithWrappers',array('id'=>'post_id'),'through'=>'posts')
);
Expand Down Expand Up @@ -658,6 +659,18 @@ protected function afterFind()
$this->incrementCounter(__FUNCTION__);
}

public function scopes()
{
return array(
'rename'=>array(
'select'=>"'renamed post' AS title",
),
'replaceContent' => array(
'select'=>"'replaced content' AS content",
),
);
}

protected function incrementCounter($wrapper)
{
if(isset(self::$_counters[$wrapper]))
Expand Down Expand Up @@ -771,6 +784,7 @@ public function defaultScope()

return array(
'condition'=>"{$alias}.deleted IS NULL",
'order'=>"{$alias}.name ASC",
);
}

Expand Down
2 changes: 1 addition & 1 deletion tests/framework/db/data/sqlite.sql
Expand Up @@ -271,7 +271,7 @@ CREATE TABLE UserWithDefaultScope

INSERT INTO UserWithDefaultScope (id,deleted,`name`) VALUES (1,NULL,'Fred Bloggs');
INSERT INTO UserWithDefaultScope (id,deleted,`name`) VALUES (2,NULL,'Joe Bloggs');
INSERT INTO UserWithDefaultScope (id,deleted,`name`) VALUES (3,NULL,'Jane Bloggs');
INSERT INTO UserWithDefaultScope (id,deleted,`name`) VALUES (3,1,'Jane Bloggs');

CREATE TABLE UserWithDefaultScopeLink
(
Expand Down
33 changes: 33 additions & 0 deletions tests/framework/db/schema/CMssqlTest.php
Expand Up @@ -3,6 +3,16 @@
Yii::import('system.db.CDbConnection');
Yii::import('system.db.schema.mssql.CMssqlSchema');

require_once(dirname(__FILE__).'/../data/models2.php');

class MssqlUser2 extends User2
{
public function tableName()
{
return '[dbo].[users]';
}
}

/**
* @group mssql
*/
Expand Down Expand Up @@ -71,6 +81,8 @@ public function setUp()
if(trim($sql)!=='')
$this->db->createCommand($sql)->execute();
}

CActiveRecord::$db=$this->db;
}

public function tearDown()
Expand Down Expand Up @@ -343,4 +355,25 @@ public function testColumnComments()
$this->assertEquals('User\'s identifier', $usersColumns['user_id']->comment);
$this->assertEmpty($usersColumns['last_name']->comment);
}

public function testARLastInsertId()
{
$user=new MssqlUser2();

$user->username='testingUser';
$user->password='testingPassword';
$user->email='testing@email.com';

$this->assertTrue($user->isNewRecord);
$this->assertNull($user->primaryKey);
$this->assertNull($user->id);
$this->assertEquals(3, $this->db->createCommand('SELECT MAX(id) FROM [dbo].[users]')->queryScalar());

$user->save();

$this->assertFalse($user->isNewRecord);
$this->assertEquals(4, $user->primaryKey);
$this->assertEquals(4, $user->id);
$this->assertEquals(4, $this->db->createCommand('SELECT MAX(id) FROM [dbo].[users]')->queryScalar());
}
}
12 changes: 12 additions & 0 deletions tests/travis/README.md
@@ -0,0 +1,12 @@
This directory contains scripts for automated test runs via the [Travis CI](http://travis-ci.org) build service. They are used for the preparation of worker instances by setting up needed extensions and configuring database access.

These scripts might be used to configure your own system for test runs. But since their primary purpose remains to support Travis in running the test cases, you would be best advised to stick to the setup notes in the tests themselves.

The scripts are:

- `memcache-setup.sh`
Compiles and installs the [memcache pecl extension](http://pecl.php.net/package/memcache)
- `mysql-setup.sh`
Prepares the [MySQL](http://www.mysql.com) server instance by creating the test database and granting access to it
- `postgresql-setup.sh`
Same for [PostgreSQL](http://www.postgresql.org/)
6 changes: 6 additions & 0 deletions tests/travis/memcache-setup.sh
@@ -0,0 +1,6 @@
#!/bin/bash

echo 'y' | pecl install memcache > ~/memcache.log || ( echo "=== MEMCACHE BUILD FAILED ==="; cat ~/memcache.log )
if [[ $TRAVIS_PHP_VERSION < 5.4 ]]; then
echo "extension=memcache.so" >> `php --ini | grep "Loaded Configuration" | sed -e "s|.*:\s*||"`
fi
3 changes: 3 additions & 0 deletions tests/travis/mysql-setup.sh
@@ -0,0 +1,3 @@
#!/bin/sh

mysql -u root -e 'CREATE SCHEMA `yii` CHARACTER SET utf8 COLLATE utf8_general_ci; GRANT ALL ON `yii`.* TO test@localhost IDENTIFIED BY "test"; FLUSH PRIVILEGES;'
5 changes: 5 additions & 0 deletions tests/travis/postgresql-setup.sh
@@ -0,0 +1,5 @@
#!/bin/sh

psql -q -c "CREATE ROLE test WITH PASSWORD 'test' LOGIN;" -U postgres
psql -q -c 'CREATE DATABASE yii WITH OWNER = test;' -U postgres
psql -q -c 'GRANT ALL PRIVILEGES ON DATABASE yii TO test;' -U postgres

0 comments on commit 126722f

Please sign in to comment.