degal/db.py
author Tero Marttila <terom@fixme.fi>
Wed, 10 Jun 2009 23:33:28 +0300
changeset 84 891545a38a2b
parent 47 189f331c7960
permissions -rw-r--r--
change utils.LazyProperty to store the cached value using obj.__dict__
import sqlite3

try :
    conn = sqlite3.connect("db/degal.db")

except sqlite3.OperationalError :
    conn = None

def execute (expr, *args) :
    c = conn.cursor()
    c.execute(expr, args)

    return c

def execute_many (expr, iter) :
    c = conn.cursor()
    c.executemany(expr, iter)

    return c

def insert (expr, *args) :
    return execute_commit(expr, *args).lastrowid

def insert_many (cb, expr, iter) :
    """
        Perform an executemany with the given iterator (which must yield (cb_val, args) tuples), calling the given callback with the args (cb_val, row_id)
    """

    c = conn.cursor()

    c.executemany(expr, _lastrowid_adapter(c, iter, cb))

    return commit(c)

def _lastrowid_adapter (c, iter, cb) :
    for val, args in iter :
        yield args

        cb(val, c.lastrowid)

def commit (cursor) :
    try :
        cursor.execute("COMMIT")
    except sqlite3.OperationalError :
        pass    # ffs. INSERT just doesn't do anything otherwise

    return cursor

def execute_commit (expr, *args) :
    return commit(execute(expr, *args))

def execute_commit_many (expr, iter) :
    return commit(execute_many(expr, iter))

select = execute

delete = execute_commit

delete_many = execute_commit_many

if conn :
    cursor = conn.cursor