|
| 1 | +# ltree type usage |
| 2 | + |
| 3 | +## Requirements |
| 4 | + |
| 5 | +The `ltree` data type requires enabling the [`ltree` extension](https://www.postgresql.org/docs/16/ltree.html) |
| 6 | +in PostgreSQL. |
| 7 | + |
| 8 | +```sql |
| 9 | +CREATE EXTENSION IF NOT EXISTS ltree; |
| 10 | +``` |
| 11 | + |
| 12 | +For [Symfony](https://symfony.com/), |
| 13 | +customize the migration that introduces the `ltree` field by adding this line |
| 14 | +at the beginning of the `up()` method: |
| 15 | + |
| 16 | +```php |
| 17 | +$this->addSql('CREATE EXTENSION IF NOT EXISTS ltree'); |
| 18 | +``` |
| 19 | + |
| 20 | +## Usage |
| 21 | + |
| 22 | +An example implementation (for a Symfony project) is: |
| 23 | + |
| 24 | +```php |
| 25 | +<?php |
| 26 | + |
| 27 | +declare(strict_types=1); |
| 28 | + |
| 29 | +namespace App\Entity; |
| 30 | + |
| 31 | +use Doctrine\Common\Collections\ArrayCollection; |
| 32 | +use Doctrine\Common\Collections\Collection; |
| 33 | +use Doctrine\ORM\Mapping as ORM; |
| 34 | +use MartinGeorgiev\Doctrine\DBAL\Types\ValueObject\Ltree; |
| 35 | +use Symfony\Bridge\Doctrine\Types\UuidType; |
| 36 | +use Symfony\Component\Uid\Uuid; |
| 37 | + |
| 38 | +/** |
| 39 | + * Manually edit `my_entity_path_gist_idx` in migration to use GIST. |
| 40 | + * Declaring the index using Doctrine attributes prevents its removal during migrations. |
| 41 | + */ |
| 42 | +#[ORM\Entity()] |
| 43 | +#[ORM\Index(columns: ['path'], name: 'my_entity_path_gist_idx')] |
| 44 | +class MyEntity implements \Stringable |
| 45 | +{ |
| 46 | + #[ORM\Column(type: UuidType::NAME)] |
| 47 | + #[ORM\GeneratedValue(strategy: 'NONE')] |
| 48 | + #[ORM\Id()] |
| 49 | + private Uuid $id; |
| 50 | + |
| 51 | + #[ORM\Column(type: 'ltree')] |
| 52 | + private Ltree $path; |
| 53 | + |
| 54 | + /** |
| 55 | + * @var Collection<array-key,MyEntity> $children |
| 56 | + */ |
| 57 | + #[ORM\OneToMany(targetEntity: MyEntity::class, mappedBy: 'parent')] |
| 58 | + private Collection $children; |
| 59 | + |
| 60 | + public function __construct( |
| 61 | + #[ORM\Column(unique: true, length: 128)] |
| 62 | + private string $name, |
| 63 | + |
| 64 | + #[ORM\ManyToOne(targetEntity: MyEntity::class, inversedBy: 'children')] |
| 65 | + private ?MyEntity $parent = null, |
| 66 | + ) { |
| 67 | + $this->id = Uuid::v7(); |
| 68 | + $this->children = new ArrayCollection(); |
| 69 | + |
| 70 | + $this->path = Ltree::fromString($this->id->toBase58()); |
| 71 | + if ($parent instanceof MyEntity) { |
| 72 | + // Initialize the path using the parent. |
| 73 | + $this->setParent($parent); |
| 74 | + } |
| 75 | + } |
| 76 | + |
| 77 | + #[\Override] |
| 78 | + public function __toString(): string |
| 79 | + { |
| 80 | + return $this->name; |
| 81 | + } |
| 82 | + |
| 83 | + public function getId(): Uuid |
| 84 | + { |
| 85 | + return $this->id; |
| 86 | + } |
| 87 | + |
| 88 | + public function getParent(): ?MyEntity |
| 89 | + { |
| 90 | + return $this->parent; |
| 91 | + } |
| 92 | + |
| 93 | + public function getName(): string |
| 94 | + { |
| 95 | + return $this->name; |
| 96 | + } |
| 97 | + |
| 98 | + public function getPath(): Ltree |
| 99 | + { |
| 100 | + return $this->path; |
| 101 | + } |
| 102 | + |
| 103 | + /** |
| 104 | + * @return Collection<array-key,MyEntity> |
| 105 | + */ |
| 106 | + public function getChildren(): Collection |
| 107 | + { |
| 108 | + return $this->children; |
| 109 | + } |
| 110 | + |
| 111 | + public function setName(string $name): void |
| 112 | + { |
| 113 | + $this->name = $name; |
| 114 | + } |
| 115 | + |
| 116 | + public function setParent(MyEntity $parent): void |
| 117 | + { |
| 118 | + if ($parent->getId()->equals($this->id)) { |
| 119 | + throw new \InvalidArgumentException("Parent MyEntity can't be self"); |
| 120 | + } |
| 121 | + |
| 122 | + // Prevent cycles: the parent can't be a descendant of the current node. |
| 123 | + if ($parent->getPath()->isDescendantOf($this->getPath())) { |
| 124 | + throw new \InvalidArgumentException("Parent MyEntity can't be a descendant of the current MyEntity"); |
| 125 | + } |
| 126 | + |
| 127 | + $this->parent = $parent; |
| 128 | + |
| 129 | + // Use withLeaf() to create a new Ltree instance |
| 130 | + // with the parent's path and the current entity's ID. |
| 131 | + $this->path = $parent->getPath()->withLeaf($this->id->toBase58()); |
| 132 | + } |
| 133 | +} |
| 134 | +``` |
| 135 | + |
| 136 | +🗃️ Doctrine's schema tool can't define PostgreSQL [GiST](https://www.postgresql.org/docs/16/gist.html) |
| 137 | +or [GIN](https://www.postgresql.org/docs/16/gin.html) indexes with the required ltree operator classes. |
| 138 | +Create the index via a manual `CREATE INDEX` statement in your migration: |
| 139 | + |
| 140 | +```sql |
| 141 | +-- Example GiST index for ltree with a custom signature length (must be a multiple of 4) |
| 142 | +CREATE INDEX my_entity_path_gist_idx |
| 143 | + ON my_entity USING GIST (path gist_ltree_ops(siglen = 100)); |
| 144 | +-- Alternative: GIN index for ltree |
| 145 | +CREATE INDEX my_entity_path_gin_idx |
| 146 | + ON my_entity USING GIN (path gin_ltree_ops); |
| 147 | +``` |
| 148 | + |
| 149 | +⚠️ **Important**: Changing an entity's parent requires cascading the change |
| 150 | +to all its children. |
| 151 | +This is not handled automatically by Doctrine. |
| 152 | +Implement an [onFlush](https://www.doctrine-project.org/projects/doctrine-orm/en/3.3/reference/events.html#reference-events-on-flush) |
| 153 | +[Doctrine entity listener](https://symfony.com/doc/7.3/doctrine/events.html#doctrine-lifecycle-listeners) |
| 154 | +to handle updating the `path` column of the updated entity's children |
| 155 | +when `path` is present in the change set: |
| 156 | + |
| 157 | +```php |
| 158 | +<?php |
| 159 | + |
| 160 | +declare(strict_types=1); |
| 161 | + |
| 162 | +namespace App\EventListener; |
| 163 | + |
| 164 | +use App\Entity\MyEntity; |
| 165 | +use Doctrine\Bundle\DoctrineBundle\Attribute\AsDoctrineListener; |
| 166 | +use Doctrine\ORM\Event\OnFlushEventArgs; |
| 167 | +use Doctrine\ORM\Events; |
| 168 | +use Doctrine\ORM\Mapping\ClassMetadata; |
| 169 | +use Doctrine\ORM\UnitOfWork; |
| 170 | + |
| 171 | +#[AsDoctrineListener(event: Events::onFlush, priority: 500, connection: 'default')] |
| 172 | +final readonly class MyEntityOnFlushListener |
| 173 | +{ |
| 174 | + public function onFlush(OnFlushEventArgs $eventArgs): void |
| 175 | + { |
| 176 | + $entityManager = $eventArgs->getObjectManager(); |
| 177 | + $unitOfWork = $entityManager->getUnitOfWork(); |
| 178 | + $entityMetadata = $entityManager->getClassMetadata(MyEntity::class); |
| 179 | + |
| 180 | + foreach ($unitOfWork->getScheduledEntityUpdates() as $entity) { |
| 181 | + $this->processEntity($entity, $entityMetadata, $unitOfWork); |
| 182 | + } |
| 183 | + } |
| 184 | + |
| 185 | + /** |
| 186 | + * @param ClassMetadata<MyEntity> $entityMetadata |
| 187 | + */ |
| 188 | + private function processEntity(object $entity, ClassMetadata $entityMetadata, UnitOfWork $unitOfWork): void |
| 189 | + { |
| 190 | + if (!$entity instanceof MyEntity) { |
| 191 | + return; |
| 192 | + } |
| 193 | + |
| 194 | + $changeset = $unitOfWork->getEntityChangeSet($entity); |
| 195 | + |
| 196 | + // check if $entity->path has changed |
| 197 | + // If the path stays the same, no need to update children |
| 198 | + if (!isset($changeset['path'])) { |
| 199 | + return; |
| 200 | + } |
| 201 | + |
| 202 | + $this->updateChildrenPaths($entity, $entityMetadata, $unitOfWork); |
| 203 | + } |
| 204 | + |
| 205 | + /** |
| 206 | + * @param ClassMetadata<MyEntity> $entityMetadata |
| 207 | + */ |
| 208 | + private function updateChildrenPaths(MyEntity $entity, ClassMetadata $entityMetadata, UnitOfWork $unitOfWork): void |
| 209 | + { |
| 210 | + foreach ($entity->getChildren() as $child) { |
| 211 | + // call the setParent method on the child, which recomputes its Ltree path. |
| 212 | + $child->setParent($entity); |
| 213 | + |
| 214 | + $unitOfWork->recomputeSingleEntityChangeSet($entityMetadata, $child); |
| 215 | + |
| 216 | + // cascade the update to the child's children |
| 217 | + $this->updateChildrenPaths($child, $entityMetadata, $unitOfWork); |
| 218 | + } |
| 219 | + } |
| 220 | +} |
| 221 | +``` |
0 commit comments