sqlite.py 24.2 KB
Newer Older
1
#
Julien Muchembled's avatar
Julien Muchembled committed
2
# Copyright (C) 2012-2015  Nexedi SA
3 4 5 6 7 8 9 10 11 12 13 14
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
15
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
16 17 18 19

import sqlite3
from hashlib import sha1
import string
20
import traceback
21 22

from . import DatabaseManager, LOG_QUERIES
23
from .manager import CreationUndone, splitOIDField
24
from neo.lib import logging, util
25 26 27
from neo.lib.exception import DatabaseFailure
from neo.lib.protocol import CellStates, ZERO_OID, ZERO_TID, ZERO_HASH

28
def unique_constraint_message(table, *columns):
29
    c = sqlite3.connect(":memory:")
30 31 32 33 34
    values = '?' * len(columns)
    insert = "INSERT INTO %s VALUES(%s)" % (table, ', '.join(values))
    x = "%s (%s)" % (table, ', '.join(columns))
    c.execute("CREATE TABLE " + x)
    c.execute("CREATE UNIQUE INDEX i ON " + x)
35
    try:
36
        c.executemany(insert, (values, values))
37 38 39 40
    except sqlite3.IntegrityError, e:
        return e.args[0]
    assert False

41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57
def retry_if_locked(f, *args):
    try:
        return f(*args)
    except sqlite3.OperationalError, e:
        x = e.args[0]
        if x == 'database is locked':
            msg = traceback.format_exception_only(type(e), e)
            msg += traceback.format_stack()
            logging.warning(''.join(msg))
            while e.args[0] == x:
                try:
                    return f(*args)
                except sqlite3.OperationalError, e:
                    pass
        raise


58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78
class SQLiteDatabaseManager(DatabaseManager):
    """This class manages a database on SQLite.

    CAUTION: Make sure we never use statement journal files, as explained at
             http://www.sqlite.org/tempfiles.html for more information.
             In other words, temporary files (by default in /var/tmp !) must
             never be used for small requests.
    """

    def __init__(self, *args, **kw):
        super(SQLiteDatabaseManager, self).__init__(*args, **kw)
        self._config = {}
        self._connect()

    def _parse(self, database):
        self.db = database

    def close(self):
        self.conn.close()

    def _connect(self):
79
        logging.info('connecting to SQLite database %r', self.db)
80
        self.conn = sqlite3.connect(self.db, check_same_thread=False)
81

82 83 84
    def commit(self):
        logging.debug('committing...')
        retry_if_locked(self.conn.commit)
85 86 87 88 89 90 91 92

    if LOG_QUERIES:
        def query(self, query):
            printable_char_list = []
            for c in query.split('\n', 1)[0][:70]:
                if c not in string.printable or c in '\t\x0b\x0c\r':
                    c = '\\x%02x' % ord(c)
                printable_char_list.append(c)
93
            logging.debug('querying %s...', ''.join(printable_char_list))
94 95 96 97
            return self.conn.execute(query)
    else:
        query = property(lambda self: self.conn.execute)

98 99 100 101
    def erase(self):
        for t in 'config', 'pt', 'trans', 'obj', 'data', 'ttrans', 'tobj':
            self.query('DROP TABLE IF EXISTS ' + t)

102
    def _setup(self):
103 104 105 106 107 108
        self._config.clear()
        q = self.query
        # The table "config" stores configuration parameters which affect the
        # persistent data.
        q("""CREATE TABLE IF NOT EXISTS config (
                 name TEXT NOT NULL PRIMARY KEY,
109
                 value TEXT)
110 111 112 113 114
          """)

        # The table "pt" stores a partition table.
        q("""CREATE TABLE IF NOT EXISTS pt (
                 rid INTEGER NOT NULL,
115
                 nid INTEGER NOT NULL,
116
                 state INTEGER NOT NULL,
117
                 PRIMARY KEY (rid, nid))
118 119 120 121 122 123 124 125 126 127 128
          """)

        # The table "trans" stores information on committed transactions.
        q("""CREATE TABLE IF NOT EXISTS trans (
                 partition INTEGER NOT NULL,
                 tid INTEGER NOT NULL,
                 packed BOOLEAN NOT NULL,
                 oids BLOB NOT NULL,
                 user BLOB NOT NULL,
                 description BLOB NOT NULL,
                 ext BLOB NOT NULL,
129
                 ttid INTEGER NOT NULL,
130 131 132 133 134 135 136
                 PRIMARY KEY (partition, tid))
          """)

        # The table "obj" stores committed object metadata.
        q("""CREATE TABLE IF NOT EXISTS obj (
                 partition INTEGER NOT NULL,
                 oid INTEGER NOT NULL,
137
                 tid INTEGER NOT NULL,
138
                 data_id INTEGER,
139 140
                 value_tid INTEGER,
                 PRIMARY KEY (partition, tid, oid))
141 142
          """)
        q("""CREATE INDEX IF NOT EXISTS _obj_i1 ON
143
                 obj(partition, oid, tid)
144 145 146 147 148 149 150 151
          """)
        q("""CREATE INDEX IF NOT EXISTS _obj_i2 ON
                 obj(data_id)
          """)

        # The table "data" stores object data.
        q("""CREATE TABLE IF NOT EXISTS data (
                 id INTEGER PRIMARY KEY AUTOINCREMENT,
152 153
                 hash BLOB NOT NULL,
                 compression INTEGER NOT NULL,
154
                 value BLOB NOT NULL)
155 156 157
          """)
        q("""CREATE UNIQUE INDEX IF NOT EXISTS _data_i1 ON
                 data(hash, compression)
158 159 160 161 162 163 164 165 166 167
          """)

        # The table "ttrans" stores information on uncommitted transactions.
        q("""CREATE TABLE IF NOT EXISTS ttrans (
                 partition INTEGER NOT NULL,
                 tid INTEGER NOT NULL,
                 packed BOOLEAN NOT NULL,
                 oids BLOB NOT NULL,
                 user BLOB NOT NULL,
                 description BLOB NOT NULL,
168 169
                 ext BLOB NOT NULL,
                 ttid INTEGER NOT NULL)
170 171 172 173 174 175
          """)

        # The table "tobj" stores uncommitted object metadata.
        q("""CREATE TABLE IF NOT EXISTS tobj (
                 partition INTEGER NOT NULL,
                 oid INTEGER NOT NULL,
176
                 tid INTEGER NOT NULL,
177
                 data_id INTEGER,
178 179
                 value_tid INTEGER,
                 PRIMARY KEY (tid, oid))
180 181
          """)

182
        self._uncommitted_data.update(q("SELECT data_id, count(*)"
183 184 185 186 187 188 189
            " FROM tobj WHERE data_id IS NOT NULL GROUP BY data_id"))

    def getConfiguration(self, key):
        try:
            return self._config[key]
        except KeyError:
            try:
190 191
                r = self.query("SELECT value FROM config WHERE name=?",
                               (key,)).fetchone()[0]
192 193 194 195 196 197 198 199 200 201 202
            except TypeError:
                r = None
            self._config[key] = r
            return r

    def _setConfiguration(self, key, value):
        q = self.query
        self._config[key] = value
        if value is None:
            q("DELETE FROM config WHERE name=?", (key,))
        else:
203
            q("REPLACE INTO config VALUES (?,?)", (key, str(value)))
204 205

    def getPartitionTable(self):
206
        return self.query("SELECT * FROM pt")
207

208 209 210 211
    def getLastTID(self, max_tid):
        return self.query("SELECT MAX(tid) FROM trans WHERE tid<=?",
                          (max_tid,)).next()[0]

212
    def _getLastIDs(self, all=True):
213
        p64 = util.p64
214
        q = self.query
215
        trans = {partition: p64(tid)
216
            for partition, tid in q("SELECT partition, MAX(tid)"
217 218
                                    " FROM trans GROUP BY partition")}
        obj = {partition: p64(tid)
219
            for partition, tid in q("SELECT partition, MAX(tid)"
220
                                    " FROM obj GROUP BY partition")}
221 222 223 224 225 226 227 228 229 230 231
        oid = q("SELECT MAX(oid) FROM (SELECT MAX(oid) AS oid FROM obj"
                                      " GROUP BY partition) as t").next()[0]
        if all:
            tid = q("SELECT MAX(tid) FROM ttrans").next()[0]
            if tid is not None:
                trans[None] = p64(tid)
            tid, toid = q("SELECT MAX(tid), MAX(oid) FROM tobj").next()
            if tid is not None:
                obj[None] = p64(tid)
            if toid is not None and (oid < toid or oid is None):
                oid = toid
232
        return trans, obj, None if oid is None else p64(oid)
233 234 235

    def getUnfinishedTIDList(self):
        p64 = util.p64
236 237
        return [p64(t[0]) for t in self.query("SELECT tid FROM ttrans"
                                       " UNION SELECT tid FROM tobj")]
238 239 240 241

    def objectPresent(self, oid, tid, all=True):
        oid = util.u64(oid)
        tid = util.u64(tid)
242 243 244 245 246
        q = self.query
        return q("SELECT 1 FROM obj WHERE partition=? AND oid=? AND tid=?",
                 (self._getPartition(oid), oid, tid)).fetchone() or all and \
               q("SELECT 1 FROM tobj WHERE tid=? AND oid=?",
                 (tid, oid)).fetchone()
247

248 249 250 251 252 253 254 255
    def getLastObjectTID(self, oid):
        oid = util.u64(oid)
        r = self.query("SELECT tid FROM obj"
                       " WHERE partition=? AND oid=?"
                       " ORDER BY tid DESC LIMIT 1",
                       (self._getPartition(oid), oid)).fetchone()
        return r and util.p64(r[0])

256 257 258 259 260 261
    def _getNextTID(self, *args): # partition, oid, tid
        r = self.query("""SELECT tid FROM obj
                          WHERE partition=? AND oid=? AND tid>?
                          ORDER BY tid LIMIT 1""", args).fetchone()
        return r and r[0]

262 263 264
    def _getObject(self, oid, tid=None, before_tid=None):
        q = self.query
        partition = self._getPartition(oid)
265
        sql = ('SELECT tid, compression, data.hash, value, value_tid'
266 267 268
               ' FROM obj LEFT JOIN data ON obj.data_id = data.id'
               ' WHERE partition=? AND oid=?')
        if tid is not None:
269
            r = q(sql + ' AND tid=?', (partition, oid, tid))
270
        elif before_tid is not None:
271
            r = q(sql + ' AND tid<? ORDER BY tid DESC LIMIT 1',
272 273
                  (partition, oid, before_tid))
        else:
274
            r = q(sql + ' ORDER BY tid DESC LIMIT 1', (partition, oid))
275 276 277 278 279 280 281
        try:
            serial, compression, checksum, data, value_serial = r.fetchone()
        except TypeError:
            return None
        if checksum:
            checksum = str(checksum)
            data = str(data)
282 283
        return (serial, self._getNextTID(partition, oid, serial),
                compression, checksum, data, value_serial)
284

285
    def changePartitionTable(self, ptid, cell_list, reset=False):
286 287 288
        q = self.query
        if reset:
            q("DELETE FROM pt")
289
        for offset, nid, state in cell_list:
290 291 292 293 294 295
            # TODO: this logic should move out of database manager
            # add 'dropCells(cell_list)' to API and use one query
            # WKRD: Why does SQLite need a statement journal file
            #       whereas we try to replace only 1 value ?
            #       We don't want to remove the 'NOT NULL' constraint
            #       so we must simulate a "REPLACE OR FAIL".
296
            q("DELETE FROM pt WHERE rid=? AND nid=?", (offset, nid))
297 298
            if state != CellStates.DISCARDED:
                q("INSERT OR FAIL INTO pt VALUES (?,?,?)",
299
                  (offset, nid, int(state)))
300
        self.setPTID(ptid)
301 302 303

    def dropPartitions(self, offset_list):
        where = " WHERE partition=?"
304 305 306 307 308 309 310 311
        q = self.query
        for partition in offset_list:
            args = partition,
            data_id_list = [x for x, in
                q("SELECT DISTINCT data_id FROM obj" + where, args) if x]
            q("DELETE FROM obj" + where, args)
            q("DELETE FROM trans" + where, args)
            self._pruneData(data_id_list)
312 313

    def dropUnfinishedData(self):
314 315 316 317
        q = self.query
        data_id_list = [x for x, in q("SELECT data_id FROM tobj") if x]
        q("DELETE FROM tobj")
        q("DELETE FROM ttrans")
318
        self.releaseData(data_id_list, True)
319 320 321 322 323 324

    def storeTransaction(self, tid, object_list, transaction, temporary=True):
        u64 = util.u64
        tid = u64(tid)
        T = 't' if temporary else ''
        obj_sql = "INSERT OR FAIL INTO %sobj VALUES (?,?,?,?,?)" % T
325 326 327 328 329 330 331 332 333 334
        q = self.query
        for oid, data_id, value_serial in object_list:
            oid = u64(oid)
            partition = self._getPartition(oid)
            if value_serial:
                value_serial = u64(value_serial)
                (data_id,), = q("SELECT data_id FROM obj"
                    " WHERE partition=? AND oid=? AND tid=?",
                    (partition, oid, value_serial))
                if temporary:
335
                    self.holdData(data_id)
336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356
            try:
                q(obj_sql, (partition, oid, tid, data_id, value_serial))
            except sqlite3.IntegrityError:
                # This may happen if a previous replication of 'obj' was
                # interrupted.
                if not T:
                    r, = q("SELECT data_id, value_tid FROM obj"
                           " WHERE partition=? AND oid=? AND tid=?",
                           (partition, oid, tid))
                    if r == (data_id, value_serial):
                        continue
                raise
        if transaction:
            oid_list, user, desc, ext, packed, ttid = transaction
            partition = self._getPartition(tid)
            assert packed in (0, 1)
            q("INSERT OR FAIL INTO %strans VALUES (?,?,?,?,?,?,?,?)" % T,
                (partition, tid, packed, buffer(''.join(oid_list)),
                 buffer(user), buffer(desc), buffer(ext), u64(ttid)))
        if temporary:
            self.commit()
357 358 359 360 361 362 363 364 365 366 367

    def _pruneData(self, data_id_list):
        data_id_list = set(data_id_list).difference(self._uncommitted_data)
        if data_id_list:
            q = self.query
            data_id_list.difference_update(x for x, in q(
                "SELECT DISTINCT data_id FROM obj WHERE data_id IN (%s)"
                % ",".join(map(str, data_id_list))))
            q("DELETE FROM data WHERE id IN (%s)"
              % ",".join(map(str, data_id_list)))

368
    def storeData(self, checksum, data, compression,
369
            _dup=unique_constraint_message("data", "hash", "compression")):
370
        H = buffer(checksum)
371 372 373 374
        try:
            return self.query("INSERT INTO data VALUES (NULL,?,?,?)",
                (H, compression,  buffer(data))).lastrowid
        except sqlite3.IntegrityError, e:
375 376 377 378 379
            if e.args[0] == _dup:
                (r, d), = self.query("SELECT id, value FROM data"
                                     " WHERE hash=? AND compression=?",
                                     (H, compression))
                if str(d) == data:
380 381
                    return r
            raise
382 383 384

    def _getDataTID(self, oid, tid=None, before_tid=None):
        partition = self._getPartition(oid)
385
        sql = 'SELECT tid, value_tid FROM obj' \
386 387
              ' WHERE partition=? AND oid=?'
        if tid is not None:
388
            r = self.query(sql + ' AND tid=?', (partition, oid, tid))
389
        elif before_tid is not None:
390
            r = self.query(sql + ' AND tid<? ORDER BY tid DESC LIMIT 1',
391 392
                           (partition, oid, before_tid))
        else:
393
            r = self.query(sql + ' ORDER BY tid DESC LIMIT 1',
394 395
                           (partition, oid))
        r = r.fetchone()
396
        return r or (None, None)
397 398 399

    def finishTransaction(self, tid):
        args = util.u64(tid),
400 401 402 403 404 405 406
        q = self.query
        sql = " FROM tobj WHERE tid=?"
        data_id_list = [x for x, in q("SELECT data_id" + sql, args) if x]
        q("INSERT OR FAIL INTO obj SELECT *" + sql, args)
        q("DELETE FROM tobj WHERE tid=?", args)
        q("INSERT OR FAIL INTO trans SELECT * FROM ttrans WHERE tid=?", args)
        q("DELETE FROM ttrans WHERE tid=?", args)
407
        self.releaseData(data_id_list)
408
        self.commit()
409 410 411 412 413

    def deleteTransaction(self, tid, oid_list=()):
        u64 = util.u64
        tid = u64(tid)
        getPartition = self._getPartition
414 415 416
        q = self.query
        sql = " FROM tobj WHERE tid=?"
        data_id_list = [x for x, in q("SELECT data_id" + sql, (tid,)) if x]
417
        self.releaseData(data_id_list)
418 419 420 421 422 423 424 425 426 427 428 429 430 431
        q("DELETE" + sql, (tid,))
        q("DELETE FROM ttrans WHERE tid=?", (tid,))
        q("DELETE FROM trans WHERE partition=? AND tid=?",
            (getPartition(tid), tid))
        # delete from obj using indexes
        data_id_set = set()
        for oid in oid_list:
            oid = u64(oid)
            sql = " FROM obj WHERE partition=? AND oid=? AND tid=?"
            args = getPartition(oid), oid, tid
            data_id_set.update(*q("SELECT data_id" + sql, args))
            q("DELETE" + sql, args)
        data_id_set.discard(None)
        self._pruneData(data_id_set)
432 433 434 435 436 437

    def deleteObject(self, oid, serial=None):
        oid = util.u64(oid)
        sql = " FROM obj WHERE partition=? AND oid=?"
        args = [self._getPartition(oid), oid]
        if serial:
438
            sql += " AND tid=?"
439
            args.append(util.u64(serial))
440 441 442 443 444
        q = self.query
        data_id_list = [x for x, in q("SELECT DISTINCT data_id" + sql, args)
                          if x]
        q("DELETE" + sql, args)
        self._pruneData(data_id_list)
445 446 447 448 449 450 451 452 453 454 455 456

    def _deleteRange(self, partition, min_tid=None, max_tid=None):
        sql = " WHERE partition=?"
        args = [partition]
        if min_tid:
            sql += " AND ? < tid"
            args.append(util.u64(min_tid))
        if max_tid:
            sql += " AND tid <= ?"
            args.append(util.u64(max_tid))
        q = self.query
        q("DELETE FROM trans" + sql, args)
457
        sql = " FROM obj" + sql
458 459 460 461 462 463 464
        data_id_list = [x for x, in q("SELECT DISTINCT data_id" + sql, args)
                          if x]
        q("DELETE" + sql, args)
        self._pruneData(data_id_list)

    def getTransaction(self, tid, all=False):
        tid = util.u64(tid)
465 466 467 468 469
        q = self.query
        r = q("SELECT oids, user, description, ext, packed, ttid"
              " FROM trans WHERE partition=? AND tid=?",
              (self._getPartition(tid), tid)).fetchone()
        if not r and all:
470
            r = q("SELECT oids, user, description, ext, packed, ttid"
471
                  " FROM ttrans WHERE tid=?", (tid,)).fetchone()
472
        if r:
473
            oids, user, description, ext, packed, ttid = r
474
            return splitOIDField(tid, oids), str(user), \
475
                str(description), str(ext), packed, util.p64(ttid)
476

477
    def getObjectHistory(self, oid, offset, length):
478 479 480 481 482
        # FIXME: This method doesn't take client's current transaction id as
        # parameter, which means it can return transactions in the future of
        # client's transaction.
        p64 = util.p64
        oid = util.u64(oid)
483 484
        return [(p64(tid), length or 0) for tid, length in self.query("""\
            SELECT tid, LENGTH(value)
485 486 487
                FROM obj LEFT JOIN data ON obj.data_id = data.id
                WHERE partition=? AND oid=? AND tid>=?
                ORDER BY tid DESC LIMIT ?,?""",
488 489
            (self._getPartition(oid), oid, self._getPackTID(), offset, length))
            ] or None
490 491 492 493 494 495 496

    def getReplicationObjectList(self, min_tid, max_tid, length, partition,
            min_oid):
        u64 = util.u64
        p64 = util.p64
        min_tid = u64(min_tid)
        return [(p64(serial), p64(oid)) for serial, oid in self.query("""\
497 498 499 500
            SELECT tid, oid FROM obj
            WHERE partition=? AND tid<=?
            AND (tid=? AND ?<=oid OR ?<tid)
            ORDER BY tid ASC, oid ASC LIMIT ?""",
501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529
            (partition, u64(max_tid), min_tid, u64(min_oid), min_tid, length))]

    def getTIDList(self, offset, length, partition_list):
        p64 = util.p64
        return [p64(t[0]) for t in self.query("""\
            SELECT tid FROM trans WHERE partition in (%s)
            ORDER BY tid DESC LIMIT %d,%d"""
            % (','.join(map(str, partition_list)), offset, length))]

    def getReplicationTIDList(self, min_tid, max_tid, length, partition):
        u64 = util.u64
        p64 = util.p64
        min_tid = u64(min_tid)
        max_tid = u64(max_tid)
        return [p64(t[0]) for t in self.query("""\
            SELECT tid FROM trans
            WHERE partition=? AND ?<=tid AND tid<=?
            ORDER BY tid ASC LIMIT ?""",
            (partition, min_tid, max_tid, length))]

    def _updatePackFuture(self, oid, orig_serial, max_serial):
        # Before deleting this objects revision, see if there is any
        # transaction referencing its value at max_serial or above.
        # If there is, copy value to the first future transaction. Any further
        # reference is just updated to point to the new data location.
        partition = self._getPartition(oid)
        value_serial = None
        q = self.query
        for T in '', 't':
530 531 532 533 534
            update = """UPDATE OR FAIL %sobj SET value_tid=?
                         WHERE partition=? AND oid=? AND tid=?""" % T
            for serial, in q("""SELECT tid FROM %sobj
                    WHERE partition=? AND oid=? AND tid>=? AND value_tid=?
                    ORDER BY tid ASC""" % T,
535 536 537 538 539 540 541 542 543 544 545 546 547
                    (partition, oid, max_serial, orig_serial)):
                q(update, (value_serial, partition, oid, serial))
                if value_serial is None:
                    # First found, mark its serial for future reference.
                    value_serial = serial
        return value_serial

    def pack(self, tid, updateObjectDataForPack):
        # TODO: unit test (along with updatePackFuture)
        p64 = util.p64
        tid = util.u64(tid)
        updatePackFuture = self._updatePackFuture
        getPartition = self._getPartition
548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574
        q = self.query
        self._setPackTID(tid)
        for count, oid, max_serial in q("SELECT COUNT(*) - 1, oid, MAX(tid)"
                                        " FROM obj WHERE tid<=? GROUP BY oid",
                                        (tid,)):
            partition = getPartition(oid)
            if q("SELECT 1 FROM obj WHERE partition=?"
                 " AND oid=? AND tid=? AND data_id IS NULL",
                 (partition, oid, max_serial)).fetchone():
                max_serial += 1
            elif not count:
                continue
            # There are things to delete for this object
            data_id_set = set()
            sql = " FROM obj WHERE partition=? AND oid=? AND tid<?"
            args = partition, oid, max_serial
            for serial, data_id in q("SELECT tid, data_id" + sql, args):
                data_id_set.add(data_id)
                new_serial = updatePackFuture(oid, serial, max_serial)
                if new_serial:
                    new_serial = p64(new_serial)
                updateObjectDataForPack(p64(oid), p64(serial),
                                        new_serial, data_id)
            q("DELETE" + sql, args)
            data_id_set.discard(None)
            self._pruneData(data_id_set)
        self.commit()
575

576
    def checkTIDRange(self, partition, length, min_tid, max_tid):
577
        # XXX: SQLite's GROUP_CONCAT is slow (looks like quadratic)
578 579 580 581 582 583 584 585 586 587 588
        count, tids, max_tid = self.query("""\
            SELECT COUNT(*), GROUP_CONCAT(tid), MAX(tid)
            FROM (SELECT tid FROM trans
                  WHERE partition=? AND ?<=tid AND tid<=?
                  ORDER BY tid ASC LIMIT ?) AS t""",
            (partition, util.u64(min_tid), util.u64(max_tid),
             -1 if length is None else length)).fetchone()
        if count:
            return count, sha1(tids).digest(), util.p64(max_tid)
        return 0, ZERO_HASH, ZERO_TID

589
    def checkSerialRange(self, partition, length, min_tid, max_tid, min_oid):
590
        u64 = util.u64
591
        # We don't ask SQLite to compute everything (like in checkTIDRange)
592 593 594
        # because it's difficult to get the last serial _for the last oid_.
        # We would need a function (that could be named 'LAST') that returns the
        # last grouped value, instead of the greatest one.
595
        min_tid = u64(min_tid)
596
        r = self.query("""\
597
            SELECT tid, oid
598
            FROM obj
599 600 601
            WHERE partition=? AND tid<=? AND (tid>? OR tid=? AND oid>=?)
            ORDER BY tid, oid LIMIT ?""",
            (partition, u64(max_tid), min_tid, min_tid, u64(min_oid),
602 603 604 605 606 607 608 609
             -1 if length is None else length)).fetchall()
        if r:
            p64 = util.p64
            return (len(r),
                    sha1(','.join(str(x[0]) for x in r)).digest(),
                    p64(r[-1][0]),
                    sha1(','.join(str(x[1]) for x in r)).digest(),
                    p64(r[-1][1]))
610
        return 0, ZERO_HASH, ZERO_TID, ZERO_HASH, ZERO_OID