lodgeit-main / lodgeit /

# -*- coding: utf-8 -*-

    Database fun :)

    :copyright: 2007-2010 by Armin Ronacher, Christopher Grebs.
    :license: BSD
import sys
from types import ModuleType

import sqlalchemy
from sqlalchemy import MetaData, orm, create_engine
from sqlalchemy.orm import mapper, scoped_session, sessionmaker
from sqlalchemy.ext.declarative import declarative_base

from lodgeit import config

metadata = MetaData()

engine = create_engine(config.get('lodgeit', 'dburi'),
session = sessionmaker(bind=engine,
ScopedSession = scoped_session(session)

class ModelBase(object):
    """Internal baseclass for all models.  It provides some syntactic
    sugar and maps the default query property.

    We use the declarative model api from sqlalchemy.

# configure the declarative base
Model = declarative_base(name='Model', cls=ModelBase,
                         mapper=mapper, metadata=metadata)
ModelBase.query = ScopedSession.query_property()

def _make_module():
    db = ModuleType('db')
    #XXX:dc: stop rexporting all of this stuff
    for mod in sqlalchemy, orm:
        for key, value in mod.__dict__.iteritems():
            if key in mod.__all__:
                setattr(db, key, value)

    db.engine = engine
    db.session = ScopedSession
    db.metadata = metadata
    db.Model = Model
    db.NoResultFound = orm.exc.NoResultFound
    return db

sys.modules['lodgeit.db'] = db = _make_module()