from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import scoped_session, sessionmaker, mapper
from sqlalchemy import Table
from sqlalchemy.orm.util import _is_mapped_class
from contextlib import contextmanager
import logging
#NOTE extra conditional import in make_classes() below


@contextmanager
def db_log_level (level):
	db_logger = logging.getLogger('sqlalchemy.engine')
	old_level = db_logger.level

	db_logger.level = level
	try:
		yield
	finally:
		db_logger.level = old_level


#TODO will be obsolete in 0.8 (see DeferredReflection)
#see http://docs.sqlalchemy.org/en/rel_0_7/orm/examples.html#declarative-reflection
#see http://hg.sqlalchemy.org/sqlalchemy/file/8e1b23314c39/examples/declarative_reflection/declarative_reflection.py
#see https://bitbucket.org/zzzeek/sqlalchemy/pull-request/1/copied-declarativereflectedbase-from-the
class DeclarativeReflectedBase(object):
    _mapper_args = []

    @classmethod
    def __mapper_cls__(cls, *args, **kw):
        """Declarative will use this function in lieu of
        calling mapper() directly.

        Collect each series of arguments and invoke
        them when prepare() is called.
        """

        cls._mapper_args.append((args, kw))

    @classmethod
    def prepare(cls, engine):
        """Reflect all the tables and map !"""
        while cls._mapper_args:
            args, kw  = cls._mapper_args.pop()
            klass = args[0]
            # autoload Table, which is already
            # present in the metadata.  This
            # will fill in db-loaded columns
            # into the existing Table object.
            if args[1] is not None:
                table = args[1]
                Table(table.name,
                    cls.metadata,
                    extend_existing=True,
                    autoload_replace=False,
                    autoload=True,
                    autoload_with=engine,
                    schema=table.schema)

            # see if we need 'inherits' in the
            # mapper args.  Declarative will have
            # skipped this since mappings weren't
            # available yet.
            for c in klass.__bases__:
                if _is_mapped_class(c):
                    kw['inherits'] = c
                    break

            klass.__mapper__ = mapper(*args, **kw)

#DBObject = declarative_base()
#DBObject = declarative_base(cls = DeclarativeReflectedBase)
class Reflected (DeclarativeReflectedBase, DBObject):
	__abstract__ = True


def make_classes (use_zope_ext = False):
	if use_zope_ext:
		from zope.sqlalchemy import ZopeTransactionExtension

	DBSession = scoped_session(sessionmaker(extension =
		ZopeTransactionExtension() if use_zope_ext else None
	))

	class QueryPropertyMixin (object):
		query = DBSession.query_property()

	return DBSession, QueryPropertyMixin


def init (engine, DBSession, Reflected, on_before_reflect = None):
	DBSession.configure(bind = engine)

	#DBObject.metadata.bind = engine
	Reflected.metadata.bind = engine

	if on_before_reflect:
		on_before_reflect()

	with db_log_level(logging.WARN):
		Reflected.prepare(engine)

add SQLAlchemy reflective initialisation boilerplate