1 import struct, contextlib, math
3 from .db import bd, txnfun, dloopfun
5 __all__ = ["maybe", "t_int", "t_uint", "t_float", "t_str", "ordered"]
7 deadlock = bd.DBLockDeadlockError
8 notfound = bd.DBNotFoundError
10 class simpletype(object):
11 def __init__(self, encode, decode):
17 def decode(self, dat):
19 def compare(self, a, b):
29 return cls(lambda ob: struct.pack(fmt, ob),
30 lambda dat: struct.unpack(fmt, dat)[0])
33 def __init__(self, bk):
37 if ob is None: return b""
38 return b"\0" + self.bk.encode(ob)
39 def decode(self, dat):
40 if dat == b"": return None
41 return self.bk.dec(dat[1:])
42 def compare(self, a, b):
50 return self.bk.compare(a[1:], b[1:])
52 class compound(object):
53 def __init__(self, *parts):
58 def minim(self, *parts):
59 return parts + tuple([self.small] * (len(self.parts) - len(parts)))
60 def maxim(self, *parts):
61 return parts + tuple([self.large] * (len(self.parts) - len(parts)))
63 def encode(self, obs):
64 if len(obs) != len(self.parts):
65 raise ValueError("invalid length of compound data: " + str(len(obs)) + ", rather than " + len(self.parts))
67 for ob, part in zip(obs, self.parts):
70 elif ob is self.large:
75 buf.append(0x80 | len(dat))
78 buf.extend(struct.pack(">BI", 0, len(dat)))
81 def decode(self, dat):
84 for part in self.parts:
90 ret.append(self.small)
93 ret.append(self.large)
96 ln = struct.unpack(">I", dat[off:off + 4])[0]
98 ret.append(part.decode(dat[off:off + ln]))
101 def compare(self, al, bl):
102 if (len(al) != len(self.parts)) or (len(bl) != len(self.parts)):
103 raise ValueError("invalid length of compound data: " + str(len(al)) + ", " + str(len(bl)) + ", rather than " + len(self.parts))
104 for a, b, part in zip(al, bl, self.parts):
105 if a in (self.small, self.large) or b in (self.small, self.large):
110 elif b is self.small:
112 elif a is self.large:
114 elif b is self.large:
116 c = part.compare(a, b)
122 if math.isnan(a) and math.isnan(b):
135 t_int = simpletype.struct(">q")
136 t_uint = simpletype.struct(">Q")
137 t_float = simpletype.struct(">d")
138 t_float.compare = floatcmp
139 t_str = simpletype((lambda ob: ob.encode("utf-8")), (lambda dat: dat.decode("utf-8")))
142 def __init__(self, db, name, datatype):
149 class ordered(index, lib.closable):
150 def __init__(self, db, name, datatype, create=True):
151 super().__init__(db, name, datatype)
152 fl = bd.DB_THREAD | bd.DB_AUTO_COMMIT
153 if create: fl |= bd.DB_CREATE
156 if a == b == "": return 0
157 return self.typ.compare(self.typ.decode(a), self.typ.decode(b))
158 db.set_flags(bd.DB_DUPSORT)
159 db.set_bt_compare(compare)
160 self.bk = db._opendb("i-" + name, bd.DB_BTREE, fl, initdb)
161 self.bk.set_get_returns_none(False)
166 class cursor(lib.closable):
167 def __init__(self, idx, fd, fi, ld, li, reverse):
170 self.cur = self.idx.bk.cursor()
179 if self.cur is not None:
186 def _decode(self, d):
188 k = self.typ.decode(k)
189 v = struct.unpack(">Q", v)[0]
195 if self.fd is missing:
196 self.item = self._decode(self.cur.first())
198 k, v = self._decode(self.cur.set_range(self.typ.encode(self.fd)))
200 while self.typ.compare(k, self.fd) == 0:
201 k, v = self._decode(self.cur.next())
204 self.item = StopIteration
209 if self.ld is missing:
210 self.item = self._decode(self.cur.last())
213 k, v = self._decode(self.cur.set_range(self.typ.encode(self.ld)))
215 k, v = self._decode(self.cur.last())
217 while self.typ.compare(k, self.ld) == 0:
218 k, v = self._decode(self.cur.next())
219 while self.typ.compare(k, self.ld) > 0:
220 k, v = self._decode(self.cur.prev())
222 while self.typ.compare(k, self.ld) >= 0:
223 k, v = self._decode(self.cur.prev())
226 self.item = StopIteration
231 k, v = self.item = self._decode(self.cur.next())
232 if (self.ld is not missing and
233 ((self.li and self.typ.compare(k, self.ld) > 0) or
234 (not self.li and self.typ.compare(k, self.ld) >= 0))):
235 self.item = StopIteration
237 self.item = StopIteration
242 self.item = self._decode(self.cur.prev())
243 if (self.fd is not missing and
244 ((self.fi and self.typ.compare(k, self.fd) < 0) or
245 (not self.fi and self.typ.compare(k, self.fd) <= 0))):
246 self.item = StopIteration
248 self.item = StopIteration
251 if self.item is None:
256 if self.item is StopIteration:
257 raise StopIteration()
258 ret, self.item = self.item, None
265 except StopIteration:
268 def get(self, *, match=missing, ge=missing, gt=missing, lt=missing, le=missing, all=False, reverse=False):
270 cur = self.cursor(self, missing, True, missing, True, reverse)
271 elif match is not missing:
272 cur = self.cursor(self, match, True, match, True, reverse)
273 elif ge is not missing or gt is not missing or lt is not missing or le is not missing:
274 if ge is not missing:
276 elif gt is not missing:
279 fd, fi = missing, True
280 if le is not missing:
282 elif lt is not missing:
285 ld, li = missing, True
286 cur = self.cursor(self, fd, fi, ld, li, reverse)
288 raise NameError("invalid get() specification")
301 @txnfun(lambda self: self.db.env.env)
302 def put(self, key, id, *, tx):
303 obid = struct.pack(">Q", id)
304 if not self.db.ob.has_key(obid, txn=tx.tx):
305 raise ValueError("no such object in database: " + str(id))
307 self.bk.put(self.typ.encode(key), obid, txn=tx.tx, flags=bd.DB_NODUPDATA)
308 except bd.DBKeyExistError:
312 @txnfun(lambda self: self.db.env.env)
313 def remove(self, key, id, *, tx):
314 obid = struct.pack(">Q", id)
315 if not self.db.ob.has_key(obid, txn=tx.tx):
316 raise ValueError("no such object in database: " + str(id))
317 cur = self.bk.cursor(txn=tx.tx)
320 cur.get_both(self.typ.encode(key), obid)