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.
Returns the current database context.
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.
A database connection context.
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.
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 the connection this context wraps.
You are attempting to use dbkit outside of a database context.
You are attempting something unsupported.
Raised to signal that code within the transaction wants to abort it.
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))
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))
These functions allow you to execute SQL statements within the current database context.
Execute an SQL statement. Returns the number of affected rows.
Execute a query. This returns an iterator of the result set.
Execute a query. Returns the first row of the result set, or 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.
Execute a query, returning an iterable of the first column.
These functions allow you to execute stored procedures within the current database context, if the DBMS supports stored procedures.
Execute a stored procedure. Returns the number of affected rows.
Execute a stored procedure. This returns an iterator of the result set.
Execute a stored procedure. Returns the first row of the result set, or 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.
Execute a stored procedure, returning an iterable of the first column.
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.
Iterator over a statement’s results as a dict.
Iterator over a statement’s results where each row is a tuple.
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.
A logger that discards everything sent to it.
Make a logger that logs to the given file object.
A logger that logs to standard error.
Convert a resultset into a dictionary keyed off of one of its columns.
Generate placeholders for the given sequence.
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.
Abstract base class for all connection pools.
Acquire a connection from the pool and returns it.
This is intended for internal use only.
Release a previously acquired connection back to the pool.
This is intended for internal use only.
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.
Returns a context that uses this pool as a connection source.
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.
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.
Called to signal that any resources can be released.
Commit the current transaction.
Get a cursor for the current connection.
Rollback the current transaction.
Mediates access to a single unpooled connection.
Mediates connection acquisition and release from/to a pool.