Source code for stalker.db
#-*- coding: utf-8 -*-
"""This is the database module of Stalker.
Whenever something is imported from stalker.db, the setup function becomes
available to let one to setup the database
"""
from sqlalchemy.orm import mapper, sessionmaker
from sqlalchemy import create_engine
from stalker.conf import defaults
from stalker.db import tables, meta
#----------------------------------------------------------------------
[docs]def setup(database=None, mappers=[]):
"""
This is a utillty function that helps to connect the system to the given
database.
if the database is None then the it setups using the default database in
the settings file.
These are the steps:
1. creates the engine, and stores it in stalker.db.meta.engine
2. creates the mappers, adds the given mappers to the
stalker.conf.defaults.MAPPERS list
3. creates the session and binds the engine to it, and stores the session
in stalker.db.meta.session
"""
if database is None:
database = defaults.DATABASE
meta.engine = create_engine(database, echo=True)
# create the mappers according to the config
assert(isinstance(mappers, list))
# extend the default mappers with the given mappers list
defaults.MAPPERS.extend(mappers)
create_mappers(defaults.MAPPERS)
# create tables
meta.metadata.create_all(meta.engine)
# create the Session class
Session = sessionmaker(bind=meta.engine)
# create and save session object to stalker.db.meta.sessison
meta.session = Session()
#----------------------------------------------------------------------
def create_mappers(mapper_list):
"""imports the given mapper helper modules, refer to :ref:`mappers` for
more information about how to create your own mapper modules.
"""
#
# just import the given list of mapper modules, if they are in the correct
# format all the mapping should be done already by just import ing the
# mapper helper modules
#
for _mapper in mapper_list:
exec("import " + _mapper)