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):
56 def encode(self, obs):
57 if len(obs) != len(self.parts):
58 raise ValueError("invalid length of compound data: " + str(len(obs)) + ", rather than " + len(self.parts))
60 for ob, part in zip(obs, self.parts):
63 buf.append(0x80 | len(dat))
66 buf.extend(struct.pack(">i", len(dat)))
69 def decode(self, dat):
72 for part in self.parts:
77 ln = struct.unpack(">i", dat[off:off + 4])[0]
79 ret.append(part.decode(dat[off:off + len]))
82 def compare(self, al, bl):
83 if (len(al) != len(self.parts)) or (len(bl) != len(self.parts)):
84 raise ValueError("invalid length of compound data: " + str(len(al)) + ", " + str(len(bl)) + ", rather than " + len(self.parts))
85 for a, b, part in zip(al, bl, self.parts):
86 c = part.compare(a, b)
92 if math.isnan(a) and math.isnan(b):
105 t_int = simpletype.struct(">q")
106 t_uint = simpletype.struct(">Q")
107 t_float = simpletype.struct(">d")
108 t_float.compare = floatcmp
109 t_str = simpletype((lambda ob: ob.encode("utf-8")), (lambda dat: dat.decode("utf-8")))
112 def __init__(self, db, name, datatype):
119 class ordered(index, lib.closable):
120 def __init__(self, db, name, datatype, create=True):
121 super().__init__(db, name, datatype)
122 fl = bd.DB_THREAD | bd.DB_AUTO_COMMIT
123 if create: fl |= bd.DB_CREATE
126 if a == b == "": return 0
127 return self.typ.compare(self.typ.decode(a), self.typ.decode(b))
128 db.set_flags(bd.DB_DUPSORT)
129 db.set_bt_compare(compare)
130 self.bk = db._opendb("i-" + name, bd.DB_BTREE, fl, initdb)
131 self.bk.set_get_returns_none(False)
136 class cursor(lib.closable):
137 def __init__(self, idx, fd, fi, ld, li, reverse):
140 self.cur = self.idx.bk.cursor()
149 if self.cur is not None:
156 def _decode(self, d):
158 k = self.typ.decode(k)
159 v = struct.unpack(">Q", v)[0]
165 if self.fd is missing:
166 self.item = self._decode(self.cur.first())
168 k, v = self._decode(self.cur.set_range(self.typ.encode(self.fd)))
170 while self.typ.compare(k, self.fd) == 0:
171 k, v = self._decode(self.cur.next())
174 self.item = StopIteration
179 if self.ld is missing:
180 self.item = self._decode(self.cur.last())
183 k, v = self._decode(self.cur.set_range(self.typ.encode(self.ld)))
185 k, v = self._decode(self.cur.last())
187 while self.typ.compare(k, self.ld) == 0:
188 k, v = self._decode(self.cur.next())
189 while self.typ.compare(k, self.ld) > 0:
190 k, v = self._decode(self.cur.prev())
192 while self.typ.compare(k, self.ld) >= 0:
193 k, v = self._decode(self.cur.prev())
196 self.item = StopIteration
201 k, v = self.item = self._decode(self.cur.next())
202 if (self.ld is not missing and
203 ((self.li and self.typ.compare(k, self.ld) > 0) or
204 (not self.li and self.typ.compare(k, self.ld) >= 0))):
205 self.item = StopIteration
207 self.item = StopIteration
212 self.item = self._decode(self.cur.prev())
213 if (self.fd is not missing and
214 ((self.fi and self.typ.compare(k, self.fd) < 0) or
215 (not self.fi and self.typ.compare(k, self.fd) <= 0))):
216 self.item = StopIteration
218 self.item = StopIteration
221 if self.item is None:
226 if self.item is StopIteration:
227 raise StopIteration()
228 ret, self.item = self.item, None
235 except StopIteration:
238 def get(self, *, match=missing, ge=missing, gt=missing, lt=missing, le=missing, all=False, reverse=False):
240 cur = self.cursor(self, missing, True, missing, True, reverse)
241 elif match is not missing:
242 cur = self.cursor(self, match, True, match, True, reverse)
243 elif ge is not missing or gt is not missing or lt is not missing or le is not missing:
244 if ge is not missing:
246 elif gt is not missing:
249 fd, fi = missing, True
250 if le is not missing:
252 elif lt is not missing:
255 ld, li = missing, True
256 cur = self.cursor(self, fd, fi, ld, li, reverse)
258 raise NameError("invalid get() specification")
271 @txnfun(lambda self: self.db.env.env)
272 def put(self, key, id, *, tx):
273 obid = struct.pack(">Q", id)
274 if not self.db.ob.has_key(obid, txn=tx.tx):
275 raise ValueError("no such object in database: " + str(id))
277 self.bk.put(self.typ.encode(key), obid, txn=tx.tx, flags=bd.DB_NODUPDATA)
278 except bd.DBKeyExistError:
282 @txnfun(lambda self: self.db.env.env)
283 def remove(self, key, id, *, tx):
284 obid = struct.pack(">Q", id)
285 if not self.db.ob.has_key(obid, txn=tx.tx):
286 raise ValueError("no such object in database: " + str(id))
287 cur = self.bk.cursor(txn=tx.tx)
290 cur.get_both(self.typ.encode(key), obid)