]> scripts.mit.edu Git - wizard.git/blob - wizard/cache.py
Rewrite parametrize to use new parametrizeWithVars
[wizard.git] / wizard / cache.py
1 """
2 Provides caching of old results from mass commands, so that
3 we don't have to do them again.  Successes are cached as
4 the string "OK"; errors are stored as the string exception name.
5 Entries are indexed by location.
6
7 .. testsetup:: *
8
9     from wizard.cache import *
10 """
11
12 import sqlite3
13
14 def make(file=None):
15     """
16     Generates a :class:`SerializedDict` if ``file`` is not ``None``,
17     and a normal dictionary otherwise.
18     """
19     if file:
20         return SerializedDict(file)
21     else:
22         return {}
23
24 class SerializedDict(object):
25     """
26     Implements a dictionary that serializes itself to disk.  We
27     use sqlite in order to implement relatively efficient updates.
28
29         >>> import os
30         >>> f = "/tmp/wizard-cache-test.db"
31         >>> if os.path.exists(f): os.unlink(f)
32         >>> d = SerializedDict(f)
33         >>> try:
34         ...   d["foo"]
35         ...   raise Exception("didn't raise")
36         ... except KeyError:
37         ...   pass
38         >>> d["foo"] = "baz"
39         >>> d["foo"]
40         'baz'
41         >>> d["foo"] = "bar"
42         >>> d["foo"]
43         'bar'
44         >>> e = SerializedDict(f)
45         >>> e["foo"]
46         'bar'
47         >>> del e["foo"]
48         >>> "foo" in e
49         False
50         >>> os.unlink(f)
51     """
52     #: Connection to sqlite database
53     conn = None
54     def __init__(self, file):
55         self.conn = sqlite3.connect(file)
56         try:
57             self.conn.execute('create table dict(key string primary key, value string)')
58         except sqlite3.OperationalError as e:
59             if e.args[0] != "table dict already exists":
60                 raise
61         self.conn.isolation_level = None
62     def __getitem__(self, key):
63         row = self.conn.execute('select value from dict where key = ?', (key,)).fetchone()
64         if row:
65             return str(row[0])
66         else:
67             raise KeyError
68     def __setitem__(self, key, value):
69         self.conn.execute('insert or replace into dict (key, value) values (?, ?)', (key, value))
70     def __delitem__(self, key):
71         self.conn.execute('delete from dict where key = ?', (key,))
72     def __contains__(self, key):
73         return bool(self.conn.execute('select count(*) from dict where key = ?', (key,)).fetchone()[0])