1 import struct, contextlib, math
3 from .db import bd, txnfun, dloopfun
5 __all__ = ["maybe", "t_int", "t_uint", "t_dbid", "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")
138 t_float = simpletype.struct(">d")
139 t_float.compare = floatcmp
140 t_str = simpletype((lambda ob: ob.encode("utf-8")), (lambda dat: dat.decode("utf-8")))
143 def __init__(self, db, name, datatype):
150 class ordered(index, lib.closable):
151 def __init__(self, db, name, datatype, create=True):
152 super().__init__(db, name, datatype)
153 fl = bd.DB_THREAD | bd.DB_AUTO_COMMIT
154 if create: fl |= bd.DB_CREATE
157 if a == b == "": return 0
158 return self.typ.compare(self.typ.decode(a), self.typ.decode(b))
159 db.set_flags(bd.DB_DUPSORT)
160 db.set_bt_compare(compare)
161 self.bk = db._opendb("i-" + name, bd.DB_BTREE, fl, initdb)
162 self.bk.set_get_returns_none(False)
167 class cursor(lib.closable):
168 def __init__(self, idx, fd, fi, ld, li, reverse):
171 self.cur = self.idx.bk.cursor()
180 if self.cur is not None:
187 def _decode(self, d):
189 k = self.typ.decode(k)
190 v = struct.unpack(">Q", v)[0]
196 if self.fd is missing:
197 self.item = self._decode(self.cur.first())
199 k, v = self._decode(self.cur.set_range(self.typ.encode(self.fd)))
201 while self.typ.compare(k, self.fd) == 0:
202 k, v = self._decode(self.cur.next())
205 self.item = StopIteration
210 if self.ld is missing:
211 self.item = self._decode(self.cur.last())
214 k, v = self._decode(self.cur.set_range(self.typ.encode(self.ld)))
216 k, v = self._decode(self.cur.last())
218 while self.typ.compare(k, self.ld) == 0:
219 k, v = self._decode(self.cur.next())
220 while self.typ.compare(k, self.ld) > 0:
221 k, v = self._decode(self.cur.prev())
223 while self.typ.compare(k, self.ld) >= 0:
224 k, v = self._decode(self.cur.prev())
227 self.item = StopIteration
232 k, v = self.item = self._decode(self.cur.next())
233 if (self.ld is not missing and
234 ((self.li and self.typ.compare(k, self.ld) > 0) or
235 (not self.li and self.typ.compare(k, self.ld) >= 0))):
236 self.item = StopIteration
238 self.item = StopIteration
243 self.item = self._decode(self.cur.prev())
244 if (self.fd is not missing and
245 ((self.fi and self.typ.compare(k, self.fd) < 0) or
246 (not self.fi and self.typ.compare(k, self.fd) <= 0))):
247 self.item = StopIteration
249 self.item = StopIteration
252 if self.item is None:
257 if self.item is StopIteration:
258 raise StopIteration()
259 ret, self.item = self.item, None
266 except StopIteration:
269 def get(self, *, match=missing, ge=missing, gt=missing, lt=missing, le=missing, all=False, reverse=False):
271 cur = self.cursor(self, missing, True, missing, True, reverse)
272 elif match is not missing:
273 cur = self.cursor(self, match, True, match, True, reverse)
274 elif ge is not missing or gt is not missing or lt is not missing or le is not missing:
275 if ge is not missing:
277 elif gt is not missing:
280 fd, fi = missing, True
281 if le is not missing:
283 elif lt is not missing:
286 ld, li = missing, True
287 cur = self.cursor(self, fd, fi, ld, li, reverse)
289 raise NameError("invalid get() specification")
302 @txnfun(lambda self: self.db.env.env)
303 def put(self, key, id, *, tx):
304 obid = struct.pack(">Q", id)
305 if not self.db.ob.has_key(obid, txn=tx.tx):
306 raise ValueError("no such object in database: " + str(id))
308 self.bk.put(self.typ.encode(key), obid, txn=tx.tx, flags=bd.DB_NODUPDATA)
309 except bd.DBKeyExistError:
313 @txnfun(lambda self: self.db.env.env)
314 def remove(self, key, id, *, tx):
315 obid = struct.pack(">Q", id)
316 if not self.db.ob.has_key(obid, txn=tx.tx):
317 raise ValueError("no such object in database: " + str(id))
318 cur = self.bk.cursor(txn=tx.tx)
321 cur.get_both(self.typ.encode(key), obid)