sqlite.py 27.7 KB
Newer Older
1
#
2
# Copyright (C) 2012-2017  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
from collections import OrderedDict
18
import os
19 20 21
import sqlite3
from hashlib import sha1
import string
22
import traceback
23

24
from . import LOG_QUERIES
25
from .manager import DatabaseManager, splitOIDField
26
from neo.lib import logging, util
27
from neo.lib.interfaces import implements
28
from neo.lib.protocol import ZERO_OID, ZERO_TID, ZERO_HASH
29

30
def unique_constraint_message(table, *columns):
31
    c = sqlite3.connect(":memory:")
32 33 34 35 36
    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)
37
    try:
38
        c.executemany(insert, (values, values))
39 40 41 42
    except sqlite3.IntegrityError, e:
        return e.args[0]
    assert False

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


61
@implements
62 63 64 65
class SQLiteDatabaseManager(DatabaseManager):
    """This class manages a database on SQLite.

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

71
    VERSION = 3
72

73
    def _parse(self, database):
74
        self.db = os.path.expanduser(database)
75

76
    def _close(self):
77 78 79
        self.conn.close()

    def _connect(self):
80
        logging.info('connecting to SQLite database %r', self.db)
81
        self.conn = sqlite3.connect(self.db, check_same_thread=False)
82
        self.lock(self.db)
83 84 85 86
        if self.UNSAFE:
            q = self.query
            q("PRAGMA synchronous = OFF")
            q("PRAGMA journal_mode = MEMORY")
87
        self._config = {}
88

89
    def _commit(self):
90
        retry_if_locked(self.conn.commit)
91 92 93 94 95 96 97 98

    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)
99
            logging.debug('querying %s...', ''.join(printable_char_list))
100 101 102 103
            return self.conn.execute(query)
    else:
        query = property(lambda self: self.conn.execute)

104 105 106 107
    def erase(self):
        for t in 'config', 'pt', 'trans', 'obj', 'data', 'ttrans', 'tobj':
            self.query('DROP TABLE IF EXISTS ' + t)

108 109 110 111 112 113 114 115
    def nonempty(self, table):
        try:
            return bool(self.query(
                "SELECT 1 FROM %s LIMIT 1" % table).fetchone())
        except sqlite3.OperationalError as e:
            if not e.args[0].startswith("no such table:"):
                raise

116
    def _alterTable(self, schema_dict, table, select="*"):
117 118 119
        # BBB: As explained in _setup, no transactional DDL
        #      so let's do the same dance as for MySQL.
        q = self.query
120 121 122
        new = 'new_' + table
        if self.nonempty(table) is None:
            if self.nonempty(new) is None:
123 124
                return
        else:
125 126 127 128 129 130 131 132 133 134 135 136
            q("DROP TABLE IF EXISTS " + new)
            q(schema_dict.pop(table) % new)
            q("INSERT INTO %s SELECT %s FROM %s" % (new, select, table))
            q("DROP TABLE " + table)
        q("ALTER TABLE %s RENAME TO %s" % (new, table))

    def _migrate1(self, *_):
        self._checkNoUnfinishedTransactions()
        self.query("DROP TABLE IF EXISTS ttrans")

    def _migrate2(self, schema_dict, index_dict):
        self._alterTable(schema_dict, 'obj')
137

138 139 140 141 142 143
    def _migrate3(self, schema_dict, index_dict):
        self._alterTable(schema_dict, 'pt', "rid, nid, CASE state"
            " WHEN 0 THEN -1"  # UP_TO_DATE
            " WHEN 2 THEN -2"  # FEEDING
            " ELSE 1-state END")

144
    def _setup(self, dedup=False):
145 146 147 148
        # BBB: SQLite has transactional DDL but before Python 3.6,
        #      the binding automatically commits between such statements.
        #      This anti-feature causes this method to be relatively slow.
        #      Unit tests enables the UNSAFE boolean flag.
149 150
        self._config.clear()
        q = self.query
151 152
        schema_dict = OrderedDict()
        index_dict = {}
153

154 155 156 157 158 159
        # The table "config" stores configuration
        # parameters which affect the persistent data.
        schema_dict['config'] = """CREATE TABLE %s (
                 name TEXT NOT NULL PRIMARY KEY,
                 value TEXT)
            """
160 161

        # The table "pt" stores a partition table.
162
        schema_dict['pt'] = """CREATE TABLE %s (
163
                 partition INTEGER NOT NULL,
164
                 nid INTEGER NOT NULL,
165 166
                 tid INTEGER NOT NULL,
                 PRIMARY KEY (partition, nid))
167
            """
168 169

        # The table "trans" stores information on committed transactions.
170
        schema_dict['trans'] = """CREATE TABLE %s (
171 172 173 174 175 176 177
                 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,
178
                 ttid INTEGER NOT NULL,
179
                 PRIMARY KEY (partition, tid))
180
            """
181 182

        # The table "obj" stores committed object metadata.
183
        schema_dict['obj'] = """CREATE TABLE %s (
184 185
                 partition INTEGER NOT NULL,
                 oid INTEGER NOT NULL,
186
                 tid INTEGER NOT NULL,
187
                 data_id INTEGER,
188
                 value_tid INTEGER,
189
                 PRIMARY KEY (partition, oid, tid))
190 191
            """
        index_dict['obj'] = (
192
            "CREATE INDEX %s ON %s(partition, tid, oid)",
193
            "CREATE INDEX %s ON %s(data_id)")
194 195

        # The table "data" stores object data.
196
        schema_dict['data'] = """CREATE TABLE %s (
197
                 id INTEGER PRIMARY KEY,
198 199
                 hash BLOB NOT NULL,
                 compression INTEGER NOT NULL,
200
                 value BLOB NOT NULL)
201
            """
202
        if dedup:
203 204
            index_dict['data'] = (
                "CREATE UNIQUE INDEX %s ON %s(hash, compression)",)
205 206

        # The table "ttrans" stores information on uncommitted transactions.
207
        schema_dict['ttrans'] = """CREATE TABLE %s (
208
                 partition INTEGER NOT NULL,
209
                 tid INTEGER,
210 211 212 213
                 packed BOOLEAN NOT NULL,
                 oids BLOB NOT NULL,
                 user BLOB NOT NULL,
                 description BLOB NOT NULL,
214 215
                 ext BLOB NOT NULL,
                 ttid INTEGER NOT NULL)
216
            """
217 218

        # The table "tobj" stores uncommitted object metadata.
219
        schema_dict['tobj'] = """CREATE TABLE %s (
220 221
                 partition INTEGER NOT NULL,
                 oid INTEGER NOT NULL,
222
                 tid INTEGER NOT NULL,
223
                 data_id INTEGER,
224 225
                 value_tid INTEGER,
                 PRIMARY KEY (tid, oid))
226 227 228 229 230 231 232 233 234 235
            """

        if self.nonempty('config') is None:
            q(schema_dict.pop('config') % 'config')
            self._setConfiguration('version', self.VERSION)
        else:
            self.migrate(schema_dict, index_dict)

        for table, schema in schema_dict.iteritems():
            q(schema % ('IF NOT EXISTS ' + table))
236 237
        for table, index in index_dict.iteritems():
            for i, index in enumerate(index, 1):
238
                q(index % ('IF NOT EXISTS _%s_i%s' % (table, i), table))
239

240
        self._uncommitted_data.update(q("SELECT data_id, count(*)"
241 242 243 244 245 246 247
            " FROM tobj WHERE data_id IS NOT NULL GROUP BY data_id"))

    def getConfiguration(self, key):
        try:
            return self._config[key]
        except KeyError:
            try:
248 249
                r = self.query("SELECT value FROM config WHERE name=?",
                               (key,)).fetchone()[0]
250 251 252 253 254 255 256 257 258 259 260
            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:
261
            q("REPLACE INTO config VALUES (?,?)", (key, str(value)))
262

263
    def _getPartitionTable(self):
264
        return self.query("SELECT * FROM pt")
265

266 267 268 269 270 271 272 273 274 275
    def _getLastTID(self, partition, max_tid=None):
        x = self.query
        if max_tid is None:
            x = x("SELECT MAX(tid) FROM trans WHERE partition=?", (partition,))
        else:
            x = x("SELECT MAX(tid) FROM trans WHERE partition=? AND tid<=?",
                  (partition, max_tid))
        return x.next()[0]

    def _getLastIDs(self, *args):
276
        q = self.query
277 278 279
        (oid,), = q("SELECT MAX(oid) FROM obj WHERE `partition`=?", args)
        (tid,), = q("SELECT MAX(tid) FROM obj WHERE `partition`=?", args)
        return tid, oid
280

281 282 283 284
    def _getDataLastId(self, partition):
        return self.query("SELECT MAX(id) FROM data WHERE %s <= id AND id < %s"
            % (partition << 48, (partition + 1) << 48)).fetchone()[0]

285
    def _getUnfinishedTIDDict(self):
286
        q = self.query
287 288 289 290 291 292 293 294 295
        return q("SELECT ttid, tid FROM ttrans"), (ttid
            for ttid, in q("SELECT DISTINCT tid FROM tobj"))

    def getFinalTID(self, ttid):
        ttid = util.u64(ttid)
        # As of SQLite 3.8.7.1, 'tid>=ttid' would ignore the index on tid,
        # even though ttid is a constant.
        for tid, in self.query("SELECT tid FROM trans"
                " WHERE partition=? AND tid>=? AND ttid=? LIMIT 1",
296
                (self._getReadablePartition(ttid), ttid, ttid)):
297
            return util.p64(tid)
298

299 300 301 302 303
    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",
304
                       (self._getReadablePartition(oid), oid)).fetchone()
305 306
        return r and util.p64(r[0])

307 308 309 310 311 312
    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]

313 314
    def _getObject(self, oid, tid=None, before_tid=None):
        q = self.query
315
        partition = self._getReadablePartition(oid)
316
        sql = ('SELECT tid, compression, data.hash, value, value_tid'
317 318 319
               ' FROM obj LEFT JOIN data ON obj.data_id = data.id'
               ' WHERE partition=? AND oid=?')
        if tid is not None:
320
            r = q(sql + ' AND tid=?', (partition, oid, tid))
321
        elif before_tid is not None:
322
            r = q(sql + ' AND tid<? ORDER BY tid DESC LIMIT 1',
323 324
                  (partition, oid, before_tid))
        else:
325
            r = q(sql + ' ORDER BY tid DESC LIMIT 1', (partition, oid))
326 327 328 329 330 331 332
        try:
            serial, compression, checksum, data, value_serial = r.fetchone()
        except TypeError:
            return None
        if checksum:
            checksum = str(checksum)
            data = str(data)
333 334
        return (serial, self._getNextTID(partition, oid, serial),
                compression, checksum, data, value_serial)
335

336
    def _changePartitionTable(self, cell_list, reset=False):
337 338 339
        q = self.query
        if reset:
            q("DELETE FROM pt")
340
        for offset, nid, state in cell_list:
341 342 343 344 345 346
            # 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".
347 348
            q("DELETE FROM pt WHERE partition=? AND nid=?", (offset, nid))
            if state is not None:
349
                q("INSERT OR FAIL INTO pt VALUES (?,?,?)",
350
                  (offset, nid, int(state)))
351 352 353

    def dropPartitions(self, offset_list):
        where = " WHERE partition=?"
354 355 356
        q = self.query
        for partition in offset_list:
            args = partition,
357 358 359
            data_id_list = [x for x, in q(
                "SELECT DISTINCT data_id FROM obj%s AND data_id IS NOT NULL"
                % where, args)]
360 361 362
            q("DELETE FROM obj" + where, args)
            q("DELETE FROM trans" + where, args)
            self._pruneData(data_id_list)
363

364
    def _getUnfinishedDataIdList(self):
365 366
        return [x for x, in self.query(
            "SELECT data_id FROM tobj WHERE data_id IS NOT NULL")]
367 368 369 370

    def dropPartitionsTemporary(self, offset_list=None):
        where = "" if offset_list is None else \
            " WHERE `partition` IN (%s)" % ','.join(map(str, offset_list))
371
        q = self.query
372 373
        q("DELETE FROM tobj" + where)
        q("DELETE FROM ttrans" + where)
374 375 376 377 378 379

    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
380 381 382 383 384 385 386 387 388 389
        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:
390
                    self.holdData(data_id)
391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407
            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,
408 409
                (partition, None if temporary else tid,
                 packed, buffer(''.join(oid_list)),
410
                 buffer(user), buffer(desc), buffer(ext), u64(ttid)))
411

412 413 414 415 416
    def getOrphanList(self):
        return [x for x, in self.query(
            "SELECT id FROM data LEFT JOIN obj ON (id=data_id)"
            " WHERE data_id IS NULL")]

417 418 419 420 421 422 423 424 425
    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)))
426 427
            return len(data_id_list)
        return 0
428

429
    def storeData(self, checksum, oid, data, compression,
430
            _dup=unique_constraint_message("data", "hash", "compression")):
431
        H = buffer(checksum)
432 433
        p = self._getPartition(util.u64(oid))
        r = self._data_last_ids[p]
434
        try:
435 436
            self.query("INSERT INTO data VALUES (?,?,?,?)",
                (r, H, compression,  buffer(data)))
437
        except sqlite3.IntegrityError, e:
438 439 440 441 442
            if e.args[0] == _dup:
                (r, d), = self.query("SELECT id, value FROM data"
                                     " WHERE hash=? AND compression=?",
                                     (H, compression))
                if str(d) == data:
443 444
                    return r
            raise
445 446
        self._data_last_ids[p] = r + 1
        return r
447

448 449
    def loadData(self, data_id):
        return self.query("SELECT compression, hash, value"
450
                          " FROM data WHERE id=?", (data_id,)).fetchone()
451

452
    def _getDataTID(self, oid, tid=None, before_tid=None):
453
        partition = self._getReadablePartition(oid)
454
        sql = 'SELECT tid, value_tid FROM obj' \
455 456
              ' WHERE partition=? AND oid=?'
        if tid is not None:
457
            r = self.query(sql + ' AND tid=?', (partition, oid, tid))
458
        elif before_tid is not None:
459
            r = self.query(sql + ' AND tid<? ORDER BY tid DESC LIMIT 1',
460 461
                           (partition, oid, before_tid))
        else:
462
            r = self.query(sql + ' ORDER BY tid DESC LIMIT 1',
463 464
                           (partition, oid))
        r = r.fetchone()
465
        return r or (None, None)
466

467 468 469 470 471 472 473
    def lockTransaction(self, tid, ttid):
        u64 = util.u64
        self.query("UPDATE ttrans SET tid=? WHERE ttid=?",
                   (u64(tid), u64(ttid)))
        self.commit()

    def unlockTransaction(self, tid, ttid):
474
        q = self.query
475 476 477
        u64 = util.u64
        tid = u64(tid)
        ttid = u64(ttid)
478
        sql = " FROM tobj WHERE tid=?"
479 480
        data_id_list = [x for x, in q("SELECT data_id%s AND data_id IS NOT NULL"
                                      % sql, (ttid,))]
481 482 483 484 485
        q("INSERT INTO obj SELECT partition, oid, ?, data_id, value_tid" + sql,
          (tid, ttid))
        q("DELETE" + sql, (ttid,))
        q("INSERT INTO trans SELECT * FROM ttrans WHERE tid=?", (tid,))
        q("DELETE FROM ttrans WHERE tid=?", (tid,))
486
        self.releaseData(data_id_list)
487

488 489
    def abortTransaction(self, ttid):
        args = util.u64(ttid),
490
        q = self.query
491
        q("DELETE FROM tobj WHERE tid=?", args)
492 493 494 495 496 497
        q("DELETE FROM ttrans WHERE ttid=?", args)

    def deleteTransaction(self, tid):
        tid = util.u64(tid)
        self.query("DELETE FROM trans WHERE partition=? AND tid=?",
            (self._getPartition(tid), tid))
498 499 500 501 502 503

    def deleteObject(self, oid, serial=None):
        oid = util.u64(oid)
        sql = " FROM obj WHERE partition=? AND oid=?"
        args = [self._getPartition(oid), oid]
        if serial:
504
            sql += " AND tid=?"
505
            args.append(util.u64(serial))
506
        q = self.query
507 508
        data_id_list = [x for x, in q(
            "SELECT DISTINCT data_id%s AND data_id IS NOT NULL" % sql, args)]
509 510
        q("DELETE" + sql, args)
        self._pruneData(data_id_list)
511 512 513 514

    def _deleteRange(self, partition, min_tid=None, max_tid=None):
        sql = " WHERE partition=?"
        args = [partition]
515
        if min_tid is not None:
516
            sql += " AND ? < tid"
517 518
            args.append(min_tid)
        if max_tid is not None:
519
            sql += " AND tid <= ?"
520
            args.append(max_tid)
521 522
        q = self.query
        q("DELETE FROM trans" + sql, args)
523
        sql = " FROM obj" + sql
524 525
        data_id_list = [x for x, in q(
            "SELECT DISTINCT data_id%s AND data_id IS NOT NULL" % sql, args)]
526 527 528 529 530
        q("DELETE" + sql, args)
        self._pruneData(data_id_list)

    def getTransaction(self, tid, all=False):
        tid = util.u64(tid)
531 532 533
        q = self.query
        r = q("SELECT oids, user, description, ext, packed, ttid"
              " FROM trans WHERE partition=? AND tid=?",
534
              (self._getReadablePartition(tid), tid)).fetchone()
535
        if not r and all:
536
            r = q("SELECT oids, user, description, ext, packed, ttid"
537
                  " FROM ttrans WHERE tid=?", (tid,)).fetchone()
538
        if r:
539
            oids, user, description, ext, packed, ttid = r
540
            return splitOIDField(tid, oids), str(user), \
541
                str(description), str(ext), packed, util.p64(ttid)
542

543
    def getObjectHistory(self, oid, offset, length):
544 545 546 547 548
        # 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)
549 550
        return [(p64(tid), length or 0) for tid, length in self.query("""\
            SELECT tid, LENGTH(value)
551 552 553
                FROM obj LEFT JOIN data ON obj.data_id = data.id
                WHERE partition=? AND oid=? AND tid>=?
                ORDER BY tid DESC LIMIT ?,?""",
554 555
            (self._getReadablePartition(oid), oid,
             self._getPackTID(), offset, length))
556
            ] or None
557

558 559 560 561 562 563 564 565 566 567 568
    def _fetchObject(self, oid, tid):
        for serial, compression, checksum, data, value_serial in self.query(
                'SELECT tid, compression, data.hash, value, value_tid'
                ' FROM obj LEFT JOIN data ON obj.data_id = data.id'
                ' WHERE partition=? AND oid=? AND tid=?',
                (self._getReadablePartition(oid), oid, tid)):
            if checksum:
                checksum = str(checksum)
                data = str(data)
            return serial, compression, checksum, data, value_serial

569 570 571 572 573 574
    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("""\
575 576 577 578
            SELECT tid, oid FROM obj
            WHERE partition=? AND tid<=?
            AND (tid=? AND ?<=oid OR ?<tid)
            ORDER BY tid ASC, oid ASC LIMIT ?""",
579 580
            (partition, u64(max_tid), min_tid, u64(min_oid), min_tid, length))]

581 582 583 584 585
    def _getTIDList(self, offset, length, partition_list):
        return (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)))
586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602

    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.
603
        partition = self._getReadablePartition(oid)
604 605 606
        value_serial = None
        q = self.query
        for T in '', 't':
607 608 609 610 611
            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,
612 613 614 615 616 617 618 619 620 621 622 623
                    (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
624
        getPartition = self._getReadablePartition
625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651
        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()
652

653
    def checkTIDRange(self, partition, length, min_tid, max_tid):
654
        # XXX: SQLite's GROUP_CONCAT is slow (looks like quadratic)
655 656 657 658 659 660 661 662 663 664 665
        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

666
    def checkSerialRange(self, partition, length, min_tid, max_tid, min_oid):
667
        u64 = util.u64
668
        # We don't ask SQLite to compute everything (like in checkTIDRange)
669 670 671
        # 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.
672
        min_tid = u64(min_tid)
673
        r = self.query("""\
674
            SELECT tid, oid
675
            FROM obj
676 677 678
            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),
679 680 681 682 683 684 685 686
             -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]))
687
        return 0, ZERO_HASH, ZERO_TID, ZERO_HASH, ZERO_OID
688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708

    def dump(self):
        main = []
        data = []
        for line in self.conn.iterdump():
            if line.startswith('INSERT '):
                assert line.endswith(';'), line
                data.append(line)
                continue
            if line.startswith('CREATE TABLE '):
                # ALTER TABLE adds quotes.
                create, table, name, tail = line.split(' ', 3)
                line = ' '.join((create, table, name.strip('"'), tail))
            main.append(line)
        assert line == 'COMMIT;', line
        data.sort()
        main[-1:-1] = data
        return '\n'.join(main) + '\n'

    def restore(self, sql):
        self.conn.executescript(sql)