| 1 | ''' |
|---|
| 2 | Elixir |
|---|
| 3 | |
|---|
| 4 | A declarative layer on top of SQLAlchemy, which is intended to replace the |
|---|
| 5 | ActiveMapper SQLAlchemy extension, and the TurboEntity project. Elixir is a |
|---|
| 6 | fairly thin wrapper around SQLAlchemy, which provides the ability to define |
|---|
| 7 | model objects following the Active Record design pattern, and using a DSL |
|---|
| 8 | syntax similar to that of the Ruby on Rails ActiveRecord system. |
|---|
| 9 | |
|---|
| 10 | Elixir does not intend to replace SQLAlchemy's core features, but instead |
|---|
| 11 | focuses on providing a simpler syntax for defining model objects when you do |
|---|
| 12 | not need the full expressiveness of SQLAlchemy's manual mapper definitions. |
|---|
| 13 | |
|---|
| 14 | For an example of how to use Elixir, please refer to the examples directory and |
|---|
| 15 | the unit tests. The examples directory includes a TurboGears application with |
|---|
| 16 | full identity support called 'videostore'. |
|---|
| 17 | ''' |
|---|
| 18 | |
|---|
| 19 | import sqlalchemy |
|---|
| 20 | |
|---|
| 21 | from sqlalchemy.ext.sessioncontext import SessionContext |
|---|
| 22 | from sqlalchemy.types import * |
|---|
| 23 | from elixir.options import using_options |
|---|
| 24 | from elixir.entity import Entity, EntityDescriptor |
|---|
| 25 | from elixir.fields import Field, has_field, with_fields |
|---|
| 26 | from elixir.relationships import belongs_to, has_one, has_many, \ |
|---|
| 27 | has_and_belongs_to_many |
|---|
| 28 | |
|---|
| 29 | __all__ = ['Entity', 'Field', 'has_field', 'with_fields', 'belongs_to', |
|---|
| 30 | 'has_one', 'has_many', 'has_and_belongs_to_many', 'using_options', |
|---|
| 31 | 'create_all', 'drop_all', 'metadata', 'objectstore'] + \ |
|---|
| 32 | sqlalchemy.types.__all__ |
|---|
| 33 | |
|---|
| 34 | # connect |
|---|
| 35 | metadata = sqlalchemy.DynamicMetaData('elixir') |
|---|
| 36 | |
|---|
| 37 | try: |
|---|
| 38 | objectstore = sqlalchemy.objectstore |
|---|
| 39 | except AttributeError: |
|---|
| 40 | # thread local SessionContext |
|---|
| 41 | class Objectstore(object): |
|---|
| 42 | def __init__(self, *args, **kwargs): |
|---|
| 43 | self.context = SessionContext(*args, **kwargs) |
|---|
| 44 | def __getattr__(self, name): |
|---|
| 45 | return getattr(self.context.current, name) |
|---|
| 46 | session = property(lambda s:s.context.current) |
|---|
| 47 | |
|---|
| 48 | objectstore = Objectstore(sqlalchemy.create_session) |
|---|
| 49 | |
|---|
| 50 | metadatas = set() |
|---|
| 51 | |
|---|
| 52 | def create_all(): |
|---|
| 53 | """Create all necessary tables for all declared entities""" |
|---|
| 54 | for md in metadatas: |
|---|
| 55 | md.create_all() |
|---|
| 56 | |
|---|
| 57 | def drop_all(): |
|---|
| 58 | """Drop all tables for all declared entities""" |
|---|
| 59 | for md in metadatas: |
|---|
| 60 | md.drop_all() |
|---|