summaryrefslogtreecommitdiffstats
path: root/src/lib/Server/Snapshots/__init__.py
blob: 6018377cb726cf0723b82a71c40fc408223f7941 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
__all__ = ['models', 'db_from_config', 'setup_session']

import sqlalchemy
import sqlalchemy.orm
import ConfigParser


def db_from_config(cfile):
    cp = ConfigParser.ConfigParser()
    cp.read([cfile])
    driver = cp.get('snapshots', 'driver')
    if driver == 'sqlite':
        path = cp.get('snapshots', 'database')
        return 'sqlite:///%s' % path
    elif driver in ['mysql', 'postgres']:
        user = cp.get('snapshots', 'user')
        password = cp.get('snapshots', 'password')
        host = cp.get('snapshots', 'host')
        db = cp.get('snapshots', 'database')
        return '%s://%s:%s@%s/%s' % (driver, user, password, host, db)
    else:
        raise Exception, "unsupported db driver %s" % driver


def setup_session(cfile, debug=False):
    engine = sqlalchemy.create_engine(db_from_config(cfile),
                                      echo=debug)
    Session = sqlalchemy.orm.sessionmaker()
    Session.configure(bind=engine)
    return Session()