Reputation: 288
how do you create sql triggers with doctrine migrations?
here is migration:
<?php
namespace App\Migrations;
use Doctrine\DBAL\Migrations\AbstractMigration;
use Doctrine\DBAL\Schema\Schema;
use Doctrine\DBAL\Schema\Table;
/**
* Auto-generated Migration: Please modify to your needs!
*/
class Version20151211173441 extends AbstractMigration
{
/**
* @param Schema $schema
*/
public function up(Schema $schema)
{
$table = $schema->createTable('public.users');
$table->addColumn('id', 'integer', [
'autoincrement' => true
]);
$table->addColumn('name', 'string');
$table->setPrimaryKey(['id']);
$this->addSql("
CREATE OR REPLACE FUNCTION public.users_insert_trigger()
RETURNS TRIGGER AS $$
BEGIN
NEW.name := NEW.name || ' test';
RETURN NEW;
END;
$$
LANGUAGE plpgsql;
");
$this->addSql("
CREATE TRIGGER users_on_insert_trigger
BEFORE INSERT ON public.users
FOR EACH ROW EXECUTE PROCEDURE public.users_insert_trigger();
");
}
/**
* @param Schema $schema
*/
public function down(Schema $schema)
{
$this->addSql("DROP TRIGGER public.users_on_insert_trigger ON users");
$this->addSql("DROP FUNCTION public.users_insert_trigger()");
$schema->dropTable('users');
}
}
This produces the following error:
SQLSTATE[42P01]: Undefined table: 7 ERROR: relation "public.users" does not exist
And produces the following sql:
CREATE OR REPLACE FUNCTION public.users_insert_trigger()
RETURNS TRIGGER AS $$
BEGIN
NEW.name := NEW.name || ' test';
RETURN NEW;
END;
$$
LANGUAGE plpgsql;
CREATE TRIGGER users_on_insert_trigger
BEFORE INSERT ON public.users
FOR EACH ROW EXECUTE PROCEDURE public.users_insert_trigger();
CREATE TABLE public.users (id SERIAL NOT NULL, name VARCHAR(255) NOT NULL, PRIMARY KEY(id));
INSERT INTO common.migrations (version) VALUES ('20151211173441');
If I correctly understand, changes in schema is applied in the end of migration. But it doesn't suit me...
So, how can i handle it?
Upvotes: 1
Views: 2214
Reputation: 288
ok, i found 2 related issues:
so you can:
without Schema you migration look like this
<?php
public function up(Schema $schema)
{
$platform = $this->connection->getSchemaManager()->getDatabasePlatform();
$table = new Table('table_name'/*, ...*/);
// ...
$sql = $platform->getCreateTableSQL($table);
// or
$sql = $platform->getDropTableSQL($table);
// etc.
$this->addSql($sql);
}
Upvotes: 0
Reputation: 79
You have correctly summarized the problem: the migration runner actually executes SQL you add via addSQL() before SQL generated using schemas.
You'll need to make this change as two separate migrations.
Upvotes: 1