-
-
Notifications
You must be signed in to change notification settings - Fork 56
feat(#410): add support for LTREE type.
#411
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from 21 commits
Commits
Show all changes
23 commits
Select commit
Hold shift + click to select a range
5d477bf
feat: add support for `ltree` type.
landure e87e243
fix: improve type validation in LtreeTypeTest
landure b9d1c46
fix: remove LtreeInterface interface
landure 2c08702
docs: fix fragile links and remove unique index on path
landure 2aed8a3
fix: rename tests to follow coding style
landure 94ea198
fix: remove equals() method
landure 69cac09
refactor: rename runTypeTest calls to runDbalBindingRoundTrip
landure 0dd55d4
feat: implement InvalidLtreeException for Ltree value object
landure 7d51c35
fix: fix Ltree type getSqlDeclaration() method to its parent in BaseT…
landure ff0187d
fix: fix Ltree exception text
landure dd8a0ee
fix: move extension activation logic to TestCase
landure c872af5
fix: remove checks for PostgreSQL platform
landure be99580
fix: remove redundant comments
landure 4d924c6
fix: reword gist and git index mention according to coderabbit recomm…
landure be43569
fix: fix minor copy paste residue
landure 745a434
fix: remove PHPMD annotation, and rephrase onFlush listener presentation
landure c104ce7
fix: add missing docblock with since version and author annotations
landure c271601
feat: add forImpossibleLtree() method.
landure 5b77b63
fix: fix getParent() method to throw InvalidLtreeException
landure 37a4a3f
fix: narrow catch clauses in convert methods and add docblock
landure 8f5c647
fix: add missing #[Test] attributes
landure 91e4e75
fix: replace static assertion for coding style respect
landure 8cc4dc7
fix: rename `throws_exception_when_getting_empty_ltree_parent` method
landure File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,221 @@ | ||
| # ltree type usage | ||
|
|
||
| ## Requirements | ||
|
|
||
| The `ltree` data type requires enabling the [`ltree` extension](https://www.postgresql.org/docs/16/ltree.html) | ||
| in PostgreSQL. | ||
|
|
||
| ```sql | ||
| CREATE EXTENSION IF NOT EXISTS ltree; | ||
| ``` | ||
|
|
||
| For [Symfony](https://symfony.com/), | ||
| customize the migration that introduces the `ltree` field by adding this line | ||
| at the beginning of the `up()` method: | ||
|
|
||
| ```php | ||
| $this->addSql('CREATE EXTENSION IF NOT EXISTS ltree'); | ||
| ``` | ||
|
|
||
| ## Usage | ||
|
|
||
| An example implementation (for a Symfony project) is: | ||
|
|
||
| ```php | ||
| <?php | ||
|
|
||
| declare(strict_types=1); | ||
|
|
||
| namespace App\Entity; | ||
|
|
||
| use Doctrine\Common\Collections\ArrayCollection; | ||
| use Doctrine\Common\Collections\Collection; | ||
| use Doctrine\ORM\Mapping as ORM; | ||
| use MartinGeorgiev\Doctrine\DBAL\Types\ValueObject\Ltree; | ||
| use Symfony\Bridge\Doctrine\Types\UuidType; | ||
| use Symfony\Component\Uid\Uuid; | ||
|
|
||
| /** | ||
| * Manually edit `my_entity_path_gist_idx` in migration to use GIST. | ||
| * Declaring the index using Doctrine attributes prevents its removal during migrations. | ||
| */ | ||
| #[ORM\Entity()] | ||
| #[ORM\Index(columns: ['path'], name: 'my_entity_path_gist_idx')] | ||
| class MyEntity implements \Stringable | ||
| { | ||
| #[ORM\Column(type: UuidType::NAME)] | ||
| #[ORM\GeneratedValue(strategy: 'NONE')] | ||
| #[ORM\Id()] | ||
| private Uuid $id; | ||
|
|
||
| #[ORM\Column(type: 'ltree')] | ||
| private Ltree $path; | ||
|
|
||
| /** | ||
| * @var Collection<array-key,MyEntity> $children | ||
| */ | ||
| #[ORM\OneToMany(targetEntity: MyEntity::class, mappedBy: 'parent')] | ||
| private Collection $children; | ||
|
|
||
| public function __construct( | ||
| #[ORM\Column(unique: true, length: 128)] | ||
| private string $name, | ||
|
|
||
| #[ORM\ManyToOne(targetEntity: MyEntity::class, inversedBy: 'children')] | ||
| private ?MyEntity $parent = null, | ||
| ) { | ||
| $this->id = Uuid::v7(); | ||
| $this->children = new ArrayCollection(); | ||
|
|
||
| $this->path = Ltree::fromString($this->id->toBase58()); | ||
| if ($parent instanceof MyEntity) { | ||
| // Initialize the path using the parent. | ||
| $this->setParent($parent); | ||
| } | ||
| } | ||
|
|
||
| #[\Override] | ||
| public function __toString(): string | ||
| { | ||
| return $this->name; | ||
| } | ||
|
|
||
| public function getId(): Uuid | ||
| { | ||
| return $this->id; | ||
| } | ||
|
|
||
| public function getParent(): ?MyEntity | ||
| { | ||
| return $this->parent; | ||
| } | ||
|
|
||
| public function getName(): string | ||
| { | ||
| return $this->name; | ||
| } | ||
|
|
||
| public function getPath(): Ltree | ||
| { | ||
| return $this->path; | ||
| } | ||
|
|
||
| /** | ||
| * @return Collection<array-key,MyEntity> | ||
| */ | ||
| public function getChildren(): Collection | ||
| { | ||
| return $this->children; | ||
| } | ||
|
|
||
| public function setName(string $name): void | ||
| { | ||
| $this->name = $name; | ||
| } | ||
|
|
||
| public function setParent(MyEntity $parent): void | ||
| { | ||
| if ($parent->getId()->equals($this->id)) { | ||
| throw new \InvalidArgumentException("Parent MyEntity can't be self"); | ||
| } | ||
|
|
||
| // Prevent cycles: the parent can't be a descendant of the current node. | ||
| if ($parent->getPath()->isDescendantOf($this->getPath())) { | ||
| throw new \InvalidArgumentException("Parent MyEntity can't be a descendant of the current MyEntity"); | ||
| } | ||
|
|
||
| $this->parent = $parent; | ||
|
|
||
| // Use withLeaf() to create a new Ltree instance | ||
| // with the parent's path and the current entity's ID. | ||
| $this->path = $parent->getPath()->withLeaf($this->id->toBase58()); | ||
| } | ||
| } | ||
| ``` | ||
|
|
||
| 🗃️ Doctrine's schema tool can't define PostgreSQL [GiST](https://www.postgresql.org/docs/16/gist.html) | ||
| or [GIN](https://www.postgresql.org/docs/16/gin.html) indexes with the required ltree operator classes. | ||
| Create the index via a manual `CREATE INDEX` statement in your migration: | ||
|
|
||
| ```sql | ||
| -- Example GiST index for ltree with a custom signature length (must be a multiple of 4) | ||
| CREATE INDEX my_entity_path_gist_idx | ||
| ON my_entity USING GIST (path gist_ltree_ops(siglen = 100)); | ||
| -- Alternative: GIN index for ltree | ||
| CREATE INDEX my_entity_path_gin_idx | ||
| ON my_entity USING GIN (path gin_ltree_ops); | ||
| ``` | ||
|
|
||
| ⚠️ **Important**: Changing an entity's parent requires cascading the change | ||
| to all its children. | ||
| This is not handled automatically by Doctrine. | ||
| Implement an [onFlush](https://www.doctrine-project.org/projects/doctrine-orm/en/3.3/reference/events.html#reference-events-on-flush) | ||
| [Doctrine entity listener](https://symfony.com/doc/7.3/doctrine/events.html#doctrine-lifecycle-listeners) | ||
| to handle updating the `path` column of the updated entity's children | ||
| when `path` is present in the change set: | ||
|
|
||
| ```php | ||
| <?php | ||
|
|
||
| declare(strict_types=1); | ||
|
|
||
| namespace App\EventListener; | ||
|
|
||
| use App\Entity\MyEntity; | ||
| use Doctrine\Bundle\DoctrineBundle\Attribute\AsDoctrineListener; | ||
| use Doctrine\ORM\Event\OnFlushEventArgs; | ||
| use Doctrine\ORM\Events; | ||
| use Doctrine\ORM\Mapping\ClassMetadata; | ||
| use Doctrine\ORM\UnitOfWork; | ||
|
|
||
| #[AsDoctrineListener(event: Events::onFlush, priority: 500, connection: 'default')] | ||
| final readonly class MyEntityOnFlushListener | ||
| { | ||
| public function onFlush(OnFlushEventArgs $eventArgs): void | ||
| { | ||
| $entityManager = $eventArgs->getObjectManager(); | ||
| $unitOfWork = $entityManager->getUnitOfWork(); | ||
| $entityMetadata = $entityManager->getClassMetadata(MyEntity::class); | ||
|
|
||
| foreach ($unitOfWork->getScheduledEntityUpdates() as $entity) { | ||
| $this->processEntity($entity, $entityMetadata, $unitOfWork); | ||
| } | ||
| } | ||
|
|
||
| /** | ||
| * @param ClassMetadata<MyEntity> $entityMetadata | ||
| */ | ||
| private function processEntity(object $entity, ClassMetadata $entityMetadata, UnitOfWork $unitOfWork): void | ||
| { | ||
| if (!$entity instanceof MyEntity) { | ||
| return; | ||
| } | ||
|
|
||
| $changeset = $unitOfWork->getEntityChangeSet($entity); | ||
|
|
||
| // check if $entity->path has changed | ||
| // If the path stays the same, no need to update children | ||
| if (!isset($changeset['path'])) { | ||
| return; | ||
| } | ||
|
|
||
| $this->updateChildrenPaths($entity, $entityMetadata, $unitOfWork); | ||
| } | ||
|
|
||
| /** | ||
| * @param ClassMetadata<MyEntity> $entityMetadata | ||
| */ | ||
| private function updateChildrenPaths(MyEntity $entity, ClassMetadata $entityMetadata, UnitOfWork $unitOfWork): void | ||
| { | ||
| foreach ($entity->getChildren() as $child) { | ||
| // call the setParent method on the child, which recomputes its Ltree path. | ||
| $child->setParent($entity); | ||
|
|
||
| $unitOfWork->recomputeSingleEntityChangeSet($entityMetadata, $child); | ||
|
|
||
| // cascade the update to the child's children | ||
| $this->updateChildrenPaths($child, $entityMetadata, $unitOfWork); | ||
| } | ||
| } | ||
| } | ||
| ``` | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.