Skip to content

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 driver 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.

dbkit.Context

A database connection context.

__init__(module, mdr)

Initialise a context with a given driver module and connection.

close()

Close the connection this context wraps.

current(with_exception = True) classmethod

Returns the current database context.

cursor()

Get a cursor for the current connection. For internal use only.

execute(stmt, args)

Execute a statement, returning a cursor. For internal use only.

execute_proc(procname, args)

Execute a stored procedure, returning a cursor. For internal use only.

transaction()

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

Exceptions

dbkit.NoContextError

Bases: Exception

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

dbkit.NotSupportedError

Bases: Exception

You are attempting something unsupported.

dbkit.AbortTransactionError

Bases: Exception

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("Naughty!", file=sys.stderr)

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("Naughty!", file=sys.stderr)

@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.TupleFactory is used as the result generator, but you can change this by assigning another, such as dbkit.DictFactory 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.DictFactory

Bases: FactoryBase

Iterator over a statement’s results as a dict.

dbkit.TupleFactory

Bases: FactoryBase

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

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.

dbkit.PoolBase

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.

create_mediator()

Create a suitable mediator for this pool.

discard()

Signal to the pool that a connection has been discarded.

This is intended for internal use only.

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.

get_max_reattempts()

Number of times this pool should be reattempted when attempting to get a fresh connection.

release(conn)

Release a previously acquired connection back to the pool.

This is intended for internal use only.

dbkit.Pool

Bases: PoolBase

A very simple connection pool.

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.

dbkit.ConnectionMediatorBase

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.

dbkit.SingleConnectionMediator

Bases: ConnectionMediatorBase

Mediates access to a single unpooled connection.

dbkit.PooledConnectionMediator

Bases: ConnectionMediatorBase

Mediates connection acquisition and release from/to a pool.