Skip to content

Store the tags of parts as entities of their own - #1672

Open
killecaptron wants to merge 4 commits into
Part-DB:masterfrom
killecaptron:tag-entities
Open

killecaptron wants to merge 4 commits into
Part-DB:masterfrom
killecaptron:tag-entities

Conversation

@killecaptron

Copy link
Copy Markdown
Contributor

In #1640 you mentioned that you plan to move tags to common global tag entities. We needed that too, so I implemented it. It has been running on our test instance (a copy of our production data, PostgreSQL) for a few days. This PR is meant as a proposal: if you have something different in mind, I'm happy to rework it to your liking. That also applies to the design decisions listed below.

Supersedes #1640 (tag style rules); with tag entities, the color simply sits on the tag.

What changes

Parts now refer to shared Tag entities instead of a comma-separated text column. Tags are a data structure like the custom part states:

  • Managed under Tools → Edit → Tags, with comment, alternative names, attachments, parameters and a color (the same Bootstrap colors as the part states). Renaming a tag renames it on all parts.
  • Tags can be nested. A tag without its own color inherits the color of its parent. The sidebar gets a tags tree, and the part list of a tag includes the tags below it if the sidebar is configured to include children.
  • When a tag input (part form or tag filter) gets the focus, it offers all existing tags (new endpoint /typeahead/tags/all).

Backwards compatibility

  • The API, import/export, the MCP tools, the part form and the info providers keep working with the comma-separated list of names. setTags() assigns tags by name; a Doctrine listener (TagAssignmentListener) replaces new tags with the existing tag of the same name before they are written.
  • Tags are also exposed as a resource of their own under /api/tags (with the MCP tools list_tags and get_tag_details).
  • Changing only the tags of a part still updates its modification date and is logged as before, in the comma-separated form, so time travel works for old and new log entries.
  • The filters, the search, the tag autocompletion and the API tag filter query the tags through subqueries, so these queries don't need an additional join.

Migration

Version20261123120000 moves the existing tags into the new tables tags and parts_tags, merges names that differ only in case or whitespace, and drops the old parts.tags column. The down migration restores the column from the tags. There are migrations for MySQL, SQLite and PostgreSQL. We ran the data migration on PostgreSQL, with our production data, and the test suite on SQLite. I haven't run the MySQL migration against a real MySQL server, only through the CI here.

Design decisions you may want to change

  1. Tag names are unique globally (not only among siblings like for the other data structures), because tags are still assigned by their name. Names are compared case-insensitively ("SMD" and "smd" are one tag, which also fixes the inconsistency between search and filters from Tags are created case-sensitive but tag filters are case-insensitive #1269).
  2. New tags permission with the same operations as the other data structures (PART_CONTAINING). The permission schema update (version 5) derives it from the part permissions, since everybody who could edit parts could change tags so far. Alternatively, tag management could simply follow the part permissions.
  3. The old column is dropped instead of being kept as a cache.

Other

  • The first commit fixes the purger of the fixtures command: it still treated association mappings as arrays (pre-ORM 3). Part-DB had no many-to-many association so far, so it never showed up; with one, loading the fixtures fails with a TypeError. I can split it off into its own PR if you prefer.
  • Only the English translations are included; the rest goes through Crowdin.
  • Tests: new tests for the entity, the repository, the listener, the filters, the admin page and the API endpoint; the full test suite and PHPStan pass.

Side note: I also have a "saved filters" feature (named filter combinations under "Show", as discussed in #1087), which I'd like to submit separately. It bumps the permission schema as well, so whichever of the two is merged second needs to renumber its schema update.

🤖 Generated with Claude Code

@greptile-apps

greptile-apps Bot commented Nov 26, 2026 •

Copy link
Copy Markdown
Contributor

Confidence Score: 2/5 · Do not merge yet: competing tag saves, MySQL accent variants, and merged long tag names still need fixes.RetriggerView in GreptileConfidence Score: 2/5 Tier: plus

[High impact] The change reaches part records and several ways people manage and find them.

Do not merge yet: competing tag saves, MySQL accent variants, and merged long tag names still need fixes.

FindingsFix All in Claude CodeFindings

  1. P1 Concurrent tag saves collide ▶
  2. P1 New accent variants collide ▶
  3. P1 Upgrade shortens stored tags ▶
Fix with agent prompt
### Issue 1
src/EntityListeners/TagAssignmentListener.php:88-92
Two requests adding the same new tag can both pass this lookup before either inserts it. One then fails on `tag_name_unique`, aborting a valid part save or import. On PostgreSQL, differently cased names can instead both be inserted because the index is case-sensitive. Resolve new names atomically in the database, with matching case-insensitive uniqueness and recovery from competing inserts.

### Issue 2
src/EntityListeners/TagAssignmentListener.php:79-80
On MySQL, adding both `cafe` and `café` in one flush fails when neither tag exists yet. They have different `nameKey()` values, so the listener keeps both inserts. The `utf8mb4_unicode_ci` unique index treats them as equal and rejects the save. Compare pending names using the database's equality rules before keeping both inserts.

### Issue 3
migrations/Version20261123120000.php:undefined-196
The upgrade silently cuts existing tag names to 255 characters. The old text field and part form allowed longer names, so this loses valid stored data. Distinct names sharing that prefix are also merged permanently when the old column is dropped. Preserve those names, or stop with an actionable error before changing the schema.

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

Summary

Moves part tags into shared Tag entities while keeping comma-separated names for existing callers.

  • Parts now share tag records while keeping the existing name-based interface.
  • People can manage shared tags and access them through a separate API.
  • Part lists search, filter, and sort using shared tag names.
  • People can browse tags as a tree and pick existing names from suggestions.
  • Fixture cleanup recognizes the ORM’s many-to-many mapping objects.

Tests and visual checks were not run because PHP and installed application dependencies are unavailable.

Diagram

%%{init: {'theme': 'neutral'}}%%
flowchart TD
    A["Part form, API, or import"] --> B["Part::setTags()"]
    B --> C["Temporary tags for supplied names"]
    C --> D["TagAssignmentListener"]
    D --> E["Reuse or create shared Tag"]
    E --> F["Write parts_tags links"]
    G["Tag admin page"] --> E
    H["API tag deletion"] --> I{"Assigned to a part?"}
    I -- Yes --> J["Return conflict"]
    I -- No --> K["Normal removal"]
Loading

Reviews (2) · Last reviewed commit: "Address the review of the tag entities" · Reviewed by Greptile

Comment thread src/Repository/Parts/TagRepository.php Resolved
Comment thread src/DataTables/PartsDataTable.php Resolved
Comment on lines +78 to +82
foreach ($newTags as $oid => $tag) {
$key = Tag::nameKey($tag->getName());
$canonical[$key] ??= $repo->findOneByName($tag->getName()) ?? $tag;
if ($canonical[$key] !== $tag) {
$replacements[$oid] = $canonical[$key];

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Concurrent tag saves collide

Two requests adding the same new tag can both pass this lookup before either inserts it. One then fails on tag_name_unique, aborting a valid part save or import. On PostgreSQL, differently cased names can instead both be inserted because the index is case-sensitive. Resolve new names atomically in the database, with matching case-insensitive uniqueness and recovery from competing inserts.

Prompt To Fix With AI
This is a comment left during a code review.
Path: src/EntityListeners/TagAssignmentListener.php
Line: 78-82

Comment:
**Concurrent tag saves collide**

Two requests adding the same new tag can both pass this lookup before either inserts it. One then fails on `tag_name_unique`, aborting a valid part save or import. On PostgreSQL, differently cased names can instead both be inserted because the index is case-sensitive. Resolve new names atomically in the database, with matching case-insensitive uniqueness and recovery from competing inserts.

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

Fix in Claude Code

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Partly addressed. With the unique index on the name key, the database now rejects case variants on all platforms, so two concurrent requests can't create "SMD" and "smd" as two tags anymore. If two requests create the same new tag at the very same moment, one of them fails with a constraint violation and has to be repeated. I haven't added a retry for that, as it needs the same tag to be new in two parallel saves, and nothing gets inconsistent. Happy to add one if you think it's worth it.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks — the unique name-key index addresses the case-variant duplicate I called out. The remaining race still means one otherwise-valid part save (or import transaction) can fail; the constraint protects consistency, but doesn’t make that save succeed.

I think recovery is worthwhile if concurrent saves/imports are expected in normal use, though I wouldn’t treat this as a data-integrity blocker. It should happen at the transaction boundary: retry the whole operation after the unique-key violation with a fresh EntityManager so the assignment listener can resolve the tag that won the race. A retry inside this listener would be too late once flush() has failed. If the race is sufficiently rare and the failure is clearly surfaced as retryable, documenting it and deferring automatic retry is also reasonable.

Comment on lines +79 to +80
$key = Tag::nameKey($tag->getName());
$canonical[$key] ??= $repo->findOneByName($tag->getName()) ?? $tag;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 New accent variants collide

On MySQL, adding both cafe and café in one flush fails when neither tag exists yet. They have different nameKey() values, so the listener keeps both inserts. The utf8mb4_unicode_ci unique index treats them as equal and rejects the save. Compare pending names using the database's equality rules before keeping both inserts.

Prompt To Fix With AI
This is a comment left during a code review.
Path: src/EntityListeners/TagAssignmentListener.php
Line: 79-80

Comment:
**New accent variants collide**

On MySQL, adding both `cafe` and `café` in one flush fails when neither tag exists yet. They have different `nameKey()` values, so the listener keeps both inserts. The `utf8mb4_unicode_ci` unique index treats them as equal and rejects the save. Compare pending names using the database's equality rules before keeping both inserts.

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

Fix in Claude Code

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This only happens on MySQL: its collation also treats keys which differ only in accents as equal. Across saves, the existing tag is reused, as the lookup is done by the database. Only if cafe and café are both new in the same save, the second insert fails. I've left it like this, as the collation decides the same way for all other names on MySQL. If you prefer accent-sensitive tags on MySQL too, the MySQL migration could give name_key a binary collation.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for clarifying. Since accent-insensitive equality is intentional on MySQL and the same-flush collision is an accepted edge case, I’m happy to leave this as-is; a binary collation would only be needed if accent-sensitive tag names were desired.

Comment thread migrations/Version20261123120000.php Resolved
Comment thread src/Entity/Parts/Tag.php Resolved
Comment thread src/Entity/Parts/Tag.php Resolved
Comment thread migrations/Version20261123120000.php Resolved
killecaptron and others added 4 commits November 30, 2026 08:19
The purger used by the fixtures command still treated association mappings
as arrays, as they were before Doctrine ORM 3. As Part-DB had no
many-to-many association until now, getJoinTableName() was never called and
nobody noticed; with one, purging fails with a TypeError.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Tags were a comma-separated text on every part, so a tag could not be
renamed, styled or grouped, and "SMD" and "smd" were two tags for the
search, but one for the filters (Part-DB#1269).

Now parts refer to shared Tag entities, which are a data structure like
the custom part states:

* Tags are managed under Tools -> Edit -> Tags: renaming a tag renames it on
  all parts, and a tag has a comment, alternative names, attachments and a
  color (the same Bootstrap colors as the custom part states).
* Tags can be grouped below other tags. A tag without a color of its own
  takes the color of the tag above it, and the sidebar has a tags tree. The
  part list of a tag includes the tags below it, if the sidebar is
  configured to include children.
* Unlike for the other data structures, a tag name is unique across all
  tags, not only among the siblings, as tags are still assigned by their
  names. Names are compared case-insensitively.
* The API, the import and export, the MCP tools, the part form and the info
  providers keep working with the comma-separated list of names: setTags()
  assigns tags by name and a doctrine listener replaces new tags by the
  existing tag of that name before they are written. Tags are also exposed
  as a resource of their own under /api/tags, with MCP tools to list them.
* Changing only the tags of a part still updates its modification date and
  is logged like before, in the same comma-separated form, so time travel
  works for old and new log entries.
* The filters, the search, the tag autocompletion and the API tag filter
  query the tag entities through subqueries, so the queries using them do
  not need an additional join.
* A new "tags" permission controls the management of tags. The permission
  schema update derives it from the part permissions, as everybody who could
  edit parts could change tags so far.

The migration moves the existing tags into the new tables, merging names
which only differ in case or whitespace, and drops the old column. Its down
migration restores the column from the tags.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The tag inputs of the part form and of the tag filter only suggested tags
after two characters were typed, so the existing tags could not be seen
without knowing how they begin. Now that tags are entities of their own,
their names are offered as soon as the input gets the focus, via a new
typeahead endpoint returning all tag names. Typing still narrows the list
down and new tags can still be entered.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- Store the key of each tag name (its Unicode case folding) in a unique
  column and compare names by it. SQLite's LOWER() only knows ASCII, so
  tags like "Über" were not found again, and PostgreSQL and SQLite did not
  enforce the case-insensitive uniqueness themselves.
- Sort the part table by tags through a subquery instead of a join, which
  repeated the rows counted by the lot, attachment and other count filters.
- Only replace the tags created by Part::setTags() with existing tags, so
  tags created otherwise (e.g. with children) are never detached.
- Validate the length of the tag names assigned to a part.
- Reject deleting a tag through the API while it is assigned to parts, like
  the admin pages do, as the assignments could not be restored by undo.
- Show the parameters tab of tags.
- Migration: work in batches, keep names longer than 255 characters in the
  comment of their tag, and raise group_concat_max_len in the MySQL rollback.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@killecaptron

Copy link
Copy Markdown
Contributor Author

I've gone through the review and pushed the fixes:

  • Every tag has a name_key column now (the Unicode case folding of its name), which is unique and used for all lookups. This fixes non-ASCII tags on SQLite, and makes the case-insensitive uniqueness a database constraint on all platforms.
  • Sorting by tags uses a subquery instead of a join, so it doesn't affect the count filters anymore.
  • Only the tags created by Part::setTags() are replaced with existing tags; tags created otherwise are left alone.
  • Parts validate the length of their tag names; deleting a tag that is still assigned is rejected in the API, like on the admin pages.
  • The migration works in batches, keeps names longer than 255 characters in the tag comment, and the MySQL rollback raises group_concat_max_len.
  • The parameters tab of tags is shown.

I've added tests for each of these, and tested the migration up and down with SQLite on old data (1200 parts, umlauts, case variants, names over 255 characters). I've also rebased the branch onto the current master; TagsConstraintTest from master now runs against part.tagEntities.

The updated Greptile summary still lists three issues. Two of them are the ones I answered inline (concurrent saves and cafe/café on MySQL); its text partly refers to the previous commit, though: the tag_name_unique index and the case-sensitive index on PostgreSQL don't exist anymore. The third one is the shortening of names longer than 255 characters: the migration keeps the full names in the tag comment now, but it still has to shorten the name itself. If you'd rather have the migration stop with an error in that case, I can change it to do so.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant