Created
September 6, 2021 10:34
-
-
Save silenius/5e9004859c64eac4789c1d2838d3bc1e to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def with_current_translations(stmt, entity, request=None): | |
if request is None: | |
registry = get_current_registry() | |
else: | |
registry = request.registry | |
insp = inspect(entity) | |
base = insp.class_ | |
current_locale, default_locale = get_locales(request) | |
translations = registry['amnesia.translations']['mappings'] | |
# orm.with_polymorphic entity | |
if insp.is_aliased_class: | |
content_cls = {_.class_ for _ in insp.with_polymorphic_mappers} | |
# Mappings from Content-like classes to corresponding | |
# ContentTranslation-like classes | |
aliased = [t for c, t in translations.items() if c in content_cls] | |
translation_cls = orm.with_polymorphic(ContentTranslation, aliased) | |
partition = sql.select( | |
translation_cls, | |
sql.func.row_number().over( | |
order_by=[ | |
sql.desc(translation_cls.language_id == current_locale), | |
sql.desc(translation_cls.language_id == default_locale) | |
], | |
partition_by=translation_cls.content_id | |
).label('index') | |
).where( | |
translation_cls.language_id.in_((current_locale, default_locale)) | |
).subquery() | |
partition_alias = orm.aliased( | |
translation_cls, partition | |
) | |
options = ( | |
orm.contains_eager( | |
getattr(getattr(entity, cls.__name__), 'current_translation'), | |
alias=partition | |
) | |
for cls in content_cls if cls is not base | |
) | |
stmt = stmt.join( | |
partition_alias, | |
sql.and_( | |
partition_alias.content_id==entity.id, | |
partition.c.index==1 | |
) | |
).options( | |
#orm.contains_eager(entity.current_translation.of_type(partition_alias) | |
orm.contains_eager(entity.current_translation, alias=partition), | |
*options | |
) | |
return (stmt, partition) | |
elif insp.is_mapper: | |
stmt = stmt.join( | |
entity.current_translation | |
).options( | |
orm.contains_eager( | |
entity.current_translation, | |
alias=entity._current_translation_partition | |
) | |
) | |
return (stmt, entity._current_translation_partition) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment