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
Original file line number Original file line Diff line number Diff line change
Expand Up @@ -5,13 +5,13 @@ php:
- 5.3 - 5.3
- 5.4 - 5.4


services:
- memcached

before_script: before_script:
- ./tests/travis/mysql-setup.sh
- ./tests/travis/postgresql-setup.sh
- ./tests/travis/memcache-setup.sh
- cd tests - 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 script: phpunit --colors --coverage-text --exclude-group mssql,oci framework
1 change: 1 addition & 0 deletions CHANGELOG
Original file line number Original file line Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
Version 1.1.13 work in progress 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 #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 #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 #124: Added CMysqlCommandBuilder to handle JOIN directive on update commands correctly (cebe, DaSourcerer)
- Bug #962: Fixed handling of negative timestamps in CDateFormatter::format() (johnmendonca) - Bug #962: Fixed handling of negative timestamps in CDateFormatter::format() (johnmendonca)
Expand Down
7 changes: 3 additions & 4 deletions UPGRADE
Original file line number Original file line Diff line number Diff line change
@@ -1,4 +1,3 @@

Upgrading Instructions for Yii Framework v1.1.13 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. 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 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. 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 You can get that alias by calling `$this->getTableAlias();` in your active record class
or `$this->owner->getTableAlias(false, false)` in behavior context. or `$this->owner->getTableAlias()` in behavior context.


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


Upgrading from v1.1.11 Upgrading from v1.1.11
Expand Down
2 changes: 1 addition & 1 deletion framework/db/ar/CActiveFinder.php
Original file line number Original file line Diff line number Diff line change
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 $scopes=array_merge($scopes,(array)$options['scopes']); // no need for complex merging


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


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


/** /**
* This event is raised before an AR finder performs a find call. * This event is raised before an AR finder performs a find call.
* In this event, the {@link CModelEvent::criteria} property contains the query criteria * This can be either a call to CActiveRecords find methods or a find call
* passed as parameters to those find methods. If you want to access * when model is loaded in relational context via lazy or eager loading.
* the query criteria specified in scopes, please use {@link getDbCriteria()}. * If you want to access or modify the query criteria used for the
* You can modify either criteria to customize them based on needs. * 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 * @param CModelEvent $event the event parameter
* @see beforeFind * @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. * This method is invoked before an AR finder executes a find call.
* The find calls include {@link find}, {@link findAll}, {@link findByPk}, * 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. * The default implementation raises the {@link onBeforeFind} event.
* If you override this method, make sure you call the parent implementation * If you override this method, make sure you call the parent implementation
* so that the event is raised properly. * so that the event is raised properly.
* For details on modifying query criteria see {@link onBeforeFind} event.
*/ */
protected function beforeFind() protected function beforeFind()
{ {
Expand Down
2 changes: 1 addition & 1 deletion framework/messages/pt/yii.php
Original file line number Original file line Diff line number Diff line change
Expand Up @@ -138,7 +138,7 @@
'Invalid MO file: {file} (magic: {magic}).' => 'Arquivo MO inválido: {file} (magic: {magic}).', '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 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}".', '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 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.', 'List index "{index}" is out of bound.' => 'Índice "{index}" da lista está fora dos limites.',
'Login Required' => 'Login requerido', 'Login Required' => 'Login requerido',
Expand Down
25 changes: 25 additions & 0 deletions tests/framework/db/ar/CActiveRecordEventWrappersTest.php
Original file line number Original file line Diff line number Diff line change
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('select'=>"'changedTitle' AS title")), 3, array('title'=>'changedTitle')),
array(new CDbCriteria(array('condition'=>"title='post 2'")), 1, array()), array(new CDbCriteria(array('condition'=>"title='post 2'")), 1, array()),
array(new CDbCriteria(array('with'=>'comments')), 3, 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 * 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
Original file line number Original file line Diff line number Diff line change
Expand Up @@ -1391,4 +1391,14 @@ public function testIssue1070()
$this->assertTrue($result); $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
Original file line number Original file line Diff line number Diff line change
Expand Up @@ -551,6 +551,7 @@ public function relations()
{ {
return array( return array(
'posts'=>array(self::HAS_MANY,'PostWithWrappers','author_id'), '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'), 'postCount'=>array(self::STAT,'PostWithWrappers','author_id'),
'comments'=>array(self::HAS_MANY,'CommentWithWrappers',array('id'=>'post_id'),'through'=>'posts') '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__); $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) protected function incrementCounter($wrapper)
{ {
if(isset(self::$_counters[$wrapper])) if(isset(self::$_counters[$wrapper]))
Expand Down Expand Up @@ -771,6 +784,7 @@ public function defaultScope()


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


Expand Down
2 changes: 1 addition & 1 deletion tests/framework/db/data/sqlite.sql
Original file line number Original file line Diff line number Diff line change
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 (1,NULL,'Fred Bloggs');
INSERT INTO UserWithDefaultScope (id,deleted,`name`) VALUES (2,NULL,'Joe 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 CREATE TABLE UserWithDefaultScopeLink
( (
Expand Down
33 changes: 33 additions & 0 deletions tests/framework/db/schema/CMssqlTest.php
Original file line number Original file line Diff line number Diff line change
Expand Up @@ -3,6 +3,16 @@
Yii::import('system.db.CDbConnection'); Yii::import('system.db.CDbConnection');
Yii::import('system.db.schema.mssql.CMssqlSchema'); 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 * @group mssql
*/ */
Expand Down Expand Up @@ -71,6 +81,8 @@ public function setUp()
if(trim($sql)!=='') if(trim($sql)!=='')
$this->db->createCommand($sql)->execute(); $this->db->createCommand($sql)->execute();
} }

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


public function tearDown() public function tearDown()
Expand Down Expand Up @@ -343,4 +355,25 @@ public function testColumnComments()
$this->assertEquals('User\'s identifier', $usersColumns['user_id']->comment); $this->assertEquals('User\'s identifier', $usersColumns['user_id']->comment);
$this->assertEmpty($usersColumns['last_name']->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
Original file line number Original file line Diff line number Diff line change
@@ -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
Original file line number Original file line Diff line number Diff line change
@@ -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
Original file line number Original file line Diff line number Diff line change
@@ -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
Original file line number Original file line Diff line number Diff line change
@@ -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.