InitDbFixture.php 2.29 KB
Newer Older
Qiang Xue committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
<?php
/**
 * @link http://www.yiiframework.com/
 * @copyright Copyright (c) 2008 Yii Software LLC
 * @license http://www.yiiframework.com/license/
 */

namespace yii\test;

use Yii;

/**
 * InitDbFixture represents the initial state needed for DB-related tests.
 *
 * Its main task is to toggle integrity check of the database during data loading.
 * This is needed by other DB-related fixtures (e.g. [[ActiveFixture]]) so that they can populate
 * data into the database without triggering integrity check errors.
 *
 * Besides, DbFixture also attempts to load an [[initScript|initialization script]] if it exists.
 *
 * You should normally use InitDbFixture to prepare a skeleton test database.
 * Other DB fixtures will then add specific tables and data to this database.
 *
 * @author Qiang Xue <qiang.xue@gmail.com>
 * @since 2.0
 */
class InitDbFixture extends DbFixture
{
	/**
	 * @var string the init script file that should be executed when loading this fixture.
	 * This should be either a file path or path alias. Note that if the file does not exist,
	 * no error will be raised.
	 */
	public $initScript = '@app/tests/fixtures/initdb.php';
	/**
	 * @var array list of database schemas that the test tables may reside in. Defaults to
Carsten Brandt committed
37
	 * `['']`, meaning using the default schema (an empty string refers to the
Qiang Xue committed
38 39 40 41 42 43 44 45 46 47 48
	 * default schema). This property is mainly used when turning on and off integrity checks
	 * so that fixture data can be populated into the database without causing problem.
	 */
	public $schemas = [''];


	/**
	 * @inheritdoc
	 */
	public function beforeLoad()
	{
Qiang Xue committed
49
		$this->checkIntegrity(false);
Qiang Xue committed
50 51 52 53 54 55 56
	}

	/**
	 * @inheritdoc
	 */
	public function afterLoad()
	{
Qiang Xue committed
57
		$this->checkIntegrity(true);
Qiang Xue committed
58 59 60 61 62 63 64 65 66 67 68 69
	}

	/**
	 * @inheritdoc
	 */
	public function load()
	{
		$file = Yii::getAlias($this->initScript);
		if (is_file($file)) {
			require($file);
		}
	}
Qiang Xue committed
70

71 72 73 74 75
	/**
	 * @inheritdoc
	 */
	public function beforeUnload()
	{
Qiang Xue committed
76
		$this->checkIntegrity(false);
77 78 79 80 81 82 83
	}

	/**
	 * @inheritdoc
	 */
	public function afterUnload()
	{
Qiang Xue committed
84
		$this->checkIntegrity(true);
85 86
	}

Qiang Xue committed
87 88 89 90 91 92 93 94 95 96
	/**
	 * Toggles the DB integrity check.
	 * @param boolean $check whether to turn on or off the integrity check.
	 */
	public function checkIntegrity($check)
	{
		foreach ($this->schemas as $schema) {
			$this->db->createCommand()->checkIntegrity($check, $schema)->execute();
		}
	}
Qiang Xue committed
97
}