feat: add choices to strings to enable literal types by MaximSrour · Pull Request #1580 · ormar-orm/ormar

Summary

Enables ormar.String to preserve string literal typing when choices are provided, while keeping the underlying database column as sqlalchemy.String.

Closes #1579.

Changes

  • update ormar.String to project a typing.Literal[...] pydantic type when string choices are provided
  • preserve nullable behavior for String(..., choices=..., nullable=True) by wrapping the projected type in Optional[...]
  • keep normal String behavior unchanged when choices are not provided
  • add/adjust tests for:
    • runtime validation of String(..., choices=...)
    • nullable string choices
    • generated JSON schema for string choices fields
  • update field documentation to describe String and String(..., choices=...) in a single section

Testing

Built and ran targetted tests for the new changes, and ran tests against the entire suite. All passing.

Installed a local version of ORMAR into a personal repository that uses it, and tested against existing type errors.

Screenshots

Error before:
image

Using the new literal inference:
image