jsor / doctrine-postgis

Spatial and Geographic Data with PostGIS and Doctrine.
MIT License
209 stars 50 forks source link

The type of a spatial column cannot be changed #58

Closed Carameil closed 1 year ago

Carameil commented 1 year ago

Hi! I have custom type for doctrine, which extends from Jsor\Doctrine\PostGIS\Types\GeometryType:

<?php

namespace App\Entity\PropertyType;

use Doctrine\DBAL\Platforms\AbstractPlatform;
use Jsor\Doctrine\PostGIS\Types\GeometryType;

class PointType extends GeometryType
{
    public const POINT = 'point_type';

    public function convertToPHPValue($value, AbstractPlatform $platform): ?Point
    {
        if ($value === null) {
            return null;
        }
        $pattern = '/POINT\(([-]?[0-9]+[.]?[0-9]*) ([-]?[0-9]+[.]?[0-9]*)\)/';

        if (preg_match($pattern, $value, $matches)) {
            $latitude = (float) $matches[1];
            $longitude = (float) $matches[2];

            return new Point($latitude, $longitude);
        } else {
            throw new \DomainException('Incorrect string');
        }
    }

    public function convertToDatabaseValue($value, AbstractPlatform $platform): ?string
    {
        /** @var Point $value */
        if ($value === null) {
            return null;
        }
        return sprintf('POINT(%f %f)', $value->getLatitude(), $value->getLongitude());
    }

    public function requiresSQLCommentHint(AbstractPlatform $platform): bool
    {
        return true;
    }
}

My Entity field:

    #[ORM\Column(type: PointType::POINT, nullable: true)]
    protected ?Point $centerLocation = null;

When I create the first migration - it's ok, but if I try to work with my DB (update, new migrations, diff) then I get error: The type of a spatial column cannot be changed (Requested changing type from "geometry" to "geometry" for column "center_location" in table "parking")

Has anyone encountered this? Any idea how to fix it? I would be grateful for your answers

jsor commented 1 year ago

You need to implement the getName()method. Here's a cookbook article from the Doctrine docs: https://www.doctrine-project.org/projects/doctrine-orm/en/2.14/cookbook/advanced-field-value-conversion-using-custom-mapping-types.html#advanced-field-value-conversion-using-custom-mapping-types