summaryrefslogtreecommitdiff
path: root/lib/sqlalchemy/orm/mapper.py
diff options
context:
space:
mode:
authorNicolas CANIART <nicolas@caniart.net>2019-08-22 14:16:29 -0400
committerMike Bayer <mike_mp@zzzcomputing.com>2019-08-27 12:59:21 -0400
commit75b2518b2659796c885396fd0893dd7f9b19a9ef (patch)
treea7d67e8d62ab16306ae2881dfd1c944a69fd3eed /lib/sqlalchemy/orm/mapper.py
parent94385b031c1dac004ee4181cb5783328d740d110 (diff)
downloadsqlalchemy-75b2518b2659796c885396fd0893dd7f9b19a9ef.tar.gz
Implement type-level sorting for Enum; apply to ORM primary keys
Added support for the use of an :class:`.Enum` datatype using Python pep-435 enumeration objects as values for use as a primary key column mapped by the ORM. As these values are not inherently sortable, as required by the ORM for primary keys, a new :attr:`.TypeEngine.sort_key_function` attribute is added to the typing system which allows any SQL type to implement a sorting for Python objects of its type which is consulted by the unit of work. The :class:`.Enum` type then defines this using the database value of a given enumeration. The sorting scheme can be also be redefined by passing a callable to the :paramref:`.Enum.sort_key_function` parameter. Pull request courtesy Nicolas Caniart. Fixes: #4285 Closes: #4816 Pull-request: https://github.com/sqlalchemy/sqlalchemy/pull/4816 Pull-request-sha: 42266b766c1e462d5b8a409cda05d33dea13bd34 Change-Id: Iadcc16173c1ba26ffac5830db57743a4cb987c55
Diffstat (limited to 'lib/sqlalchemy/orm/mapper.py')
-rw-r--r--lib/sqlalchemy/orm/mapper.py19
1 files changed, 19 insertions, 0 deletions
diff --git a/lib/sqlalchemy/orm/mapper.py b/lib/sqlalchemy/orm/mapper.py
index 5e8d25647..07fd9f3fb 100644
--- a/lib/sqlalchemy/orm/mapper.py
+++ b/lib/sqlalchemy/orm/mapper.py
@@ -2749,6 +2749,25 @@ class Mapper(InspectionAttr):
return identity_key[1]
@_memoized_configured_property
+ def _persistent_sortkey_fn(self):
+ key_fns = [col.type.sort_key_function for col in self.primary_key]
+
+ if set(key_fns).difference([None]):
+
+ def key(state):
+ return tuple(
+ key_fn(val) if key_fn is not None else val
+ for key_fn, val in zip(key_fns, state.key[1])
+ )
+
+ else:
+
+ def key(state):
+ return state.key[1]
+
+ return key
+
+ @_memoized_configured_property
def _identity_key_props(self):
return [self._columntoproperty[col] for col in self.primary_key]