feat: add choices to strings to enable literal types#1580
feat: add choices to strings to enable literal types#1580MaximSrour wants to merge 2 commits intoormar-orm:masterfrom
Conversation
Merging this PR will degrade performance by 23.72%
Performance Changes
Comparing Footnotes |
|
Any particural reason why you dont want to use EnumField here? |
I wrote about it a bit in the linked issue, but it mostly comes down to flexibility - with an enum, I'd need to push a migration to update the column type (which can take a while when there are a lot of records), after which I'll be able to use the new value. With a string column instead, the code can immediately start using the new values. |
|
We used to have If we would like to restore it as Note also that you now overwrite the |
Ah, it was removed a bit before I had started using ORMAR, so I was never aware that it was even a feature in the first place. I imagine that it was removed for a good reason, so it may be unwise to just add it back in. That's fine though, this PR was just a quick attempt to see if it was an quick and easy fix.
I noted that Unless you mean that the
Ah, interesting, I'd need to investigate this, but good catch. Either way, I'm fine with this PR (and the linked issue) being closed, since the desired feature was removed in the first place. Ultimately up to you. |
|
To be honest I dont remember why it was removed now 😅 Might have been an issue with the implementation not working with pydantic 2.0. It was not using the literals for sure. I guess we could restore it - as the lack of migration is a valid benefit for that use case, but as I mentioned in the comment, then we should make it generic for all column types in ormar so choices can be applied also on ints or other types. |
|
Lol, no worries. Gimme a couple of weeks to find the time, and I'll get this one resolved 🤞 |
Summary
Enables
ormar.Stringto preserve string literal typing whenchoicesare provided, while keeping the underlying database column assqlalchemy.String.Closes #1579.
Changes
ormar.Stringto project atyping.Literal[...]pydantic type when stringchoicesare providedString(..., choices=..., nullable=True)by wrapping the projected type inOptional[...]Stringbehavior unchanged whenchoicesare not providedString(..., choices=...)StringandString(..., choices=...)in a single sectionTesting
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:

Using the new literal inference:
