Phinx migrations sqlite memory phpunit

884 Views Asked by At

Phinx migrations using sqlite memory don't appear to be working in 0.9.2, I have a very simple app with one table (product). After running the migration the product table doesn't exist:

use Symfony\Component\Yaml\Yaml;
use Phinx\Config\Config;
use Phinx\Migration\Manager;
use Symfony\Component\Console\Input\StringInput;
use Symfony\Component\Console\Output\NullOutput;

$pdo = new PDO('sqlite::memory:', null, null, [
    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
]);

$settings = Yaml::parseFile('../phinx.yml');
$settings['environments']['testing'] = [
    'adapter'       => 'sqlite',
    'connection'    => $pdo
];
$config = new Config($settings);

$manager = new Manager($config, new StringInput(' '), new NullOutput());
$manager->migrate('testing');
$manager->seed('testing');

$pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_OBJ);

// This line creates an exception of table doesn't exist
$pdo->query("SELECT * FROM product");

That final line queries the product table which produces the following exception:

PDOException: SQLSTATE[HY000]: General error: 1 no such table: product in /home/vagrant/code/ecommerce/public/index.php on line 43

For completeness here's the product migration which works perfectly with the development mysql environment:

use Phinx\Migration\AbstractMigration;

class Product extends AbstractMigration
{
    public function change()
    {
        $table = $this->table('product');
        $table->addColumn('name', 'string', ['limit' => 100, 'null' => false])
            ->addColumn('price', 'integer')
            ->create();
    }
}
1

There are 1 best solutions below

0
On

When you use phinx normally from the command line the the property configFilePath of Phinx\Config is properly set to the full path to phinx.yml

However in the example in the phinx documentation (http://docs.phinx.org/en/latest/commands.html#using-phinx-with-phpunit) for creating a sqlite memory database for phpunit testing it uses a php array because a pdo instance has to be manually fed in.

Because no path to phinx.yml is set, the replaceTokens method of Phinx\Config creates the PHINX_CONFIG_DIR by calling this:

$tokens['%%PHINX_CONFIG_DIR%%'] = dirname($this->getConfigFilePath());

Phinx uses %%PHINX_CONFIG_DIR%% to work out where its migrations and seeds folders are, when no phinx.yml is used this no longer works.

The solution is to provide a path when manually creating your Config class:

$config = new Config($settings, './');