user2560652
user2560652

Reputation:

Symfony2 Doctrine custom types generating unneeded migrations

I have created a custom doctrine type as told in http://doctrine-orm.readthedocs.org/en/latest/cookbook/working-with-datetime.html

Here is the code:

<?php

namespace XXX\Bundle\XXXBundle\Doctrine\Type;

use Doctrine\DBAL\Platforms\AbstractPlatform;
use Doctrine\DBAL\Types\ConversionException;
use Doctrine\DBAL\Types\DateTimeType;

class UTCDateTimeType extends DateTimeType
{
    static private $utc = null;

    public function convertToDatabaseValue($value, AbstractPlatform $platform)
    {
        if ($value === null) {
            return null;
        }

        $value->setTimezone(new \DateTimeZone('UTC'));
        $dbDate = $value->format($platform->getDateTimeFormatString());

        return $dbDate;
    }

    public function convertToPHPValue($value, AbstractPlatform $platform)
    {
        if ($value === null) {
            return null;
        }

        $val = \DateTime::createFromFormat(
            $platform->getDateTimeFormatString(),
            $value,
            (self::$utc) ? self::$utc : (self::$utc = new \DateTimeZone('UTC'))
        );
        if (!$val) {
            throw ConversionException::conversionFailed($value, $this->getName());
        }
        return $val;
    }
}

The problem is when I run app/console doctrine:migrations:diff it always will generate new migrations even if I have migrated, and the content is always the same. Example:

$this->addSql('ALTER TABLE Availability CHANGE start start DATETIME NOT NULL, CHANGE end end DATETIME NOT NULL, CHANGE rrule rrule LONGTEXT DEFAULT NULL, CHANGE created created DATETIME NOT NULL, CHANGE updated updated DATETIME NOT NULL');

Upvotes: 10

Views: 2658

Answers (1)

Nico
Nico

Reputation: 6913

Here is a response from Steve Müller from this bug report : http://www.doctrine-project.org/jira/browse/DBAL-1085

I think you will have to mark your custom type as requiring a SQL comment, otherwise the schema manager cannot distinguish between DateTime type and your custom type because both map to the same native SQL type.

See here: https://github.com/doctrine/dbal/blob/master/lib/Doctrine/DBAL/Types/Type.php#L327-L340

You will have to add the following to your custom type implementation:

/**
 * {@inheritdoc}
 */
public function requiresSQLCommentHint(AbstractPlatform $platform)
{
    return true;
}

Also I think it might be required to give your custom type a distinct name like:

/**
 * {@inheritdoc}
 */
public function getName()
{
    return 'datetime_utc';
}

There features are implemented in doctrine >=2.3

Upvotes: 15

Related Questions