degal/db.py
author Tero Marttila <terom@fixme.fi>
Wed, 03 Jun 2009 19:03:28 +0300
branchuse-distutils
changeset 41 3b1579a7bffb
parent 26 lib/db.py@81d6679d50d0
child 44 533b7e8b5d3b
permissions -rw-r--r--
reorganize files to move lib, templates, www into 'degal' package, keep separate 'cgi-bin' for now
# DeGAL - A pretty simple web image gallery
# Copyright (C) 2007 Tero Marttila
# http://marttila.de/~terom/degal/
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the
# Free Software Foundation, Inc.,
# 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
#

import sqlite3

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

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

cursor = conn.cursor