Akram
Akram

Reputation: 493

Execute sql script when updating database schema Doctrine

Is it possible to append (or execute) a custom sql queries when executing:

app/console doctrine:schema:update --force

I have a script that create all my views and I want them to be updated whenever I update the database schema.

Upvotes: 2

Views: 1777

Answers (1)

chalasr
chalasr

Reputation: 13167

Sure, you can extend the UpdateSchemaCommand command and inject the EntityManager into by defining the command as a service.

The command:

// src/AppBundle/Command/CustomUpdateSchemaCommand.php
<?php

namespace AppBundle\Command;

use Doctrine\Bundle\DoctrineBundle\Command\Proxy\UpdateSchemaDoctrineCommand;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\Console\Input\ArrayInput;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Command\Command;

class CustomUpdateSchemaCommand extends UpdateSchemaDoctrineCommand
{
    /** @var EntityManagerInterface */
    private $em;

    /**
     * @param EntityManagerInterface $em
     */
    public function __construct(EntityManagerInterface $em)
    {
        $this->em = $em;

        parent::__construct();
    }

    /**
     * {@inheritDoc}
     */
    protected function configure()
    {
        parent::configure();
    }

    /**
     * {@inheritDoc}
     */
    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $output->writeln('Hello world');
        $conn = $this->em->getConnection();
        $conn->exec(/* QUERY */);


        return parent::execute($input, $output);
    }
}

The service:

// app/config/services.yml
app.command.custom_schema_update_command:
    class: App\SportBundle\Command\CustomUpdateSchemaCommand
    arguments: ["@doctrine.orm.entity_manager"]
    tags:
        -  { name: console.command }

Hope this helps.

Upvotes: 6

Related Questions