[Checkins] SVN: megrok.rdb/trunk/src/megrok/rdb/setup.py Make sure schema table arg is honored when using reflection.

Martijn Faassen faassen at infrae.com
Mon Oct 27 22:06:19 EDT 2008


Log message for revision 92646:
  Make sure schema table arg is honored when using reflection.
  
  Unfortunately I have no idea how to automatically test this code
  using sqlite. Need to think hard about test infrastructure to allow
  testing with MySQL...
  

Changed:
  U   megrok.rdb/trunk/src/megrok/rdb/setup.py

-=-
Modified: megrok.rdb/trunk/src/megrok/rdb/setup.py
===================================================================
--- megrok.rdb/trunk/src/megrok/rdb/setup.py	2008-10-28 02:03:37 UTC (rev 92645)
+++ megrok.rdb/trunk/src/megrok/rdb/setup.py	2008-10-28 02:06:18 UTC (rev 92646)
@@ -3,6 +3,7 @@
 
 from sqlalchemy.orm import mapper
 from sqlalchemy.ext.declarative import instrument_declarative
+from sqlalchemy.schema import Table
 
 from z3c.saconfig.interfaces import IEngineFactory
 from megrok.rdb.interfaces import DatabaseSetupEvent
@@ -32,6 +33,10 @@
         return
     # first reflect database-defined schemas into metadata
     engine = Engine()
+    for class_ in metadata._reflected_registry.keys():
+        _reflectTableForClass(class_, metadata, engine)
+    # reflect any remaining tables. This will not reload tables already loaded
+    # (XXX is this necessary?)
     metadata.reflect(bind=engine)
     if not hasattr(metadata, '_decl_registry'):
         metadata._decl_registry = {}
@@ -41,6 +46,28 @@
     # XXX thread safety?
     metadata._reflected_completed = True
 
+def _reflectTableForClass(class_, metadata, bind):
+    """Reflect an individual table defined for a class.
+
+    This supports the special 'schema' indicator in '__table_args__',
+    allowing reflection of tables not in the default schema.
+    metadata.reflect() doesn't allow this in declarative mode.
+    """
+    reflect_opts = {'autoload': True}
+    reflect_opts['autoload_with'] = bind
+    conn = bind.contextual_connect()
+
+    table_args = getattr(class_, '__table_args__', {})
+    if type(table_args) is tuple:
+        table_args = table_args[-1]
+        if type(table_args) is not dict:
+            table_args = {}
+    schema = table_args.get('schema', None)
+    if schema is not None:
+        reflect_opts['schema'] = schema
+
+    Table(class_.__tablename__, metadata, **reflect_opts)
+        
 def createTables(metadata):
     """Create class-specified tables.
     """



More information about the Checkins mailing list