summaryrefslogtreecommitdiff
path: root/lib/sqlalchemy/orm/util.py
diff options
context:
space:
mode:
authorMike Bayer <mike_mp@zzzcomputing.com>2022-11-21 09:46:43 -0500
committerMike Bayer <mike_mp@zzzcomputing.com>2022-11-22 09:49:02 -0500
commit509ffeedefca1ad0ad8e29c6c3410d270fb3d2b9 (patch)
treebfa5022ae1de59d90830241b99b10e80ea0b5c62 /lib/sqlalchemy/orm/util.py
parent46e6693cb3db445f18aa25d5e4ca613504bd12b3 (diff)
downloadsqlalchemy-509ffeedefca1ad0ad8e29c6c3410d270fb3d2b9.tar.gz
fix optionalized forms for dict[]
Fixed a suite of issues involving :class:`.Mapped` use with dictionary types, such as ``Mapped[dict[str, str] | None]``, would not be correctly interpreted in Declarative ORM mappings. Support to correctly "de-optionalize" this type including for lookup in type_annotation_map has been fixed. Fixes: #8777 Change-Id: Iaba90791dea341d00eaff788d40b0a4e48dab02e
Diffstat (limited to 'lib/sqlalchemy/orm/util.py')
-rw-r--r--lib/sqlalchemy/orm/util.py23
1 files changed, 20 insertions, 3 deletions
diff --git a/lib/sqlalchemy/orm/util.py b/lib/sqlalchemy/orm/util.py
index e5bdbaa4f..06f2d6d1d 100644
--- a/lib/sqlalchemy/orm/util.py
+++ b/lib/sqlalchemy/orm/util.py
@@ -2097,13 +2097,30 @@ def _cleanup_mapped_str_annotation(
stack.append(g2)
break
- # stack: ['Mapped', 'List', 'Address']
- if not re.match(r"""^["'].*["']$""", stack[-1]):
+ # stacks we want to rewrite, that is, quote the last entry which
+ # we think is a relationship class name:
+ #
+ # ['Mapped', 'List', 'Address']
+ # ['Mapped', 'A']
+ #
+ # stacks we dont want to rewrite, which are generally MappedColumn
+ # use cases:
+ #
+ # ['Mapped', "'Optional[Dict[str, str]]'"]
+ # ['Mapped', 'dict[str, str] | None']
+
+ if (
+ # avoid already quoted symbols such as
+ # ['Mapped', "'Optional[Dict[str, str]]'"]
+ not re.match(r"""^["'].*["']$""", stack[-1])
+ # avoid further generics like Dict[] such as
+ # ['Mapped', 'dict[str, str] | None']
+ and not re.match(r".*\[.*\]", stack[-1])
+ ):
stripchars = "\"' "
stack[-1] = ", ".join(
f'"{elem.strip(stripchars)}"' for elem in stack[-1].split(",")
)
- # stack: ['Mapped', 'List', '"Address"']
annotation = "[".join(stack) + ("]" * (len(stack) - 1))