Skip to content

Fix patternProperties/propertyNames key constraints lost with field_constraints#2994

Merged
koxudaxi merged 1 commit intomainfrom
fix/pattern-properties-field-constraints
Feb 14, 2026
Merged

Fix patternProperties/propertyNames key constraints lost with field_constraints#2994
koxudaxi merged 1 commit intomainfrom
fix/pattern-properties-field-constraints

Conversation

@koxudaxi
Copy link
Copy Markdown
Owner

@koxudaxi koxudaxi commented Feb 14, 2026

Fixes: #2988

Summary by CodeRabbit

Release Notes

  • New Features

    • Pattern constraints on dictionary keys are now consistently applied in all code generation modes, ensuring proper regex validation.
    • Generated code properly enforces regex patterns on dictionary keys through constrained string types.
  • Bug Fixes

    • Resolved inconsistent behavior where pattern constraints were not applied to dictionary keys in certain configurations.
  • Tests

    • Added comprehensive test cases for pattern properties with annotated types and field constraints to verify correct constraint application.

@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented Feb 14, 2026

📝 Walkthrough

Walkthrough

The changes fix a bug where pattern constraints on JSON schema dictionary keys (patternProperties and propertyNames) were not being preserved when using the --use-annotated option. The parser now consistently applies pattern constraints to dictionary key types regardless of field_constraints mode, with corresponding test fixtures demonstrating the corrected output.

Changes

Cohort / File(s) Summary
Parser Logic
src/datamodel_code_generator/parser/jsonschema.py
Modified parse_pattern_properties and parse_property_names to always apply pattern constraints to dict keys when present, removing the field_constraints gating condition.
Test Fixtures
tests/data/expected/main/jsonschema/pattern_properties_field_constraints.py, tests/data/expected/main/jsonschema/pattern_properties_use_annotated.py, tests/data/expected/main/jsonschema/property_names_pattern_field_constraints.py
New and updated expected output files showing pattern-constrained dict keys using constr() or Annotated types in Pydantic v2 models.
Test Coverage
tests/main/jsonschema/test_main_jsonschema.py
Added test test_jsonschema_pattern_properties_use_annotated to verify pattern constraints are preserved when using --use-annotated with patternProperties schema.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

  • #2770: Both PRs modify parse_pattern_properties to handle merged regex patterns for dict key types in patternProperties.
  • #2766: Both PRs modify patternProperties handling in the JSON schema parser, with overlapping changes to pattern constraint application logic.
  • #2824: Both PRs modify parse_property_names in the same file to alter how dictionary key type constraints are derived from propertyNames constraints.

Suggested labels

breaking-change-analyzed, breaking-change

Poem

🐰 Pattern guards now stand so tall,
Keys constrained through it all,
With --use-annotated we rejoice,
Regex patterns have their voice!
Bug squashed bright, the rules apply,
Hopping higher toward the sky! 🎉

🚥 Pre-merge checks | ✅ 5 | ❌ 1
❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Merge Conflict Detection ⚠️ Warning ❌ Merge conflicts detected (5 files):

⚔️ src/datamodel_code_generator/model/pydantic/base_model.py (content)
⚔️ src/datamodel_code_generator/parser/jsonschema.py (content)
⚔️ tests/data/expected/main/jsonschema/pattern_properties_field_constraints.py (content)
⚔️ tests/main/jsonschema/test_main_jsonschema.py (content)
⚔️ tests/main/test_dynamic_models.py (content)

These conflicts must be resolved before merging into main.
Resolve conflicts locally and push changes to this branch.
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately describes the main change: fixing preservation of patternProperties/propertyNames key constraints when using field_constraints mode.
Linked Issues check ✅ Passed The code changes directly address issue #2988 by ensuring pattern constraints are applied to dictionary keys even in field_constraints mode, implementing the fix to preserve key constraints with --use-annotated.
Out of Scope Changes check ✅ Passed All changes are directly related to fixing pattern constraints on dictionary keys in patternProperties/propertyNames; no unrelated modifications are present.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch fix/pattern-properties-field-constraints
⚔️ Resolve merge conflicts (beta)
  • Auto-commit resolved conflicts to branch fix/pattern-properties-field-constraints
  • Create stacked PR with resolved conflicts
  • Post resolved changes as copyable diffs in a comment

No actionable comments were generated in the recent review. 🎉


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@github-actions
Copy link
Copy Markdown
Contributor

@codecov
Copy link
Copy Markdown

codecov Bot commented Feb 14, 2026

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 100.00%. Comparing base (b58970a) to head (d488ad6).
⚠️ Report is 2 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff            @@
##              main     #2994   +/-   ##
=========================================
  Coverage   100.00%   100.00%           
=========================================
  Files           94        94           
  Lines        18051     18065   +14     
  Branches      2091      2090    -1     
=========================================
+ Hits         18051     18065   +14     
Flag Coverage Δ
unittests 100.00% <100.00%> (ø)

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@koxudaxi koxudaxi merged commit 0f1bc0f into main Feb 14, 2026
36 of 37 checks passed
@koxudaxi koxudaxi deleted the fix/pattern-properties-field-constraints branch February 14, 2026 05:16
@github-actions
Copy link
Copy Markdown
Contributor

Breaking Change Analysis

Result: No breaking changes detected

Reasoning: This PR is a bug fix that corrects inconsistent behavior where patternProperties and propertyNames constraints were incorrectly dropped when using --field-constraints or --use-annotated flags. Before the fix, dict[str, Bar] was incorrectly generated; after the fix, dict[constr(regex=...), Bar] is correctly generated. While this changes the generated output, it's a correctness fix rather than a breaking change - the previous behavior was a bug that silently dropped constraints that should have been preserved according to the JSON Schema. Users expecting the buggy behavior would see different output, but the new output correctly reflects what the schema specifies.


This analysis was performed by Claude Code Action

@github-actions
Copy link
Copy Markdown
Contributor

🎉 Released in 0.54.0

This PR is now available in the latest release. See the release notes for details.

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

patternProperties key constraints doesn't get preserved with --use-annotated

1 participant