| 1 | """ |
|---|
| 2 | SuperModel |
|---|
| 3 | |
|---|
| 4 | A declarative layer on top of SQLAlchemy |
|---|
| 5 | """ |
|---|
| 6 | |
|---|
| 7 | import sqlalchemy |
|---|
| 8 | from sqlalchemy.types import * |
|---|
| 9 | |
|---|
| 10 | from supermodel.entity import Entity, EntityDescriptor |
|---|
| 11 | from supermodel.fields import Field, has_field, with_fields |
|---|
| 12 | from supermodel.relationships import belongs_to, has_one, has_many, \ |
|---|
| 13 | has_and_belongs_to_many |
|---|
| 14 | from supermodel.options import using_options |
|---|
| 15 | |
|---|
| 16 | import sqlalchemy |
|---|
| 17 | from sqlalchemy.ext.sessioncontext import SessionContext |
|---|
| 18 | |
|---|
| 19 | __all__ = ['Entity', 'Field', 'has_field', 'with_fields', 'belongs_to', 'has_one', |
|---|
| 20 | 'has_many', 'has_and_belongs_to_many', 'using_options', |
|---|
| 21 | 'create_all', 'drop_all'] + sqlalchemy.types.__all__ |
|---|
| 22 | |
|---|
| 23 | |
|---|
| 24 | # connect |
|---|
| 25 | metadata = sqlalchemy.DynamicMetaData('supermodel') |
|---|
| 26 | |
|---|
| 27 | try: |
|---|
| 28 | objectstore = sqlalchemy.objectstore |
|---|
| 29 | except AttributeError: |
|---|
| 30 | # thread local SessionContext |
|---|
| 31 | class Objectstore(object): |
|---|
| 32 | def __init__(self, *args, **kwargs): |
|---|
| 33 | self.context = SessionContext(*args, **kwargs) |
|---|
| 34 | def __getattr__(self, name): |
|---|
| 35 | return getattr(self.context.current, name) |
|---|
| 36 | session = property(lambda s:s.context.current) |
|---|
| 37 | |
|---|
| 38 | objectstore = Objectstore(sqlalchemy.create_session) |
|---|
| 39 | |
|---|
| 40 | metadatas = set() |
|---|
| 41 | |
|---|
| 42 | def create_all(): |
|---|
| 43 | """Create all necessary tables for all declared entities""" |
|---|
| 44 | for md in metadatas: |
|---|
| 45 | md.create_all() |
|---|
| 46 | |
|---|
| 47 | def drop_all(): |
|---|
| 48 | """Drop all tables for all declared entities""" |
|---|
| 49 | for md in metadatas: |
|---|
| 50 | md.drop_all() |
|---|