Advertisement
Guest User

Untitled

a guest
Aug 24th, 2019
102
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.56 KB | None | 0 0
  1. import collections.abc
  2. import sqlite3
  3.  
  4. from contextlib import suppress
  5. from operator import itemgetter
  6.  
  7.  
  8. class SQLDict(collections.abc.MutableMapping):
  9.  
  10. def __init__(self, dbname, items=[], **kwargs) -> None:
  11. self.dbname = dbname
  12. self.conn = sqlite3.connect(dbname)
  13. cursor = self.conn.cursor()
  14. with suppress(sqlite3.OperationalError):
  15. cursor.execute("CREATE TABLE Dict (key TEXT, value TEXT)")
  16. cursor.execute("CREATE UNIQUE INDEX Kndx ON Dict (key)")
  17. self.update(items, **kwargs)
  18.  
  19. def __setitem__(self, key: str, value: str) -> None:
  20. if key in self:
  21. del self[key]
  22. with self.conn as c:
  23. c.execute("INSERT INTO Dict VALUES(?, ?)", (key, value))
  24.  
  25. def __getitem__(self, key: str) -> str:
  26. c = self.conn.execute("SELECT value FROM Dict WHERE key=?", (key,))
  27. row = c.fetchone()
  28. if row is None:
  29. raise KeyError(key)
  30. return row[0]
  31.  
  32. def __delitem__(self, key: str) -> None:
  33. if key not in self:
  34. raise KeyError(key)
  35. with self.conn as c:
  36. c.execute("DELETE FROM Dict WHERE key=?", (key,))
  37.  
  38. def __len__(self) -> int:
  39. return next(self.conn.execute("SELECT COUNT(*) FROM Dict"))[0]
  40.  
  41. def __iter__(self):
  42. c = self.conn.execute("SELECT key FROM Dict")
  43. return map(itemgetter(0), c.fetchall())
  44.  
  45. def __repr__(self) -> str:
  46. return f"{type(self).__name__}(dbname={self.dbname!r}, items={list(self.items())})"
  47.  
  48. def close(self):
  49. self.conn.close()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement