Below the Model level, peewee uses an abstraction for representing the database. The Database is responsible for establishing and closing connections, making queries, and gathering information from the database.
The Database in turn uses another abstraction called an BaseAdapter, which is backend-specific and encapsulates functionality specific to a given db driver. Since there is some difference in column types across database engines, this information also resides in the adapter. The adapter is responsible for smoothing out the quirks of each database driver to provide a consistent interface, for example sqlite uses the question-mark ”?” character for parameter interpolation, while all the other backends use “%s”.
For a high-level overview of working with transactions, check out the transactions cookbook.
For notes on deferring instantiation of database, for example if loading configuration at run-time, see the notes on deferring initialization.
Note
The internals of the Database and BaseAdapter will be of interest to anyone interested in adding support for another database driver.
Peewee currently supports Sqlite, MySQL and Postgresql. These databases are very popular and run the gamut from fast, embeddable databases to heavyweight servers suitable for large-scale deployments. That being said, there are a ton of cool databases out there and adding support for your database-of-choice should be really easy, provided the driver supports the DB-API 2.0 spec.
The db-api 2.0 spec should be familiar to you if you’ve used the standard library sqlite3 driver, psycopg2 or the like. Peewee currently relies on a handful of parts:
These methods are generally wrapped up in higher-level abstractions and exposed by the Database and BaseAdapter, so even if your driver doesn’t do these exactly you can still get a lot of mileage out of peewee. An example is the apsw sqlite driver which I’m tinkering with adding support for.
Note
In later versions of peewee, the db-api 2.0 methods may be further abstracted out to add support for drivers that don’t conform to the spec.
There are two classes you will want to implement at the very least:
connections to the database, as well as describing the features provided by the database engine
transactions, and can introspect the underlying db.
Let’s say we want to add support for a fictitious “FooDB” which has an open-source python driver that uses the DB-API 2.0.
The adapter provides a bridge between the driver and peewee’s higher-level database class which is responsible for executing queries.
from peewee import BaseAdapter
import foodb # our fictional driver
class FooAdapter(BaseAdapter):
def connect(self, database, **kwargs):
return foodb.connect(database, **kwargs)
Now we want to create a mapping that exposes the operations our database engine supports. These are the operations that a user perform when building out the WHERE clause of a given query.
class FooAdapter(BaseAdapter):
operations = {
'lt': '< %s',
'lte': '<= %s',
'gt': '> %s',
'gte': '>= %s',
'eq': '= %s',
'ne': '!= %s',
'in': 'IN (%s)',
'is': 'IS %s',
'isnull': 'IS NULL',
'between': 'BETWEEN %s AND %s',
'icontains': 'ILIKE %s',
'contains': 'LIKE %s',
'istartswith': 'ILIKE %s',
'startswith': 'LIKE %s',
}
def connect(self, database, **kwargs):
return foodb.connect(database, **kwargs)
Other things the adapter handles that are not covered here include:
The Database provides a higher-level API and is responsible for executing queries, creating tables and indexes, and introspecting the database to get lists of tables. Each database must specify a BaseAdapter subclass, so our database will need to specify the FooAdapter we just defined:
from peewee import Database
class FooDatabase(Database):
def __init__(self, database, **connect_kwargs):
super(FooDatabase, self).__init__(FooAdapter(), database, **connect_kwargs)
This is the absolute minimum needed, though some features will not work – for best results you will want to additionally add a method for extracting a list of tables and indexes for a table from the database. We’ll pretend that FooDB is a lot like MySQL and has special “SHOW” statements:
class FooDatabase(Database):
def __init__(self, database, **connect_kwargs):
super(FooDatabase, self).__init__(FooAdapter(), database, **connect_kwargs)
def get_tables(self):
res = self.execute('SHOW TABLES;')
return [r[0] for r in res.fetchall()]
def get_indexes_for_table(self, table):
res = self.execute('SHOW INDEXES IN %s;' % self.quote_name(table))
rows = sorted([(r[2], r[1] == 0) for r in res.fetchall()])
return rows
There is a good deal of functionality provided by the Database class that is not covered here. Refer to the documentation below or the source code. for details.
Note
If your driver conforms to the db-api 2.0 spec, there shouldn’t be much work needed to get up and running.
Our new database can be used just like any of the other database subclasses:
from peewee import *
from foodb_ext import FooDatabase
db = FooDatabase('my_database', user='foo', password='secret')
class BaseModel(Model):
class Meta:
database = db
class Blog(BaseModel):
title = CharField()
contents = TextField()
pub_date = DateTimeField()
A high-level api for working with the supported database engines. Database provides a wrapper around some of the functions performed by the Adapter, in addition providing support for:
Parameters: |
|
---|
Note
if your database name is not known when the class is declared, you can pass None in as the database name which will mark the database as “deferred” and any attempt to connect while in this state will raise an exception. To initialize your database, call the Database.init() method with the database name
If the database was instantiated with database=None, the database is said to be in a ‘deferred’ state (see notes) – if this is the case, you can initialize it at any time by calling the init method.
Parameters: |
|
---|
Establishes a connection to the database
Note
If you initialized with threadlocals=True, then this will store the connection inside a threadlocal, ensuring that connections are not shared across threads.
Closes the connection to the database (if one is open)
Note
If you initialized with threadlocals=True, only a connection local to the calling thread will be closed.
Return type: | a connection to the database, creates one if does not exist |
---|
Return type: | a cursor for executing queries |
---|
Parameters: | autocommit – a boolean value indicating whether to turn on/off autocommit for the current connection |
---|
Return type: | a boolean value indicating whether autocommit is on for the current connection |
---|
Parameters: |
|
---|
Note
You can configure whether queries will automatically commit by using the set_autocommit() and Database.get_autocommit() methods.
Call commit() on the active connection, committing the current transaction
Call rollback() on the active connection, rolling back the current transaction
Decorator that wraps the given function in a single transaction, which, upon success will be committed. If an error is raised inside the function, the transaction will be rolled back and the error will be re-raised.
Parameters: | func – function to decorate |
---|
@database.commit_on_success
def transfer_money(from_acct, to_acct, amt):
from_acct.charge(amt)
to_acct.pay(amt)
return amt
Return a context manager that executes statements in a transaction. If an error is raised inside the context manager, the transaction will be rolled back, otherwise statements are committed when exiting.
# delete a blog instance and all its associated entries, but
# do so within a transaction
with database.transaction():
blog.delete_instance(recursive=True)
Parameters: |
|
---|---|
Return type: | the primary key of the most recently inserted instance |
Return type: | number of rows affected by the last query |
---|
Parameters: |
|
---|
Parameters: |
|
---|
Parameters: |
---|
Parameters: |
|
---|
Note
Cascading drop tables are not supported at this time, so if a constraint exists that prevents a table being dropped, you will need to handle that in application logic.
Parameters: |
|
---|---|
Return type: | SQL suitable for adding the column |
Note
Adding a non-null column to a table with rows may cause an IntegrityError.
Parameters: |
|
---|---|
Return type: | SQL suitable for renaming the column |
Note
There must be a field instance named field_name at the time this SQL is generated.
Note
SQLite does not support renaming columns
Parameters: |
|
---|
Note
SQLite does not support dropping columns
Parameters: | sequence_name – name of sequence to create |
---|
Note
only works with database engines that support sequences
Parameters: | sequence_name – name of sequence to drop |
---|
Note
only works with database engines that support sequences
Parameters: | table – the name of table to introspect |
---|---|
Return type: | a list of (index_name, is_unique) tuples |
Warning
Not implemented – implementations exist in subclasses
Return type: | a list of table names in the database |
---|
Warning
Not implemented – implementations exist in subclasses
Rtype boolean: |
---|
The various subclasses of BaseAdapter provide a bridge between the high- level Database abstraction and the underlying python libraries like psycopg2. It also provides a way to unify the pythonic field types with the underlying column types used by the database engine.
The BaseAdapter provides two types of mappings: - mapping between filter operations and their database equivalents - mapping between basic field types and their database column types
The BaseAdapter also is the mechanism used by the Database class to: - handle connections with the database - extract information from the database cursor
A mapping of query operation to SQL
The string used by the driver to interpolate query parameters
Whether the given backend supports sequences
Table names that are reserved by the backend – if encountered in the application a warning will be issued.
Return type: | a dictionary mapping “user-friendly field type” to specific column type, e.g. {'string': 'VARCHAR', 'float': 'REAL', ... } |
---|
Return type: | a dictionary similar to that returned by get_field_types(). |
---|
Provides a mechanism to override any number of field types without having to override all of them.
Parameters: |
|
---|---|
Return type: | a database connection |
Parameters: | conn – a database connection |
---|
Close the given database connection
Parameters: |
|
---|---|
Return type: | a converted value appropriate for the given lookup |
Used as a hook when a specific lookup requires altering the given value, like for example when performing a LIKE query you may need to insert wildcards.
Return type: | most recently inserted primary key |
---|
Return type: | number of rows affected by most recent query |
---|
Subclass of BaseAdapter that works with the “sqlite3” driver
Subclass of BaseAdapter that works with the “MySQLdb” driver
Subclass of BaseAdapter that works with the “psycopg2” driver