# Path: opentuner/resultsdb/models.py
# class Base(object):
#     @declared_attr
#     def __tablename__(cls):
#         """convert camel case to underscores"""
#         return re.sub(r'([a-z])([A-Z])', r'\1_\2', cls.__name__).lower()
# 
#     id = Column(Integer, primary_key=True, index=True)
# 
# class _Meta(Base):
#     """ meta table to track current version """
#     db_version = Column(String(128))
# 
#     @classmethod
#     def has_version(cls, session, version):
#         try:
#             session.flush()
#             session.query(_Meta).filter_by(db_version=version).one()
#             return True
#         except sqlalchemy.orm.exc.NoResultFound:
#             return False
# 
#     @classmethod
#     def get_version(cls, session):
#         try:
#             session.flush()
#             x = session.query(_Meta).one()
#             return x.db_version
#         except sqlalchemy.orm.exc.NoResultFound:
#             return None
# 
#     @classmethod
#     def add_version(cls, session, version):
#         if not cls.has_version(session, version):
#             session.add(_Meta(db_version=version))


import logging
import time
    import atexit
from pprint import pprint
from sqlalchemy import create_engine
from sqlalchemy.orm import scoped_session, sessionmaker
from .models import Base, _Meta
    from sqlalchemy import event
    from collections import Counter
    from sqlalchemy.engine import Engine

def connect(dbstr):
    engine = create_engine(dbstr, echo=False)
    connection = engine.connect()

    # handle case that the db was initialized before a version table existed yet
    if engine.dialect.has_table(connection, "program"):
        # if there are existing tables
        if not engine.dialect.has_table(connection, "_meta"):
            # if no version table, assume outdated db version and error
            connection.close()
            raise Exception("Your opentuner database is currently out of date. Save a back up and reinitialize")

    # else if we have the table already, make sure version matches
    if engine.dialect.has_table(connection, "_meta"):
        Session = scoped_session(sessionmaker(autocommit=False,
                                              autoflush=False,
                                              bind=engine))
        version = _Meta.get_version(Session)
        if not DB_VERSION == version:
            raise Exception(
                'Your opentuner database version {} is out of date with the current version {}'.format(version,
                                                                                                       DB_VERSION))

    Base.metadata.create_all(engine)

    Session = scoped_session(sessionmaker(autocommit=False,
                                          autoflush=False,
                                          bind=engine))
    # mark database with current version

# Path: opentuner/resultsdb/models.py
# class Base(object):
#     @declared_attr
#     def __tablename__(cls):
#         """convert camel case to underscores"""
#         return re.sub(r'([a-z])([A-Z])', r'\1_\2', cls.__name__).lower()
# 
#     id = Column(Integer, primary_key=True, index=True)
# 
# class _Meta(Base):
#     """ meta table to track current version """
#     db_version = Column(String(128))
# 
#     @classmethod
#     def has_version(cls, session, version):
#         try:
#             session.flush()
#             session.query(_Meta).filter_by(db_version=version).one()
#             return True
#         except sqlalchemy.orm.exc.NoResultFound:
#             return False
# 
#     @classmethod
#     def get_version(cls, session):
#         try:
#             session.flush()
#             x = session.query(_Meta).one()
#             return x.db_version
#         except sqlalchemy.orm.exc.NoResultFound:
#             return None
# 
#     @classmethod
#     def add_version(cls, session, version):
#         if not cls.has_version(session, version):
#             session.add(_Meta(db_version=version))


# Path: opentuner/resultsdb/connect.py
import logging
import time
    import atexit
from pprint import pprint
from sqlalchemy import create_engine
from sqlalchemy.orm import scoped_session, sessionmaker
from .models import Base, _Meta
    from sqlalchemy import event
    from collections import Counter
    from sqlalchemy.engine import Engine


def connect(dbstr):
    engine = create_engine(dbstr, echo=False)
    connection = engine.connect()

    # handle case that the db was initialized before a version table existed yet
    if engine.dialect.has_table(connection, "program"):
        # if there are existing tables
        if not engine.dialect.has_table(connection, "_meta"):
            # if no version table, assume outdated db version and error
            connection.close()
            raise Exception("Your opentuner database is currently out of date. Save a back up and reinitialize")

    # else if we have the table already, make sure version matches
    if engine.dialect.has_table(connection, "_meta"):
        Session = scoped_session(sessionmaker(autocommit=False,
                                              autoflush=False,
                                              bind=engine))
        version = _Meta.get_version(Session)
        if not DB_VERSION == version:
            raise Exception(
                'Your opentuner database version {} is out of date with the current version {}'.format(version,
                                                                                                       DB_VERSION))

    Base.metadata.create_all(engine)

    Session = scoped_session(sessionmaker(autocommit=False,
                                          autoflush=False,
                                          bind=engine))
    # mark database with current version

    _Meta.add_version(Session, DB_VERSION)