Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Yii test. Truncate foreign keys

What is best solution for truncate database on each test start? I'm have InnoDB engine with foreigh keys, yii can't truncate table.

like image 737
Actimele Avatar asked Sep 30 '13 10:09

Actimele


2 Answers

If you extend CDbTestCase and use the built in public $fixtures property to specify your fixture files, it will handle this automatically.

However, if you built your own fixture generating system, or otherwise want to truncate a table, you can use the following.

$this->getFixtureManager()->checkIntegrity(false);
$this->getFixtureManager()->truncateTable('table_name');
$this->getFixtureManager()->checkIntegrity(false);

This again assumes you are extends CDbTestCase for your unit test files. If you are not, then you can directly remove the integrity checks like so:

Yii::app()->db->createCommand('set foreign_key_checks=0')->execute();
//do whatever, including truncating
Yii::app()->db->createCommand('set foreign_key_checks=1')->execute();

That will also temporarily disable the foreign key checks.

like image 140
Willem Renzema Avatar answered Nov 14 '22 23:11

Willem Renzema


Just to add a reference for Yii2 (as there are no easy to find examples):

$this->db->createCommand()->checkIntegrity(false)->execute();
$this->truncateTable('table_name');
$this->db->createCommand()->checkIntegrity(true)->execute();
like image 21
d.raev Avatar answered Nov 15 '22 00:11

d.raev