Peewee - SQLite Extensions



Peewee comes with a Playhouse namespace. It is a collection of various extension modules. One of them is a playhouse.sqlite_ext module. It mainly defines SqliteExtDatabase class which inherits SqliteDatabase class, supports following additional features −

Features of SQLite Extensions

The features of SQLite Extensions which are supported by Peewee are as follows −

  • Full-text search.

  • JavaScript Object Notation (JSON) extension integration.

  • Closure table extension support.

  • LSM1 extension support.

  • User-defined table functions.

  • Support for online backups using backup API: backup_to_file().

  • BLOB API support, for efficient binary data storage.

JSON data can be stored, if a special JSONField is declared as one of the field attributes.

class MyModel(Model):
   json_data = JSONField(json_dumps=my_json_dumps)

To activate full-text search, the model can have DocIdField to define primary key.

class NoteIndex(FTSModel):
   docid = DocIDField()
   content = SearchField()

   class Meta:
      database = db

FTSModel is a Subclass of VirtualModel which is available at http://docs.peewee-orm.com/en/latest/peewee/sqlite_ext.html#VirtualModel to be used with the FTS3 and FTS4 full-text search extensions. Sqlite will treat all column types as TEXT (although, you can store other data types, Sqlite will treat them as text).

SearchField is a Field-class to be used for columns on models representing full-text search virtual tables.

SqliteDatabase supports AutoField for increasing primary key. However, SqliteExtDatabase supports AutoIncrementField to ensure that primary always increases monotonically, irrespective of row deletions.

SqliteQ module in playhouse namespace (playhouse.sqliteq) defines subclass of SqliteExeDatabase to handle serialised concurrent writes to a SQlite database.

On the other hand, playhouse.apsw module carries support for apsw sqlite driver. Another Python SQLite Wrapper (APSW) is fast and can handle nested transactions, that are managed explicitly by you code.

from apsw_ext import *
db = APSWDatabase('testdb')

class BaseModel(Model):
   class Meta:
      database = db

class MyModel(BaseModel):
   field1 = CharField()
   field2 = DateTimeField()
Advertisements