Debian Codegraph @

hypothesis-python/docs/how-to/custom-database.rst

raw
1 Write a custom Hypothesis database
2 ==================================
3
4 To define your own |ExampleDatabase| class, implement the |ExampleDatabase.save|, |ExampleDatabase.fetch|, and |ExampleDatabase.delete| methods.
5
6 For example, here's a simple database class that uses :mod:`sqlite <sqlite3>` as the backing data store:
7
8 .. code-block:: python
9
10 import sqlite3
11 from collections.abc import Iterable
12
13 from hypothesis.database import ExampleDatabase
14
15 class SQLiteExampleDatabase(ExampleDatabase):
16 def __init__(self, db_path: str):
17 self.conn = sqlite3.connect(db_path)
18
19 self.conn.execute(
20 """
21 CREATE TABLE examples (
22 key BLOB,
23 value BLOB,
24 UNIQUE (key, value)
25 )
26 """
27 )
28
29 def save(self, key: bytes, value: bytes) -> None:
30 self.conn.execute(
31 "INSERT OR IGNORE INTO examples VALUES (?, ?)",
32 (key, value),
33 )
34
35 def fetch(self, key: bytes) -> Iterable[bytes]:
36 cursor = self.conn.execute("SELECT value FROM examples WHERE key = ?", (key,))
37 yield from [value[0] for value in cursor.fetchall()]
38
39 def delete(self, key: bytes, value: bytes) -> None:
40 self.conn.execute(
41 "DELETE FROM examples WHERE key = ? AND value = ?",
42 (key, value),
43 )
44
45 Database classes are not required to implement |ExampleDatabase.move|. The default implementation of a move is a |ExampleDatabase.delete| of the value in the old key, followed by a |ExampleDatabase.save| of the value in the new key. You can override |ExampleDatabase.move| to override this behavior, if for instance the backing store offers a more efficient move implementation.
46
47 Change listening
48 ----------------
49
50 To support change listening in a database class, you should call |ExampleDatabase._broadcast_change| whenever a value is saved, deleted, or moved in the backing database store. How you track this depends on the details of the database class. For instance, in |DirectoryBasedExampleDatabase|, Hypothesis installs a filesystem monitor via :pypi:`watchdog` in order to broadcast change events.
51
52 Two useful related methods are |ExampleDatabase._start_listening| and |ExampleDatabase._stop_listening|, which a database class can override to know when to start or stop expensive listening operations. See documentation for details.