[Urgent] CDbException, The table "*" for active record class "*" cannot be found in the database.

Hi, this is the second time (different project) in which im getting this error

In another proyect it did the same with a diferent table (Country) And I had to stop using that Model and use a hardcoded SQL query, it wasent critical at that time and ActiveRecord for my table Leaf worked fine

Note:Im using the same MySql database for both projects

But now, in a different project im getting this error again, with table Leaf, do you guys know what can be possible causing this?

In project A that same model works perfectly, but in project B (using the same database and a copy/pasted model from project A) I get this error:


CDbException

Description


The table "leaf" for active record class "Leaf" cannot be found in the database.

Source File


/portal/app/www/yii/framework/db/ar/CActiveRecord.php(2137)

Any ideas on how to fix this? its the last time i get this error, and if i use a hardcoded query it works fine, and well… the table is there im using it on other projects, and Im using the same copy/pasted model too.

So I dont understand whats happening :(

Is your table name ‘Leaf’ or ‘leaf’?

I tink that this problem occurs when you do the model and the crud command…

suppose that the table is called ‘leaf’, well

You must do the model command this way: model Leaf

and the crud command in the same way: crud Leaf

At least this happens to me once and y discover that I did the model/crud command in diferent way:

table: leaf

model Leaf

crud leaf

Note that I do model Leaf and crud leaf.

This way the error occurs (no matter the of the table, in this case ‘leaf’)

But whey I did the commnad whit the proper case, all works perfect!

thanks for your reply.

Ive had that problem before too, but this is not the case im working on it, and ive tracked the problem down to the CMysqlSchema




/**

	 * Collects the table column metadata.

	 * @param CMysqlTableSchema the table metadata

	 * @return boolean whether the table exists in the database

	 */

	protected function findColumns($table)

	{

		$sql='SHOW COLUMNS FROM '.$table->rawName;

		try

		{

			$columns=$this->getDbConnection()->createCommand($sql)->queryAll();

		}

		catch(Exception $e)

		{

			return false;

		}



Note that if there is an exception false is returned and so no columns = no table is the error displayed but the real error is lost in the catch, so i echoed aout the Exception and the real exception is:


'CDbException' with message 'CDbCommand failed to execute the SQL statement: SQLSTATE[HY000]: 

General error: 2014 Cannot execute queries while other unbuffered 

queries are active. Consider using PDOStatement::fetchAll(). Alternatively, if your code

 is only ever going to run against mysql, you may enable query buffering by setting the 

PDO::MYSQL_ATTR_USE_BUFFERED_QUERY attribute.' in /portal/app/www/yii/framework

/db/CDbCommand.php:318

Stack trace:

#0 /portal/app/www/yii/framework/db/CDbCommand.php(237): CDbCommand->queryInternal('fetchAll', 2)

#1 /portal/app/www/yii/framework/db/schema/mysql/CMysqlSchema.php(106): CDbCommand->queryAll()

#2 /portal/app/www/yii/framework/db/schema/mysql/CMysqlSchema.php(66): CMysqlSchema->findColumns(Object(CMysqlTableSchema))

#3 /portal/app/www/yii/framework/db/schema/CDbSchema.php(73): CMysqlSchema->createTable('leaf')

#4 /portal/app/www/yii/framework/db/ar/CActiveRecord.php(2136): CDbSchema->getTable('leaf')

#5 /portal/app/www/yii/framework/db/ar/CActiveRecord.php(634): CActiveRecordMetaData->__construct(Object(Leaf))

#6 /portal/app/www/ecards/protected/models/Leaf.php(29): CActiveRecord::model('Leaf')

#7 /portal/app/www/ecards/protected/models/CustomObjects/COCategory.php(71): Leaf::model()

#8 /portal/app/www/ecards/protected/controllers/HomeController.php(35): COCategory->getRandomEcard()

#9 /portal/app/www/yii/framework/web/actions/CInlineAction.php(32): HomeController->actionIndex()

#10 /portal/app/www/yii/framework/web/CController.php(300): CInlineAction->run()

#11 /portal/app/www/yii/framework/web/CController.php(278): CController->runAction(Object(CInlineAction))

#12 /portal/app/www/yii/framework/web/CController.php(257): CController->runActionWithFilters(Object(CInlineAction), Array)

#13 /portal/app/www/yii/framework/web/CWebApplication.php(332): CController->run('')

#14 /portal/app/www/yii/framework/web/CWebApplication.php(120): CWebApplication->runController('')

#15 /portal/app/www/yii/framework/base/CApplication.php(133): CWebApplication->processRequest()

#16 /portal/app/www/ecards/index.php(16): CApplication->run()

#17 {main}.

Im working on it right now :S i dont really know how to solve that, perharps if I shoud you my code you guy can help me out? :)




/**

	 * returns a CustomObject COEcard representing a random Ecard from this category

	 * @return COEcard

	 */

	public function getRandomEcard($limit = 1, $exclude = Array()){

		$notIn = "";

		if(!empty($exclude)){

			$notIn = "AND l.ID NOT IN (".implode(",",  array_map("collectIds", $exclude)).") ";

		}


		$q = "SELECT l.ID FROM NODE n

				JOIN (LEAF l, NODE_LEAF nl, LEAF_RESOURCE lr, EXTRA_NODE en)

				ON (l.ID = nl.LEAF_ID AND n.ID = nl.NODE_ID AND lr.LEAF_ID = l.ID AND en.NODE_ID = n.ID)

				WHERE en.NODE_ID IN (SELECT id FROM Node WHERE node_id = {$this->id}) $notIn

				ORDER BY RAND() LIMIT $limit;";

		$conn = conn();

		$command = $conn->createCommand($q);

		$reader=$command->query();//PROBLEM

		$cards = Array();

		foreach($reader as $row){

			$cards[] = Leaf::model()->findByPk($row['ID'])->getCOEcard();//here is where the the problem happens

		}

		return (count($cards) > 0) ? $cards : null;

	}



It looks like it didnt like me hardcoding the SQL and then using a model :-[

[SOLVED]: Well the problem was that I used $reader=$command->query();

when I should have used

$reader=$command->queryColumn();

for some reason it didnt "unbuffered" if I used just query()

So the right code is:




/**

	 * returns a CustomObject COEcard representing a random Ecard from this category

	 * @return COEcard

	 */

	public function getRandomEcard($limit = 1, $exclude = Array()){

		$notIn = "";

		if(!empty($exclude)){

			$notIn = "AND l.ID NOT IN (".implode(",",  array_map("collectIds", $exclude)).") ";

		}


		$q = "SELECT l.ID FROM NODE n

				JOIN (LEAF l, NODE_LEAF nl, LEAF_RESOURCE lr, EXTRA_NODE en)

				ON (l.ID = nl.LEAF_ID AND n.ID = nl.NODE_ID AND lr.LEAF_ID = l.ID AND en.NODE_ID = n.ID)

				WHERE en.NODE_ID IN (SELECT id FROM Node WHERE node_id = {$this->id}) $notIn

				ORDER BY RAND() LIMIT $limit;";

		$conn = conn();

		$command = $conn->createCommand($q);

		$reader=$command->queryColumn();//Just the First Column

		$cards = Array();

		foreach($reader as $row){

			$cards[] = Leaf::model()->findByPk($row)->getCOEcard();

		}

		return (count($cards) > 0) ? $cards : null;

	}



Reminds me of when I had to setActive(false) on the connection or the subsequent AR access would fail.




  Yii::app()->getDb()->createCommand($sql)->execute();

  Yii::app()->getDb()->setActive(false);



/Tommy

Hi

I also face this problem as well, this situation happen if you mixed your query method with ActiveRecord and DAO, it happned inside a loop. I manage to handle it by readAll() result into array, and close the dataReader.

Just sharing.

Should be fixed now.

See this thread:

http://www.yiiframework.com/forum/index.php?/topic/4978-createcommand-execute-then-using-findall-from-an-ar-class-throws-error/page__fromsearch__1

/Tommy

Edited: [SOLVED] It turned out that my Registration model returns the tablename with uppercase first letter ("Registration") while in my db I have the table in lower case first letter ("registration").




	/**

	 * @return string the associated database table name

	 */

	public function tableName()

	{

		return '{{registration}}';

	}



Help! I also have the same error, but I got it when creating new object (calling __construct). Strangely it works on my localhost (Windows) but not on my shared host (Linux). Basically I want to call the action "Activate" from controller "Registration", which is accessed through URL www.example.com/index.php?r=registration/activate&id=x&code=y. On my Windows when I try localhost/index.php?r=registration/activate (omitting the id & code params) I get the 404 "Sorry, activation failed", but on linux I got this exception.

Please help, what did I do wrong?

Thanks!

The exception:




CDbException

Description


The table "{{Registration}}" for active record class "Registration" cannot be found in the database.

Source File


/home/www/framework/db/ar/CActiveRecord.php(1930)


01918:     private $_model;

01919: 

01920:     /**

01921:      * Constructor.

01922:      * @param CActiveRecord the model instance

01923:      */

01924:     public function __construct($model)

01925:     {

01926:         $this->_model=$model;

01927: 

01928:         $tableName=$model->tableName();

01929:         if(($table=$model->getDbConnection()->getSchema()->getTable($tableName))===null)

01930: throw new CDbException(Yii::t('yii','The table "{table}" for active record class "{class}" cannot be found in the database.',

01931:                 array('{class}'=>get_class($model),'{table}'=>$tableName)));

01932:         if($table->primaryKey===null)

01933:             $table->primaryKey=$model->primaryKey();

01934:         $this->tableSchema=$table;

01935:         $this->columns=$table->columns;

01936: 

01937:         foreach($table->columns as $name=>$column)

01938:         {

01939:             if(!$column->isPrimaryKey && $column->defaultValue!==null)

01940:                 $this->attributeDefaults[$name]=$column->defaultValue;

01941:         }

01942: 


Stack Trace


#0 /home/www/framework/db/ar/CActiveRecord.php(328): CActiveRecordMetaData->__construct(Object(Registration))

#1 /home/www/framework/db/ar/CActiveRecord.php(341): CActiveRecord::model('Registration')

#2 /home/www/framework/db/ar/CActiveRecord.php(59): CActiveRecord->getMetaData()

#3 /home/www/protected/controllers/RegistrationController.php(76): CActiveRecord->__construct()

#4 /home/www/framework/web/actions/CInlineAction.php(32): RegistrationController->actionActivate()

#5 /home/www/framework/web/CController.php(300): CInlineAction->run()

#6 /home/www/framework/web/filters/CFilterChain.php(129): CController->runAction(Object(CInlineAction))

#7 /home/www/framework/web/filters/CFilter.php(41): CFilterChain->run()

#8 /home/www/framework/web/CController.php(983): CFilter->filter(Object(CFilterChain))

#9 /home/www/framework/web/filters/CInlineFilter.php(59): CController->filterAccessControl(Object(CFilterChain))

#10 /home/www/framework/web/filters/CFilterChain.php(126): CInlineFilter->filter(Object(CFilterChain))

#11 /home/www/framework/web/CController.php(283): CFilterChain->run()

#12 /home/www/framework/web/CController.php(257): CController->runActionWithFilters(Object(CInlineAction), Array)

#13 /home/www/framework/web/CWebApplication.php(320): CController->run('activate')

#14 /home/www/framework/web/CWebApplication.php(120): CWebApplication->runController('registration/ac...')

#15 /home/www/framework/base/CApplication.php(135): CWebApplication->processRequest()

#16 /home/www/index.php(11): CApplication->run()

#17 {main}



The RegistrationController.php:




/**

 * Activates user registration.

 * If creation is successful, the browser will be redirected to index page.

 */

  public function actionActivate()

  {

    $regid = $_GET['id'];

    $activatecode = $_GET['code'];

    $criteria = new CDbCriteria(array(

		  'condition' => 'id=:regid AND activation=:activatecode',

		  'params' => array(':regid'=>$regid,':activatecode'=>$activatecode)));

    $reg = new Registration;

    $registration = $reg->find($criteria);

    if(is_null($registration))

      throw new CHttpException(404,'Sorry, activation failed.');

    else {

        // do things

    }

    $this->redirect(array('site/index'));

  }



the same problem, but nothing helped above…

Controller:




public function actionList()

	{

		$criteria=new CDbCriteria;

        //$criteria->condition='rusis=0';

        

		$pages=new CPagination(Augalas::model()->count($criteria));

		$pages->pageSize=self::PAGE_SIZE;

		$pages->applyLimit($criteria);


		$models=Augalas::model()->findAll($criteria);

        

		$this->render('list',array(

			'augalai'=>$models,

			'pages'=>$pages,

		));

	}




Database contains ‘augalas’ table.

and the error…

Description

The table "Augalas" for active record class "Augalas" cannot be found in the database.

Source File

/home/vhosts/silingumedelynas.eu5.org/opt/yii/framework/db/ar/CActiveRecord.php(1952)

01940: private $_model;

01941:

01942: /**

01943: * Constructor.

01944: * @param CActiveRecord the model instance

01945: */

01946: public function __construct($model)

01947: {

01948: $this->_model=$model;

01949:

01950: $tableName=$model->tableName();

01951: if(($table=$model->getDbConnection()->getSchema()->getTable($tableName))===null)

01952: throw new CDbException(Yii::t(‘yii’,‘The table “{table}” for active record class “{class}” cannot be found in the database.’,

01953: array(’{class}’=>get_class($model),’{table}’=>$tableName)));

01954: if($table->primaryKey===null)

01955: $table->primaryKey=$model->primaryKey();

01956: $this->tableSchema=$table;

01957: $this->columns=$table->columns;

01958:

01959: foreach($table->columns as $name=>$column)

01960: {

01961: if(!$column->isPrimaryKey && $column->defaultValue!==null)

01962: $this->attributeDefaults[$name]=$column->defaultValue;

01963: }

01964:

Anyone help, pls?

are you sure your table name and the model returned name are in the same case?

A very late reply on an old topic, but here is what we discovered on our MySQL setup.

We encountered the same problems as described, we checked all the usual suspects, it even worked on our developer machines but failed on the build machine, WTH!

It turns out that while the configured user on our developer machines had GRANT ALL (easier to deal with) the configured user in the dbconnection on the build machine had much more restricted privileges - it did not have SELECT permission on the table in question. User must have SELECT permission for SHOW CREATE TABLE, SHOW COLUMNS and so on. Nothing in the framework complained when attempting to load table or column information. So the “can’t find table for …” message is totally bogus.

The framework should have complained that it could not execute the SHOW TABLE or SHOW COLUMNS before it ever got to this point.

FWIW, this problem for me was caused by my recent install of Microsoft Security Essentials. Like Asgaroth, I also had to trace into the framework to find the real exception (it was being caught and returning FALSE in CMysqlSchema::findColumns()).

Here is a blog post that helped me determine the problem and find a simple solution (can’t post full link due to forum rules): http – beerpla.net – /2010/01/05/how-to-fix-intermittent-mysql-errcode-13-errors-on-windows/

i too had the same issue,

reason i figured out was

my table name: operators

my model name: staffoperators.php

my model class name: Operatorsstaff

following method fixed my issue

i changed both model name & class name to db name, i.e. operators.php & operators

hope this helps

charles

i ran into the issue again, this time i solved it in a very strange method, this issue is killing me.

iam using netbeans IDE. usually when u ctrl+click on a model name netbeans takes you to the corresponding class file. In this case netbeans was not navigating to the class file.

So i deleted the model file. created new model file using yiimodel generator.

now evthing is working fine.