Guest User

Untitled

a guest
Jun 21st, 2018
74
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.77 KB | None | 0 0
  1. class Unique(object):
  2. def __init__(self, name, n=1, ttl=float("inf")):
  3. conn = sqlite3.connect(name)
  4. c = conn.cursor()
  5. rc = pathlib.Path.home() / ".sqliterc"
  6. if rc.exists():
  7. c.executescript(rc.read_text())
  8. fields = ",".join(f"_{i}" for i in range(n))
  9. c.execute(f"create table if not exists _({fields},_,primary key({fields}))")
  10. holders = ",".join("?" * n)
  11. conditions = " and ".join(f"_{i}=?" for i in range(n))
  12. self.sql_select = f"select _ from _ where {conditions}"
  13. self.sql_insert = f"insert or replace into _({fields},_) values({holders},?)"
  14. self.ttl = ttl
  15. self.conn, self.c = conn, c
  16.  
  17. def add(self, *values):
  18. if values not in self:
  19. self.c.execute(self.sql_insert, values + (time.time(),))
  20. self.conn.commit()
  21. return True
  22.  
  23. def __contains__(self, values):
  24. o = self.c.execute(self.sql_select, values).fetchone()
  25. if o and o[0] + self.ttl > time.time():
  26. return True
  27.  
  28. class KV(object):
  29. def __init__(self, name, ttl=float("inf")):
  30. conn = sqlite3.connect(name)
  31. c = conn.cursor()
  32. rc = pathlib.Path.home() / ".sqliterc"
  33. if rc.exists():
  34. c.executescript(rc.read_text())
  35. c.execute("create table if not exists _(k,v,_,primary key(k))")
  36. self.ttl = ttl
  37. self.conn, self.c = conn, c
  38.  
  39. def __getitem__(self, key):
  40. sql = "select _,v from _ where k=?"
  41. o = self.c.execute(sql, (key,)).fetchone()
  42. if o and o[0] + self.ttl > time.time():
  43. return o[1]
  44.  
  45. def __setitem__(self, key, value):
  46. sql = "insert or replace into _(k,v,_) values(?,?,?)"
  47. self.c.execute(sql, (key, value, time.time()))
  48. self.conn.commit()
Add Comment
Please, Sign In to add comment