Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Unique(object):
- def __init__(self, name, n=1, ttl=float("inf")):
- conn = sqlite3.connect(name)
- c = conn.cursor()
- rc = pathlib.Path.home() / ".sqliterc"
- if rc.exists():
- c.executescript(rc.read_text())
- fields = ",".join(f"_{i}" for i in range(n))
- c.execute(f"create table if not exists _({fields},_,primary key({fields}))")
- holders = ",".join("?" * n)
- conditions = " and ".join(f"_{i}=?" for i in range(n))
- self.sql_select = f"select _ from _ where {conditions}"
- self.sql_insert = f"insert or replace into _({fields},_) values({holders},?)"
- self.ttl = ttl
- self.conn, self.c = conn, c
- def add(self, *values):
- if values not in self:
- self.c.execute(self.sql_insert, values + (time.time(),))
- self.conn.commit()
- return True
- def __contains__(self, values):
- o = self.c.execute(self.sql_select, values).fetchone()
- if o and o[0] + self.ttl > time.time():
- return True
- class KV(object):
- def __init__(self, name, ttl=float("inf")):
- conn = sqlite3.connect(name)
- c = conn.cursor()
- rc = pathlib.Path.home() / ".sqliterc"
- if rc.exists():
- c.executescript(rc.read_text())
- c.execute("create table if not exists _(k,v,_,primary key(k))")
- self.ttl = ttl
- self.conn, self.c = conn, c
- def __getitem__(self, key):
- sql = "select _,v from _ where k=?"
- o = self.c.execute(sql, (key,)).fetchone()
- if o and o[0] + self.ttl > time.time():
- return o[1]
- def __setitem__(self, key, value):
- sql = "insert or replace into _(k,v,_) values(?,?,?)"
- self.c.execute(sql, (key, value, time.time()))
- self.conn.commit()
Add Comment
Please, Sign In to add comment