root / elixir / trunk / elixir / __init__.py @ 248

Revision 248, 4.5 kB (checked in by cleverdevil, 6 years ago)

After reviewing the existing docstrings, clarifying the main docstring to focus on the new attribute syntax, and downplaying the DSL syntax a bit. This will also go on the front page of the wiki in a moment.

Line 
1'''
2Elixir package
3
4A declarative layer on top of SQLAlchemy, which is intended to replace the
5ActiveMapper SQLAlchemy extension, and the TurboEntity project.  Elixir is a
6fairly thin wrapper around SQLAlchemy, which provides the ability to define
7model objects following the Active Record design pattern, and using a
8syntax familiar to users of other Object Relational Mappers, like SQLObject.
9
10Elixir does not intend to replace SQLAlchemy's core features, but instead
11focuses on providing a simpler syntax for defining model objects when you do
12not need the full expressiveness of SQLAlchemy's manual mapper definitions.
13
14For an example of how to use Elixir, please refer to the examples directory
15and the unit tests. The examples directory includes a TurboGears application
16with full identity support called 'videostore'.
17'''
18
19import sqlalchemy
20
21from sqlalchemy.types import *
22
23from elixir.options import using_options, using_table_options, \
24                           using_mapper_options, options_defaults
25from elixir.entity import Entity, EntityMeta, EntityDescriptor, \
26                          setup_entities, cleanup_entities
27from elixir.fields import has_field, with_fields, Field
28from elixir.relationships import belongs_to, has_one, has_many, \
29                                 has_and_belongs_to_many
30from elixir.relationships import ManyToOne, OneToOne, OneToMany, ManyToMany
31from elixir.properties import has_property, GenericProperty, ColumnProperty
32from elixir.statements import Statement
33
34try:
35    set
36except NameError:
37    from sets import Set as set
38
39__version__ = '0.4.0'
40
41__all__ = ['Entity', 'EntityMeta',
42           'Field', 'has_field', 'with_fields',
43           'has_property', 'GenericProperty', 'ColumnProperty',
44           'belongs_to', 'has_one', 'has_many', 'has_and_belongs_to_many',
45           'ManyToOne', 'OneToOne', 'OneToMany', 'ManyToMany',
46           'using_options', 'using_table_options', 'using_mapper_options',
47           'options_defaults', 'metadata', 'objectstore', 'session',
48           'create_all', 'drop_all',
49           'setup_all', 'cleanup_all', 
50           'setup_entities', 'cleanup_entities'] + \
51           sqlalchemy.types.__all__
52
53__doc_all__ = ['create_all', 'drop_all',
54                 'setup_all', 'cleanup_all',
55                 'metadata', 'session']
56
57
58class Objectstore(object):
59    """a wrapper for a SQLAlchemy session-making object, such as
60    SessionContext or ScopedSession.
61   
62    Uses the ``registry`` attribute present on both objects
63    (versions 0.3 and 0.4) in order to return the current
64    contextual session.
65    """
66   
67    def __init__(self, ctx):
68        self.context = ctx
69
70    def __getattr__(self, name):
71        return getattr(self.context.registry(), name)
72   
73    session = property(lambda s:s.context.registry())
74
75# default session
76try: 
77    from sqlalchemy.orm import scoped_session
78    session = scoped_session(sqlalchemy.orm.create_session)
79except ImportError: 
80    # Not on version 0.4 of sqlalchemy
81    from sqlalchemy.ext.sessioncontext import SessionContext
82    session = Objectstore(SessionContext(sqlalchemy.orm.create_session))
83
84# backward-compatible name
85objectstore = session
86
87# default metadata
88metadata = sqlalchemy.MetaData()
89
90metadatas = set()
91
92# default entity collection
93entities = list()
94
95def create_all(*args, **kwargs):
96    '''Create the necessary tables for all declared entities'''
97    for md in metadatas:
98        md.create_all(*args, **kwargs)
99
100def drop_all(*args, **kwargs):
101    '''Drop tables for all declared entities'''
102    for md in metadatas:
103        md.drop_all(*args, **kwargs)
104
105
106def setup_all(create_tables=False, *args, **kwargs):
107    '''Setup the table and mapper of all entities in the default entity
108    collection.
109
110    This is called automatically if any entity of the collection is configured
111    with the `autosetup` option (this is the default) and it is first accessed,
112    instanciated (called) or the create_all method of a metadata containing
113    tables from any of those entities is called.
114    '''
115    setup_entities(entities)
116
117    # issue the "CREATE" SQL statements
118    if create_tables:
119        create_all(*args, **kwargs)
120
121def cleanup_all(drop_tables=False, *args, **kwargs):
122    '''Clear all mappers, clear the session, and clear all metadatas.
123    Optionally drops the tables.
124    '''
125    if drop_tables:
126        drop_all(*args, **kwargs)
127
128    cleanup_entities(entities)
129
130    for md in metadatas:
131        md.clear()
132    metadatas.clear()
133
134    session.clear()
135
136    sqlalchemy.orm.clear_mappers()
137    del entities[:]
Note: See TracBrowser for help on using the browser.