Make pokedex work with SQLAlchemy 0.7. Warning: ugly hack!
[zzz-pokedex.git] / pokedex / db / multilang.py
index 7e2840f..d027d13 100644 (file)
@@ -5,8 +5,9 @@ from sqlalchemy.orm import aliased, compile_mappers, mapper, relationship, synon
 from sqlalchemy.orm.collections import attribute_mapped_collection
 from sqlalchemy.orm.scoping import ScopedSession
 from sqlalchemy.orm.session import Session, object_session
+from sqlalchemy.engine.base import Connection
 from sqlalchemy.schema import Column, ForeignKey, Table
-from sqlalchemy.sql.expression import and_, bindparam, select
+from sqlalchemy.sql.expression import and_, bindparam, select, Select
 from sqlalchemy.types import Integer
 
 def create_translation_table(_table_name, foreign_class, relation_name,
@@ -167,20 +168,24 @@ class MultilangSession(Session):
 
         super(MultilangSession, self).__init__(*args, **kwargs)
 
-    def execute(self, clause, params=None, *args, **kwargs):
-        if not params:
-            params = {}
-        params.setdefault('_default_language_id', self.default_language_id)
-
-        return super(MultilangSession, self).execute(
-            clause, params, *args, **kwargs)
+    def connection(self, *args, **kwargs):
+        """Monkeypatch the connection. Not pretty at all.
+        """
+        conn = super(MultilangSession, self).connection(*args, **kwargs)
+        original_execute = conn.execute
+        if original_execute.__name__ != 'monkeypatched_execute':
+            def monkeypatched_execute(statement, *multiparams, **params):
+                if isinstance(statement, Select):
+                    boundparams = dict(multiparams[0])
+                    boundparams.setdefault('_default_language_id', self.default_language_id)
+                    multiparams = [boundparams] + list(multiparams[1:])
+                return original_execute(statement, *multiparams, **params)
+            conn.execute = monkeypatched_execute
+        return conn
 
 class MultilangScopedSession(ScopedSession):
     """Dispatches language selection to the attached Session."""
 
-    def __init__(self, *args, **kwargs):
-        super(MultilangScopedSession, self).__init__(*args, **kwargs)
-
     @property
     def default_language_id(self):
         """Passes the new default language id through to the current session.