#
# db.py: Connect to database and create a cursor
#
# If this module doesn't run standalone then nothing else will work.
#
__all__ = ['conn', 'curs', 'Error', 'pmark']

try:
    # Get the Settings from django of you can
    # NOTE: NEVER import from settings as it is not a module
    from django.conf import settings
except ImportError:
    # Default settings for when django is not loaded
    class FakeSettings(object): pass
    settings = FakeSettings()
    settings.DATABASE_NAME     = "testing07"
    settings.DATABASE_USER     = "postgres"
    settings.DATABASE_PASSWORD = "pycon2006"
    settings.DATABASE_HOST     = "localhost"
    settings.DATABASE_PORT     = 5432

conn = None
import psycopg2 as db
Error = (db.Error, db.ProgrammingError)
conn = db.connect(database=settings.DATABASE_NAME,
                  user=settings.DATABASE_USER,
                  password=settings.DATABASE_PASSWORD,
                  host=settings.DATABASE_HOST,
                  port=settings.DATABASE_PORT)
curs = conn.cursor()

#
# This is an attempt to allow development of code with multiple paramstyles
# Early exercises might need you to set pmark before you understand it :)
#
pmark = "%s"

#
# Using atexit.register allows us to ensure the database is properly closed
#
from atexit import register

def close():
    global conn
    if conn:
        conn.close()
    conn = None

register(close)

