Reference

dbkit.connect(module, *args, **kwargs)

Connect to a database using the given DB-API driver module. Returns a database context representing that connection. Any arguments or keyword arguments are passed the module’s connect() function.

dbkit.context()

Returns the current database context.

Contexts

Contexts wrap a notional database connection. They’re returned by the dbkit.connect() function. Methods are for the internal use of dbkit only though it does expose a method for closing the database connection when you’re done with it and contains references for each of the exceptions exposed by the connection’s database driver. For a list of these exceptions, see PEP-0249.

class dbkit.Context(module, mdr)

A database connection context.

default_factory

The row factory used for generating rows from dbkit.query() and dbkit.query_row(). The default is dbkit.tuple_set().

The factory function should take a cursor an return an iterable over the current resultset.

logger

The function used for logging statements and their arguments.

The logging function should take two arguments: the query and a sequence of query arguments.

There are two supplied logging functions: dbkit.null_logger(), the default, logs nothing, while dbkit.stderr_logger() logs its arguments to stderr.

close()

Close the connection this context wraps.

Exceptions

class dbkit.NoContext

You are attempting to use dbkit outside of a database context.

class dbkit.NotSupported

You are attempting something unsupported.

class dbkit.AbortTransaction

Raised to signal that code within the transaction wants to abort it.

Transactions

dbkit.transaction()

Sets up a context where all the statements within it are ran within a single database transaction.

Here’s a rough example of how you’d use it:

import sqlite3
import sys
from dbkit import connect, transaction, query_value, execute

# ...do some stuff...

with connect(sqlite3, '/path/to/my.db') as ctx:
    try:
        change_ownership(page_id, new_owner_id)
    catch ctx.IntegrityError:
        print >> sys.stderr, "Naughty!"

def change_ownership(page_id, new_owner_id):
    with transaction():
        old_owner_id = query_value(
            "SELECT owner_id FROM pages WHERE page_id = ?",
            (page_id,))
        execute(
            "UPDATE users SET owned = owned - 1 WHERE id = ?",
            (old_owner_id,))
        execute(
            "UPDATE users SET owned = owned + 1 WHERE id = ?",
            (new_owner_id,))
        execute(
            "UPDATE pages SET owner_id = ? WHERE page_id = ?",
            (new_owner_id, page_id))
dbkit.transactional(wrapped)

A decorator to denote that the content of the decorated function or method is to be ran in a transaction.

The following code is equivalent to the example for dbkit.transaction():

import sqlite3
import sys
from dbkit import connect, transactional, query_value, execute

# ...do some stuff...

with connect(sqlite3, '/path/to/my.db') as ctx:
    try:
        change_ownership(page_id, new_owner_id)
    catch ctx.IntegrityError:
        print >> sys.stderr, "Naughty!"

@transactional
def change_ownership(page_id, new_owner_id):
    old_owner_id = query_value(
        "SELECT owner_id FROM pages WHERE page_id = ?",
        (page_id,))
    execute(
        "UPDATE users SET owned = owned - 1 WHERE id = ?",
        (old_owner_id,))
    execute(
        "UPDATE users SET owned = owned + 1 WHERE id = ?",
        (new_owner_id,))
    execute(
        "UPDATE pages SET owner_id = ? WHERE page_id = ?",
        (new_owner_id, page_id))

Statement execution

These functions allow you to execute SQL statements within the current database context.

dbkit.execute(stmt, args=())

Execute an SQL statement. Returns the number of affected rows.

dbkit.query(stmt, args=(), factory=None)

Execute a query. This returns an iterator of the result set.

dbkit.query_row(stmt, args=(), factory=None)

Execute a query. Returns the first row of the result set, or None.

dbkit.query_value(stmt, args=(), default=None)

Execute a query, returning the first value in the first row of the result set. If the query returns no result set, a default value is returned, which is None by default.

dbkit.query_column(stmt, args=())

Execute a query, returning an iterable of the first column.

Stored procedures

These functions allow you to execute stored procedures within the current database context, if the DBMS supports stored procedures.

dbkit.execute_proc(procname, args=())

Execute a stored procedure. Returns the number of affected rows.

dbkit.query_proc(procname, args=(), factory=None)

Execute a stored procedure. This returns an iterator of the result set.

dbkit.query_proc_row(procname, args=(), factory=None)

Execute a stored procedure. Returns the first row of the result set, or None.

dbkit.query_proc_value(procname, args=(), default=None)

Execute a stored procedure, returning the first value in the first row of the result set. If it returns no result set, a default value is returned, which is None by default.

dbkit.query_proc_column(procname, args=())

Execute a stored procedure, returning an iterable of the first column.

Result generators

Result generators are generator functions that are used internally by dbkit to take the results from a database cursor and turn them into a form that’s easier to deal with programmatically, such a sequence of tuples or a sequence of dictionaries, where each tuple or dictionary represents a row of the result set. By default, dbkit.tuple_set() is used as the result generator, but you can change this by assigning another, such as dbkit.dict_set() to dbkit.Context.default_factory function.

Some query functions allow you to specify the result generator to be used for the result, which is passed in using the factory parameter.

dbkit.dict_set(cursor, mdr)

Iterator over a statement’s results as a dict.

dbkit.tuple_set(cursor, mdr)

Iterator over a statement’s results where each row is a tuple.

Loggers

Loggers are functions that you can assign to dbkit.Context.logger to have dbkit log any SQL statements ran or stored procedures called to some sink. dbkit comes with a number of simple loggers listed below. To create your own logger, simply create a function that takes two arguments, the first of which is the SQL statement or stored procedure name, and the second is a sequence of arguments that were passed with it.

dbkit.null_logger(_stmt, _args)

A logger that discards everything sent to it.

dbkit.make_file_object_logger(fh)

Make a logger that logs to the given file object.

dbkit.stderr_logger(stmt, args)

A logger that logs to standard error.

Utilities

dbkit.to_dict(key, resultset)

Convert a resultset into a dictionary keyed off of one of its columns.

dbkit.make_placeholders(seq, start=1)

Generate placeholders for the given sequence.

Connection pools

Note

Connection pool support is currently considered pre-alpha.

Connection pooling is a way to share a common set of database connections over a set of contexts, each of which can be executing in different threads. Connection pooling can increase efficiency as it mitigates much of the cost involved in connecting and disconnecting from databases. It also can help lower the number of database connections an application needs to keep open with a database server concurrently, thus helping to lower server low.

As with contexts, pools have a copy of the driver module’s exceptions. For a list of these exceptions, see PEP-0249.

The acquire and release methods are for internal use only.

class dbkit.PoolBase(module, threadsafety, args, kwargs)

Abstract base class for all connection pools.

acquire()

Acquire a connection from the pool and returns it.

This is intended for internal use only.

connect()

Returns a context that uses this pool as a connection source.

finalise()

Shut this pool down. Call this or have it called when you’re finished with the pool.

Please note that it is only guaranteed to complete after all connections have been returned to the pool for finalisation.

release(conn)

Release a previously acquired connection back to the pool.

This is intended for internal use only.

class dbkit.Pool(module, max_conns, *args, **kwargs)

A very simple connection pool.

connect()

Returns a context that uses this pool as a connection source.

finalise()

Connection mediators

Connection mediators are used internally within contexts to mediate connection acquisition and release between a context and a (notional) connection pool. They’re an advanced feature that you as a developer will only need to understand and use if writing your own connection pool. All connection mediator instances are context managers.

Note

You might find the naming a bit odd. After all, wouldn’t calling something like this a ‘manager’ be just as appropriate and less... odd? Not really. Calling something a ‘manager’ presupposes a degree of control over the resource in question. A ‘mediator’, on the other hand, simply acts as a middle man which both parties know. Introducing the mediator means that contexts don’t need to know where their connections come from and pools don’t need to care how they’re used. The mediator takes care of all that.

class dbkit.ConnectionMediatorBase(exceptions)

Mediates connection acquisition and release from/to a pool.

Implementations should keep track of the times they’ve been entered and exited, incrementing a counter for the former and decrementing it for the latter. They should acquire a connection when entered with a counter value of 0 and release it when exited with a counter value of 0.

close()

Called to signal that any resources can be released.

commit()

Commit the current transaction.

cursor()

Get a cursor for the current connection.

rollback()

Rollback the current transaction.

class dbkit.SingleConnectionMediator(module, connect_)

Mediates access to a single unpooled connection.

class dbkit.PooledConnectionMediator(pool)

Mediates connection acquisition and release from/to a pool.