| 25 | |
| 26 | |
| 27 | class Db(object): |
| 28 | def __init__(self, db, injector): |
| 29 | self.db = db |
| 30 | self.injector = injector |
| 31 | self.tasks = queue.Queue() |
| 32 | self.position = None |
| 33 | self.pending_events = [] |
| 34 | self.running = True |
| 35 | self.thread = threading.Thread(target=self._process) |
| 36 | self.thread.daemon = True |
| 37 | self.thread.start() |
| 38 | |
| 39 | def close(self): |
| 40 | self.tasks.put(lambda conn: self._close()) |
| 41 | |
| 42 | def reset(self): |
| 43 | self.tasks.put(lambda conn: self._reset()) |
| 44 | |
| 45 | def load(self, records, event=None): |
| 46 | self.tasks.put(lambda conn: self._load(conn, records, event)) |
| 47 | |
| 48 | def get_id(self, event): |
| 49 | self.tasks.put(lambda conn: self._get_id(conn, event)) |
| 50 | |
| 51 | def insert(self, id, data, event=None): |
| 52 | self.tasks.put(lambda conn: self._insert(conn, id, data, event)) |
| 53 | |
| 54 | def delete(self, id, event=None): |
| 55 | self.tasks.put(lambda conn: self._delete(conn, id, event)) |
| 56 | |
| 57 | def _reset(self, ignored=None): |
| 58 | self.position = None |
| 59 | |
| 60 | def _close(self, ignored=None): |
| 61 | self.running = False |
| 62 | |
| 63 | def _get_id(self, conn, event): |
| 64 | cursor = conn.execute("SELECT * FROM records ORDER BY id DESC") |
| 65 | row = cursor.fetchone() |
| 66 | if event: |
| 67 | if row: |
| 68 | event.id = row['id'] |
| 69 | else: |
| 70 | event.id = 0 |
| 71 | self.injector.trigger(event) |
| 72 | |
| 73 | def _load(self, conn, records, event): |
| 74 | if self.position: |
| 75 | cursor = conn.execute("SELECT * FROM records WHERE id > ? ORDER BY id", (self.position,)) |
| 76 | else: |
| 77 | cursor = conn.execute("SELECT * FROM records ORDER BY id") |
| 78 | while not records.full(): |
| 79 | row = cursor.fetchone() |
| 80 | if row: |
| 81 | self.position = row['id'] |
| 82 | records.put(dict(row)) |
| 83 | else: |
| 84 | break |