svv/application.py
author Tero Marttila <terom@fixme.fi>
Fri, 21 Jan 2011 04:44:30 +0200
changeset 61 ce1d012d02fe
parent 25 cfb55708ee03
permissions -rw-r--r--
html: amend
"""
    Application runtime state
"""

from sqlalchemy import create_engine

import logging

from svv import database as db

log = logging.getLogger('svv.app')

class Application (object) :
    """
        Our core run-time state, which e.g. WSGIAoo acts as a frontend to
    """

    def __init__ (self, db_url) :
        """
            Initialize app, connecting to database.

                db_url      - sqlalchemy-style URL to database
        """
        
        if db_url :
            # connect
            self._engine = engine = create_engine(db_url)

            log.info("Connected to database %s", engine)

        else :
            self._engine = None

    @property
    def engine (self) :
        """
            Our sqlalchemy engine providing access to our database
        """

        if not self._engine :
            raise RuntimeError("No database configured")
           
        return self._engine

    def create_tables (self) :
        """
            Initialize the database if new.
        """

        log.warn("Creating database tables...")

        db.schema.create_all(self.engine)

    def get_connection (self) :
        """
            Return an active sqlalchemy Connection for our database.
        """
        
        return self.engine.connect()

    def query (self, sql) :
        """
            Execute a simple SQL query, and return results
        """

        return self.engine.execute(sql)
    
    def insert (self, sql, **values) :
        """
            Execute a simple SQL insert, returning the new IDs a a tuple.

            For the common case of a table with a simplex primary key, a call looks like:

                new_id, = app.insert(sql, foo=bar)
        """
        
        return self.engine.execute(sql, **values).last_inserted_ids()

    def execute (self, sql, **values) :
        """
            Execute an SQL statement (UPDATE) that doesn't return any values.
        """

        self.engine.execute(sql, **values)

    # XXX: rename this to something else, conflicts, to some degree, with web session with cookies (although using
    # SQL transctions at that level would be pretty cool..)
    # orm orm_session objects dbsession dbmapping dbmaps 
    def session (self) :
        """
            Return a new SQLAlchemy database session, for use with ORM mapped objects.
        """

        return db.session_factory(bind=self.engine)