Skip to content

Instantly share code, notes, and snippets.

@ods
Created August 21, 2013 16:44
Show Gist options
  • Save ods/6296927 to your computer and use it in GitHub Desktop.
Save ods/6296927 to your computer and use it in GitHub Desktop.
Automatically discover relationships to replicate
#!/usr/bin/python2.7
import path_config
from app import db_maker
db = db_maker()
from models import admin
from models.admin.base import AdminFrontModel
from sqlalchemy.orm.attributes import manager_of_class
from sqlalchemy.orm import RelationshipProperty
def replicatable_models():
for name in dir(admin):
cls = getattr(admin, name)
if isinstance(cls, type) and issubclass(cls, AdminFrontModel):
yield cls
def get_relations(cls):
return [a for a in manager_of_class(cls).attributes
if isinstance(a.property, RelationshipProperty)]
def is_reflectable(prop):
return prop.secondary is not None and not prop.cascade.delete_orphan
def is_replicatable(prop):
return prop.cascade.delete_orphan
def repl_pair(attr):
return attr.key, attr.property.argument.__name__
ok = failed = 0
for cls in replicatable_models():
rels = list(get_relations(cls))
rels_reflect = set(repl_pair(a)
for a in rels if is_reflectable(a.property))
rels_replicate = set(repl_pair(a)
for a in rels if is_replicatable(a.property))
rels_reflect_manual = set(getattr(cls, 'reflectable_relations', []))
rels_replicate_manual = set(getattr(cls, 'replicatable_relations', []))
if rels_reflect==rels_reflect_manual and \
rels_replicate==rels_replicate_manual:
print cls.__name__, 'ok'
ok += 1
else:
print cls.__name__, 'failed:'
print rels_reflect, rels_reflect_manual
print rels_replicate, rels_replicate_manual
failed += 1
print 'ok:', ok, ' failed:', failed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment