PostgreSQL
 sql >> Database >  >> RDS >> PostgreSQL

Come anteporre i nomi delle sequenze?

Sulla base della risposta da qui:Come impostare la tabella prefisso in symfony2

  1. Apri Resources/config/services.yml del tuo bundle e aggiungi:

    parameters:
        mybundle.db.sequence_prefix: myprefix_
    
  2. Aggiungi un nuovo servizio:

    services:
        mybundle.sqprefix_subscriber:
            class: MyBundle\Subscriber\SequencePrefixSubscriber
            arguments: [%mybundle.db.sequence_prefix%]
            tags:
                - { name: doctrine.event_subscriber }
    
  3. Crea MyBundle\Subscriber\SequencePrefixSubscriber.php

    <?php
    namespace MyBundle\Subscriber;
    
    use Doctrine\ORM\Event\LoadClassMetadataEventArgs;
    
    class SequencePrefixSubscriber implements \Doctrine\Common\EventSubscriber
    {
        protected $prefix = '';
    
        public function __construct($prefix)
        {
            $this->prefix = (string) $prefix;
        }
    
        public function getSubscribedEvents()
        {
            return array('loadClassMetadata');
        }
    
        public function loadClassMetadata(LoadClassMetadataEventArgs $args)
        {
            $classMetadata = $args->getClassMetadata();
            if ($classMetadata->isInheritanceTypeSingleTable() && !$classMetadata->isRootEntity()) {
                return;
            }
    
    
            if ($classMetadata->isIdGeneratorSequence())
            {
                $newDefinition = $classMetadata->sequenceGeneratorDefinition;
                $newDefinition['sequenceName'] = $this->prefix . $newDefinition['sequenceName'];
    
                $classMetadata->setSequenceGeneratorDefinition($newDefinition);
                $em = $args->getEntityManager();
                if (isset($classMetadata->idGenerator)) {
                    $sequenceGenerator = new \Doctrine\ORM\Id\SequenceGenerator(
                        $em->getConfiguration()->getQuoteStrategy()->getSequenceName(
                            $newDefinition,
                            $classMetadata,
                            $em->getConnection()->getDatabasePlatform()),
                        $newDefinition['allocationSize']
                    );
                    $classMetadata->setIdGenerator($sequenceGenerator);
                }
            }
        }
    }
    

Riferimento:http://www .doctrine-project.org/api/orm/2.0/class-Doctrine.ORM.Mapping.ClassMetadataInfo.html

La documentazione dice READ-ONLY per la sequenceGeneratorDefinition proprietà quindi penso che sia più semplice usare il setter piuttosto che cambiare il valore manualmente (ma non c'è un getter, quindi usiamo solo il valore della proprietà pubblica).