mysqldb.py 32.9 KB
Newer Older
Aurel's avatar
Aurel committed
1
#
2
# Copyright (C) 2006-2017  Nexedi SA
3
#
Aurel's avatar
Aurel committed
4 5 6 7
# 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.
8
#
Aurel's avatar
Aurel committed
9 10 11 12 13 14
# 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/>.
Aurel's avatar
Aurel committed
16

17
from binascii import a2b_hex
Yoshinori Okuji's avatar
Yoshinori Okuji committed
18
import MySQLdb
19 20
from MySQLdb import DataError, IntegrityError, \
    OperationalError, ProgrammingError
Yoshinori Okuji's avatar
Yoshinori Okuji committed
21
from MySQLdb.constants.CR import SERVER_GONE_ERROR, SERVER_LOST
22
from MySQLdb.constants.ER import DATA_TOO_LONG, DUP_ENTRY, NO_SUCH_TABLE
Julien Muchembled's avatar
Julien Muchembled committed
23 24 25
# BBB: the following 2 constants were added to mysqlclient 1.3.8
DROP_LAST_PARTITION = 1508
SAME_NAME_PARTITION = 1517
26
from array import array
27
from hashlib import sha1
28
import os
29
import re
30
import string
31
import struct
32
import sys
33
import time
Yoshinori Okuji's avatar
Yoshinori Okuji committed
34

35
from . import LOG_QUERIES
36
from .manager import DatabaseManager, splitOIDField
37
from neo.lib import logging, util
38
from neo.lib.exception import DatabaseFailure
39
from neo.lib.interfaces import implements
40
from neo.lib.protocol import CellStates, ZERO_OID, ZERO_TID, ZERO_HASH
Yoshinori Okuji's avatar
Yoshinori Okuji committed
41

42

43 44 45 46 47
def getPrintableQuery(query, max=70):
    return ''.join(c if c in string.printable and c not in '\t\x0b\x0c\r'
        else '\\x%02x' % ord(c) for c in query)


48
@implements
49 50
class MySQLDatabaseManager(DatabaseManager):
    """This class manages a database on MySQL."""
Yoshinori Okuji's avatar
Yoshinori Okuji committed
51

52
    VERSION = 1
53
    ENGINES = "InnoDB", "RocksDB", "TokuDB"
54
    _engine = ENGINES[0] # default engine
55

56 57 58
    # Disabled even on MySQL 5.1-5.5 and MariaDB 5.2-5.3 because
    # 'select count(*) from obj' sometimes returns incorrect values
    # (tested with testOudatedCellsOnDownStorage).
59 60
    _use_partition = False

61 62
    _max_allowed_packet = 32769 * 1024

63 64
    def _parse(self, database):
        """ Get the database credentials (username, password, database) """
65
        # expected pattern : [user[:password]@]database[(~|.|/)unix_socket]
66
        self.user, self.passwd, self.db, self.socket = re.match(
67
            '(?:([^:]+)(?::(.*))?@)?([^~./]+)(.+)?$', database).groups()
Yoshinori Okuji's avatar
Yoshinori Okuji committed
68

69
    def _close(self):
70 71
        self.conn.close()

72
    def _connect(self):
Yoshinori Okuji's avatar
Yoshinori Okuji committed
73 74 75
        kwd = {'db' : self.db, 'user' : self.user}
        if self.passwd is not None:
            kwd['passwd'] = self.passwd
76
        if self.socket:
77
            kwd['unix_socket'] = os.path.expanduser(self.socket)
78
        logging.info('connecting to MySQL on the database %s with user %s',
Yoshinori Okuji's avatar
Yoshinori Okuji committed
79
                     self.db, self.user)
80 81 82 83
        if self._wait < 0:
            timeout_at = None
        else:
            timeout_at = time.time() + self._wait
84
        last = None
85 86 87
        while True:
            try:
                self.conn = MySQLdb.connect(**kwd)
88
                break
89 90
            except Exception as e:
                if None is not timeout_at <= time.time():
91
                    raise
92 93 94 95 96 97 98
                e = str(e)
                if last == e:
                    log = logging.debug
                else:
                    last = e
                    log = logging.exception
                log('Connection to MySQL failed, retrying.')
99
                time.sleep(1)
100
        self._active = 0
101
        self._config = {}
102 103 104 105
        conn = self.conn
        conn.autocommit(False)
        conn.query("SET SESSION group_concat_max_len = %u" % (2**32-1))
        conn.set_sql_mode("TRADITIONAL,NO_ENGINE_SUBSTITUTION")
106 107 108 109 110 111 112 113 114 115 116
        def query(sql):
            conn.query(sql)
            r = conn.store_result()
            return r.fetch_row(r.num_rows())
        if self.LOCK:
            (locked,), = query("SELECT GET_LOCK('%s.%s', 0)"
                % (self.db, self.LOCK))
            if not locked:
                sys.exit(self.LOCKED)
        (name, value), = query(
            "SHOW VARIABLES WHERE variable_name='max_allowed_packet'")
117 118 119 120 121
        if int(value) < self._max_allowed_packet:
            raise DatabaseFailure("Global variable %r is too small."
                " Minimal value must be %uk."
                % (name, self._max_allowed_packet // 1024))
        self._max_allowed_packet = int(value)
122

123
    def _commit(self):
124
        self.conn.commit()
125
        self._active = 0
Yoshinori Okuji's avatar
Yoshinori Okuji committed
126 127 128

    def query(self, query):
        """Query data from a database."""
129 130 131
        if LOG_QUERIES:
            logging.debug('querying %s...',
                getPrintableQuery(query.split('\n', 1)[0][:70]))
132 133 134 135
        # Try 3 times at most. When it fails too often for the same
        # query then the disconnection is likely caused by this query.
        # We don't want to enter into an infinite loop.
        retry = 2
136 137 138 139 140 141 142 143 144 145 146
        while 1:
            conn = self.conn
            try:
                conn.query(query)
                if query.startswith("SELECT "):
                    r = conn.store_result()
                    return tuple([
                        tuple([d.tostring() if isinstance(d, array) else d
                              for d in row])
                        for row in r.fetch_row(r.num_rows())])
                break
Julien Muchembled's avatar
Julien Muchembled committed
147 148
            except OperationalError as m:
                code, m = m.args
149 150
                if self._active or SERVER_GONE_ERROR != code != SERVER_LOST \
                   or not retry:
151
                    raise DatabaseFailure('MySQL error %d: %s\nQuery: %s'
Julien Muchembled's avatar
Julien Muchembled committed
152
                        % (code, m, getPrintableQuery(query[:1000])))
153
                logging.info('the MySQL server is gone; reconnecting')
154
                self._connect()
155
                retry -= 1
156 157 158 159
        r = query.split(None, 1)[0]
        if r in ("INSERT", "REPLACE", "DELETE", "UPDATE"):
            self._active = 1
        else:
160
            assert r in ("ALTER", "CREATE", "DROP"), query
161

162 163
    @property
    def escape(self):
164
        """Escape special characters in a string."""
165
        return self.conn.escape_string
166

167
    def erase(self):
168 169
        self.query("DROP TABLE IF EXISTS"
            " config, pt, trans, obj, data, bigdata, ttrans, tobj")
170

171 172 173
    def nonempty(self, table):
        try:
            return bool(self.query("SELECT 1 FROM %s LIMIT 1" % table))
Julien Muchembled's avatar
Julien Muchembled committed
174 175
        except ProgrammingError as e:
            if e.args[0] != NO_SUCH_TABLE:
176 177
                raise

178
    def _setup(self):
179
        self._config.clear()
180
        q = self.query
181
        p = engine = self._engine
182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197

        if self.nonempty("config") is None:
            # The table "config" stores configuration
            # parameters which affect the persistent data.
            q("""CREATE TABLE config (
                     name VARBINARY(255) NOT NULL PRIMARY KEY,
                     value VARBINARY(255) NULL
                 ) ENGINE=""" + engine)
        else:
            # Automatic migration.
            version = self._getVersion()
            if version < 1:
                self._checkNoUnfinishedTransactions()
                q("DROP TABLE IF EXISTS ttrans")

        self._setConfiguration("version", self.VERSION)
198 199 200 201

        # The table "pt" stores a partition table.
        q("""CREATE TABLE IF NOT EXISTS pt (
                 rid INT UNSIGNED NOT NULL,
202
                 nid INT NOT NULL,
203
                 state TINYINT UNSIGNED NOT NULL,
204
                 PRIMARY KEY (rid, nid)
205
             ) ENGINE=""" + engine)
206

207 208 209
        if self._use_partition:
            p += """ PARTITION BY LIST (`partition`) (
                PARTITION dummy VALUES IN (NULL))"""
210

211 212
        # The table "trans" stores information on committed transactions.
        q("""CREATE TABLE IF NOT EXISTS trans (
213
                 `partition` SMALLINT UNSIGNED NOT NULL,
214
                 tid BIGINT UNSIGNED NOT NULL,
215
                 packed BOOLEAN NOT NULL,
216 217
                 oids MEDIUMBLOB NOT NULL,
                 user BLOB NOT NULL,
Yoshinori Okuji's avatar
Yoshinori Okuji committed
218
                 description BLOB NOT NULL,
219
                 ext BLOB NOT NULL,
220
                 ttid BIGINT UNSIGNED NOT NULL,
221
                 PRIMARY KEY (`partition`, tid)
222
             ) ENGINE=""" + p)
223

224
        # The table "obj" stores committed object metadata.
225
        q("""CREATE TABLE IF NOT EXISTS obj (
226
                 `partition` SMALLINT UNSIGNED NOT NULL,
227
                 oid BIGINT UNSIGNED NOT NULL,
228
                 tid BIGINT UNSIGNED NOT NULL,
229
                 data_id BIGINT UNSIGNED NULL,
230
                 value_tid BIGINT UNSIGNED NULL,
231 232
                 PRIMARY KEY (`partition`, tid, oid),
                 KEY (`partition`, oid, tid),
233
                 KEY (data_id)
234 235 236 237
             ) ENGINE=""" + p)

        if engine == "TokuDB":
            engine += " compression='tokudb_uncompressed'"
238

239
        # The table "data" stores object data.
240
        # We'd like to have partial index on 'hash' column (e.g. hash(4))
241
        # but 'UNIQUE' constraint would not work as expected.
242
        q("""CREATE TABLE IF NOT EXISTS data (
243
                 id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
244
                 hash BINARY(20) NOT NULL,
245
                 compression TINYINT UNSIGNED NULL,
246
                 value MEDIUMBLOB NOT NULL,
247
                 UNIQUE (hash, compression)
248
             ) ENGINE=""" + engine)
249

250 251 252 253 254
        q("""CREATE TABLE IF NOT EXISTS bigdata (
                 id INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
                 value MEDIUMBLOB NOT NULL
             ) ENGINE=""" + engine)

255 256
        # The table "ttrans" stores information on uncommitted transactions.
        q("""CREATE TABLE IF NOT EXISTS ttrans (
257
                 `partition` SMALLINT UNSIGNED NOT NULL,
258
                 tid BIGINT UNSIGNED,
259
                 packed BOOLEAN NOT NULL,
260 261
                 oids MEDIUMBLOB NOT NULL,
                 user BLOB NOT NULL,
Yoshinori Okuji's avatar
Yoshinori Okuji committed
262
                 description BLOB NOT NULL,
263 264
                 ext BLOB NOT NULL,
                 ttid BIGINT UNSIGNED NOT NULL
265
             ) ENGINE=""" + engine)
266

267
        # The table "tobj" stores uncommitted object metadata.
268
        q("""CREATE TABLE IF NOT EXISTS tobj (
269
                 `partition` SMALLINT UNSIGNED NOT NULL,
270
                 oid BIGINT UNSIGNED NOT NULL,
271
                 tid BIGINT UNSIGNED NOT NULL,
272
                 data_id BIGINT UNSIGNED NULL,
273 274
                 value_tid BIGINT UNSIGNED NULL,
                 PRIMARY KEY (tid, oid)
275
             ) ENGINE=""" + engine)
276

277 278
        self._uncommitted_data.update(q("SELECT data_id, count(*)"
            " FROM tobj WHERE data_id IS NOT NULL GROUP BY data_id"))
279

280 281
    def getConfiguration(self, key):
        try:
282 283 284 285 286 287 288 289 290 291
            return self._config[key]
        except KeyError:
            sql_key = self.escape(str(key))
            try:
                r = self.query("SELECT value FROM config WHERE name = '%s'"
                               % sql_key)[0][0]
            except IndexError:
                r = None
            self._config[key] = r
            return r
292

293 294 295
    def _setConfiguration(self, key, value):
        q = self.query
        e = self.escape
296
        self._config[key] = value
297
        k = e(str(key))
298
        if value is None:
299 300 301 302 303 304
            q("DELETE FROM config WHERE name = '%s'" % k)
            return
        value = str(value)
        sql = "REPLACE INTO config VALUES ('%s', '%s')" % (k, e(value))
        try:
            q(sql)
Julien Muchembled's avatar
Julien Muchembled committed
305 306
        except DataError as e:
            if e.args[0] != DATA_TOO_LONG or len(value) < 256 or key != "zodb":
307 308 309
                raise
            q("ALTER TABLE config MODIFY value VARBINARY(%s) NULL" % len(value))
            q(sql)
310

311 312 313
    def getPartitionTable(self, *nid):
        if nid:
            return self.query("SELECT rid, state FROM pt WHERE nid=%u" % nid)
314
        return self.query("SELECT * FROM pt")
315

316
    def getLastTID(self, max_tid):
317 318
        return self.query("SELECT MAX(t) FROM (SELECT MAX(tid) as t FROM trans"
            " WHERE tid<=%s GROUP BY `partition`) as t" % max_tid)[0][0]
319

320
    def _getLastIDs(self):
321
        p64 = util.p64
322
        q = self.query
323
        trans = {partition: p64(tid)
324 325
            for partition, tid in q("SELECT `partition`, MAX(tid)"
                                    " FROM trans GROUP BY `partition`")}
326
        obj = {partition: p64(tid)
327 328
            for partition, tid in q("SELECT `partition`, MAX(tid)"
                                    " FROM obj GROUP BY `partition`")}
329
        oid = q("SELECT MAX(oid) FROM (SELECT MAX(oid) AS oid FROM obj"
330
                                      " GROUP BY `partition`) as t")[0][0]
331
        return trans, obj, None if oid is None else p64(oid)
332

333
    def _getUnfinishedTIDDict(self):
334
        q = self.query
335 336 337 338 339 340 341 342
        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)
        # MariaDB is smart enough to realize that 'ttid' is constant.
        r = self.query("SELECT tid FROM trans"
            " WHERE `partition`=%s AND tid>=ttid AND ttid=%s LIMIT 1"
343
            % (self._getReadablePartition(ttid), ttid))
344 345
        if r:
            return util.p64(r[0][0])
346

347 348 349
    def getLastObjectTID(self, oid):
        oid = util.u64(oid)
        r = self.query("SELECT tid FROM obj"
350
                       " WHERE `partition`=%d AND oid=%d"
351
                       " ORDER BY tid DESC LIMIT 1"
352
                       % (self._getReadablePartition(oid), oid))
353 354
        return util.p64(r[0][0]) if r else None

355 356
    def _getNextTID(self, *args): # partition, oid, tid
        r = self.query("SELECT tid FROM obj"
357
                       " FORCE INDEX(`partition`)"
358
                       " WHERE `partition`=%d AND oid=%d AND tid>%d"
359 360 361
                       " ORDER BY tid LIMIT 1" % args)
        return r[0][0] if r else None

362
    def _getObject(self, oid, tid=None, before_tid=None):
363
        q = self.query
364
        partition = self._getReadablePartition(oid)
365
        sql = ('SELECT tid, compression, data.hash, value, value_tid'
366
               ' FROM obj LEFT JOIN data ON (obj.data_id = data.id)'
367
               ' WHERE `partition` = %d AND oid = %d') % (partition, oid)
368
        if before_tid is not None:
369
            sql += ' AND tid < %d ORDER BY tid DESC LIMIT 1' % before_tid
370 371
        elif tid is not None:
            sql += ' AND tid = %d' % tid
372
        else:
373
            # XXX I want to express "HAVING tid = MAX(tid)", but
374
            # MySQL does not use an index for a HAVING clause!
375
            sql += ' ORDER BY tid DESC LIMIT 1'
376 377 378 379 380
        r = q(sql)
        try:
            serial, compression, checksum, data, value_serial = r[0]
        except IndexError:
            return None
381 382 383
        if compression and compression & 0x80:
            compression &= 0x7f
            data = ''.join(self._bigData(data))
384 385
        return (serial, self._getNextTID(partition, oid, serial),
                compression, checksum, data, value_serial)
386

387
    def _changePartitionTable(self, cell_list, reset=False):
388
        offset_list = []
389 390
        q = self.query
        if reset:
391
            q("DELETE FROM pt")
392
        for offset, nid, state in cell_list:
393 394 395
            # TODO: this logic should move out of database manager
            # add 'dropCells(cell_list)' to API and use one query
            if state == CellStates.DISCARDED:
396 397
                q("DELETE FROM pt WHERE rid = %d AND nid = %d"
                  % (offset, nid))
398 399 400 401
            else:
                offset_list.append(offset)
                q("INSERT INTO pt VALUES (%d, %d, %d)"
                  " ON DUPLICATE KEY UPDATE state = %d"
402
                  % (offset, nid, state, state))
403 404 405 406
        if self._use_partition:
            for offset in offset_list:
                add = """ALTER TABLE %%s ADD PARTITION (
                    PARTITION p%u VALUES IN (%u))""" % (offset, offset)
407
                for table in 'trans', 'obj':
408 409
                    try:
                        self.conn.query(add % table)
Julien Muchembled's avatar
Julien Muchembled committed
410 411
                    except OperationalError as e:
                        if e.args[0] != SAME_NAME_PARTITION:
412
                            raise
413

414
    def dropPartitions(self, offset_list):
415 416 417 418 419
        q = self.query
        # XXX: these queries are inefficient (execution time increase with
        # row count, although we use indexes) when there are rows to
        # delete. It should be done as an idle task, by chunks.
        for partition in offset_list:
420
            where = " WHERE `partition`=%d" % partition
421
            data_id_list = [x for x, in
422 423
                q("SELECT DISTINCT data_id FROM obj USE INDEX(PRIMARY)" + where)
                if x]
424 425 426 427
            if not self._use_partition:
                q("DELETE FROM obj" + where)
                q("DELETE FROM trans" + where)
            self._pruneData(data_id_list)
428 429 430 431 432 433
        if self._use_partition:
            drop = "ALTER TABLE %s DROP PARTITION" + \
                ','.join(' p%u' % i for i in offset_list)
            for table in 'trans', 'obj':
                try:
                    self.conn.query(drop % table)
Julien Muchembled's avatar
Julien Muchembled committed
434 435
                except OperationalError as e:
                    if e.args[0] != DROP_LAST_PARTITION:
436
                        raise
437

438 439 440 441 442 443
    def _getUnfinishedDataIdList(self):
        return [x for x, in self.query("SELECT data_id FROM tobj") if x]

    def dropPartitionsTemporary(self, offset_list=None):
        where = "" if offset_list is None else \
            " WHERE `partition` IN (%s)" % ','.join(map(str, offset_list))
444
        q = self.query
445 446
        q("DELETE FROM tobj" + where)
        q("DELETE FROM ttrans" + where)
447

448
    def storeTransaction(self, tid, object_list, transaction, temporary = True):
449
        e = self.escape
450 451
        u64 = util.u64
        tid = u64(tid)
452 453 454 455 456 457
        if temporary:
            obj_table = 'tobj'
            trans_table = 'ttrans'
        else:
            obj_table = 'obj'
            trans_table = 'trans'
458
        q = self.query
459 460 461
        sql = ["REPLACE INTO %s VALUES " % obj_table]
        values_max = self._max_allowed_packet - len(sql[0])
        values_size = 0
462 463 464 465 466 467
        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"
468
                    " WHERE `partition`=%d AND oid=%d AND tid=%d"
469 470
                    % (partition, oid, value_serial))
                if temporary:
471
                    self.holdData(data_id)
472 473
            else:
                value_serial = 'NULL'
474 475 476 477 478 479 480 481 482 483 484 485 486 487
            value = "(%s,%s,%s,%s,%s)," % (
                partition, oid, tid, data_id or 'NULL', value_serial)
            values_size += len(value)
            # actually: max_values < values_size + EXTRA - len(final comma)
            # (test_max_allowed_packet checks that EXTRA == 2)
            if values_max <= values_size:
                sql[-1] = sql[-1][:-1] # remove final comma
                q(''.join(sql))
                del sql[1:]
                values_size = len(value)
            sql.append(value)
        if values_size:
            sql[-1] = value[:-1] # remove final comma
            q(''.join(sql))
488 489 490 491
        if transaction:
            oid_list, user, desc, ext, packed, ttid = transaction
            partition = self._getPartition(tid)
            assert packed in (0, 1)
492 493 494
            q("REPLACE INTO %s VALUES (%s,%s,%s,'%s','%s','%s','%s',%s)" % (
                trans_table, partition, 'NULL' if temporary else tid, packed,
                e(''.join(oid_list)), e(user), e(desc), e(ext), u64(ttid)))
495

496 497 498
    _structLL = struct.Struct(">LL")
    _unpackLL = _structLL.unpack

499 500 501 502 503
    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")]

504 505 506
    def _pruneData(self, data_id_list):
        data_id_list = set(data_id_list).difference(self._uncommitted_data)
        if data_id_list:
507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523
            q = self.query
            id_list = []
            bigid_list = []
            for id, value in q("SELECT id, IF(compression < 128, NULL, value)"
                               " FROM data LEFT JOIN obj ON (id = data_id)"
                               " WHERE id IN (%s) AND data_id IS NULL"
                               % ",".join(map(str, data_id_list))):
                id_list.append(str(id))
                if value:
                    bigdata_id, length = self._unpackLL(value)
                    bigid_list += xrange(bigdata_id,
                                         bigdata_id + (length + 0x7fffff >> 23))
            if id_list:
                q("DELETE FROM data WHERE id IN (%s)" % ",".join(id_list))
                if bigid_list:
                    q("DELETE FROM bigdata WHERE id IN (%s)"
                      % ",".join(map(str, bigid_list)))
524 525
                return len(id_list)
        return 0
526 527 528 529 530 531 532

    def _bigData(self, value):
        bigdata_id, length = self._unpackLL(value)
        q = self.query
        return (q("SELECT value FROM bigdata WHERE id=%s" % i)[0][0]
            for i in xrange(bigdata_id,
                            bigdata_id + (length + 0x7fffff >> 23)))
533

534
    def storeData(self, checksum, data, compression, _pack=_structLL.pack):
535 536
        e = self.escape
        checksum = e(checksum)
537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560
        if 0x1000000 <= len(data): # 16M (MEDIUMBLOB limit)
            compression |= 0x80
            q = self.query
            for r, d in q("SELECT id, value FROM data"
                          " WHERE hash='%s' AND compression=%s"
                          % (checksum, compression)):
                i = 0
                for d in self._bigData(d):
                    j = i + len(d)
                    if data[i:j] != d:
                        raise IntegrityError(DUP_ENTRY)
                    i = j
                if j != len(data):
                    raise IntegrityError(DUP_ENTRY)
                return r
            i = 'NULL'
            length = len(data)
            for j in xrange(0, length, 0x800000): # 8M
                q("INSERT INTO bigdata VALUES (%s, '%s')"
                  % (i, e(data[j:j+0x800000])))
                if not j:
                    i = bigdata_id = self.conn.insert_id()
                i += 1
            data = _pack(bigdata_id, length)
561 562 563
        try:
            self.query("INSERT INTO data VALUES (NULL, '%s', %d, '%s')" %
                       (checksum, compression,  e(data)))
Julien Muchembled's avatar
Julien Muchembled committed
564 565
        except IntegrityError as e:
            if e.args[0] == DUP_ENTRY:
566 567 568 569
                (r, d), = self.query("SELECT id, value FROM data"
                                     " WHERE hash='%s' AND compression=%s"
                                     % (checksum, compression))
                if d == data:
570 571 572
                    return r
            raise
        return self.conn.insert_id()
573

574 575 576 577 578 579 580 581 582
    def loadData(self, data_id):
        compression, hash, value = self.query(
            "SELECT compression, hash, value FROM data where id=%s"
            % data_id)[0]
        if compression and compression & 0x80:
            compression &= 0x7f
            data = ''.join(self._bigData(data))
        return compression, hash, value

583 584
    del _structLL

585
    def _getDataTID(self, oid, tid=None, before_tid=None):
586
        sql = ('SELECT tid, value_tid FROM obj'
587
               ' WHERE `partition` = %d AND oid = %d'
588
              ) % (self._getReadablePartition(oid), oid)
589
        if tid is not None:
590
            sql += ' AND tid = %d' % tid
591
        elif before_tid is not None:
592
            sql += ' AND tid < %d ORDER BY tid DESC LIMIT 1' % before_tid
593
        else:
594
            # XXX I want to express "HAVING tid = MAX(tid)", but
595
            # MySQL does not use an index for a HAVING clause!
596
            sql += ' ORDER BY tid DESC LIMIT 1'
597
        r = self.query(sql)
598
        return r[0] if r else (None, None)
599

600 601 602 603 604 605 606
    def lockTransaction(self, tid, ttid):
        u64 = util.u64
        self.query("UPDATE ttrans SET tid=%d WHERE ttid=%d LIMIT 1"
                   % (u64(tid), u64(ttid)))
        self.commit()

    def unlockTransaction(self, tid, ttid):
607
        q = self.query
608 609 610
        u64 = util.u64
        tid = u64(tid)
        sql = " FROM tobj WHERE tid=%d" % u64(ttid)
611
        data_id_list = [x for x, in q("SELECT data_id" + sql) if x]
612 613 614
        q("INSERT INTO obj SELECT `partition`, oid, %d, data_id, value_tid %s"
          % (tid, sql))
        q("DELETE" + sql)
615 616
        q("INSERT INTO trans SELECT * FROM ttrans WHERE tid=%d" % tid)
        q("DELETE FROM ttrans WHERE tid=%d" % tid)
617
        self.releaseData(data_id_list)
618

619 620
    def abortTransaction(self, ttid):
        ttid = util.u64(ttid)
621
        q = self.query
622
        q("DELETE FROM tobj WHERE tid=%s" % ttid)
623 624 625 626 627 628
        q("DELETE FROM ttrans WHERE ttid=%s" % ttid)

    def deleteTransaction(self, tid):
        tid = util.u64(tid)
        self.query("DELETE FROM trans WHERE `partition`=%s AND tid=%s" %
            (self._getPartition(tid), tid))
629

630 631
    def deleteObject(self, oid, serial=None):
        u64 = util.u64
632
        oid = u64(oid)
633
        sql = " FROM obj WHERE `partition`=%d AND oid=%d" \
634 635
            % (self._getPartition(oid), oid)
        if serial:
636
            sql += ' AND tid=%d' % u64(serial)
637 638 639 640
        q = self.query
        data_id_list = [x for x, in q("SELECT DISTINCT data_id" + sql) if x]
        q("DELETE" + sql)
        self._pruneData(data_id_list)
641

642
    def _deleteRange(self, partition, min_tid=None, max_tid=None):
643
        sql = " WHERE `partition`=%d" % partition
644 645 646 647
        if min_tid:
            sql += " AND %d < tid" % util.u64(min_tid)
        if max_tid:
            sql += " AND tid <= %d" % util.u64(max_tid)
648
        q = self.query
649
        q("DELETE FROM trans" + sql)
650
        sql = " FROM obj" + sql
651 652 653
        data_id_list = [x for x, in q("SELECT DISTINCT data_id" + sql) if x]
        q("DELETE" + sql)
        self._pruneData(data_id_list)
654

655
    def getTransaction(self, tid, all = False):
656
        tid = util.u64(tid)
657 658
        q = self.query
        r = q("SELECT oids, user, description, ext, packed, ttid"
659
              " FROM trans WHERE `partition` = %d AND tid = %d"
660
              % (self._getReadablePartition(tid), tid))
661
        if not r and all:
662
            r = q("SELECT oids, user, description, ext, packed, ttid"
663
                  " FROM ttrans WHERE tid = %d" % tid)
664
        if r:
665
            oids, user, desc, ext, packed, ttid = r[0]
666
            oid_list = splitOIDField(tid, oids)
667
            return oid_list, user, desc, ext, bool(packed), util.p64(ttid)
668

669
    def getObjectHistory(self, oid, offset, length):
670
        # FIXME: This method doesn't take client's current transaction id as
671 672
        # parameter, which means it can return transactions in the future of
        # client's transaction.
673
        oid = util.u64(oid)
674
        p64 = util.p64
675 676 677 678 679
        r = self.query("SELECT tid, IF(compression < 128, LENGTH(value),"
            "  CAST(CONV(HEX(SUBSTR(value, 5, 4)), 16, 10) AS INT))"
            " FROM obj LEFT JOIN data ON (obj.data_id = data.id)"
            " WHERE `partition` = %d AND oid = %d AND tid >= %d"
            " ORDER BY tid DESC LIMIT %d, %d" %
680 681
            (self._getReadablePartition(oid), oid,
             self._getPackTID(), offset, length))
682
        if r:
683
            return [(p64(tid), length or 0) for tid, length in r]
684

685 686
    def getReplicationObjectList(self, min_tid, max_tid, length, partition,
            min_oid):
687
        u64 = util.u64
688
        p64 = util.p64
689
        min_tid = u64(min_tid)
690
        r = self.query('SELECT tid, oid FROM obj'
691
                       ' WHERE `partition` = %d AND tid <= %d'
692 693
                       ' AND (tid = %d AND %d <= oid OR %d < tid)'
                       ' ORDER BY tid ASC, oid ASC LIMIT %d' % (
694 695
            partition, u64(max_tid), min_tid, u64(min_oid), min_tid, length))
        return [(p64(serial), p64(oid)) for serial, oid in r]
696

697 698 699 700 701
    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)))
702

703
    def getReplicationTIDList(self, min_tid, max_tid, length, partition):
704 705 706 707
        u64 = util.u64
        p64 = util.p64
        min_tid = u64(min_tid)
        max_tid = u64(max_tid)
708
        r = self.query("""SELECT tid FROM trans
709
                    WHERE `partition` = %(partition)d
710
                    AND tid >= %(min_tid)d AND tid <= %(max_tid)d
711
                    ORDER BY tid ASC LIMIT %(length)d""" % {
712
            'partition': partition,
713 714
            'min_tid': min_tid,
            'max_tid': max_tid,
715 716
            'length': length,
        })
717
        return [p64(t[0]) for t in r]
718

719
    def _updatePackFuture(self, oid, orig_serial, max_serial):
720 721 722 723 724 725
        q = self.query
        # 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.
        value_serial = None
726
        kw = {
727
          'partition': self._getReadablePartition(oid),
728
          'oid': oid,
729 730 731
          'orig_tid': orig_serial,
          'max_tid': max_serial,
          'new_tid': 'NULL',
732 733
        }
        for kw['table'] in 'obj', 'tobj':
734
            for kw['tid'], in q('SELECT tid FROM %(table)s'
735
                  ' WHERE `partition`=%(partition)d AND oid=%(oid)d'
736 737 738
                  ' AND tid>=%(max_tid)d AND value_tid=%(orig_tid)d'
                  ' ORDER BY tid ASC' % kw):
                q('UPDATE %(table)s SET value_tid=%(new_tid)s'
739
                  ' WHERE `partition`=%(partition)d AND oid=%(oid)d'
740
                  ' AND tid=%(tid)d' % kw)
741
                if value_serial is None:
742
                    # First found, mark its serial for future reference.
743
                    kw['new_tid'] = value_serial = kw['tid']
744
        return value_serial
745 746 747

    def pack(self, tid, updateObjectDataForPack):
        # TODO: unit test (along with updatePackFuture)
748
        p64 = util.p64
749 750
        tid = util.u64(tid)
        updatePackFuture = self._updatePackFuture
751
        getPartition = self._getReadablePartition
752 753 754 755 756 757
        q = self.query
        self._setPackTID(tid)
        for count, oid, max_serial in q("SELECT COUNT(*) - 1, oid, MAX(tid)"
                                        " FROM obj WHERE tid <= %d GROUP BY oid"
                                        % tid):
            partition = getPartition(oid)
758
            if q("SELECT 1 FROM obj WHERE `partition` = %d"
759 760 761 762 763 764 765
                 " AND oid = %d AND tid = %d AND data_id IS NULL"
                 % (partition, oid, max_serial)):
                max_serial += 1
            elif not count:
                continue
            # There are things to delete for this object
            data_id_set = set()
766
            sql = ' FROM obj WHERE `partition`=%d AND oid=%d' \
767 768 769 770 771 772 773 774 775 776 777 778
                ' AND tid<%d' % (partition, oid, max_serial)
            for serial, data_id in q('SELECT tid, data_id' + sql):
                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)
            data_id_set.discard(None)
            self._pruneData(data_id_set)
        self.commit()
779

780
    def checkTIDRange(self, partition, length, min_tid, max_tid):
781
        count, tid_checksum, max_tid = self.query(
782
            """SELECT COUNT(*), SHA1(GROUP_CONCAT(tid SEPARATOR ",")), MAX(tid)
783
               FROM (SELECT tid FROM trans
784
                     WHERE `partition` = %(partition)s
785 786
                       AND tid >= %(min_tid)d
                       AND tid <= %(max_tid)d
787
                     ORDER BY tid ASC %(limit)s) AS t""" % {
788 789 790
            'partition': partition,
            'min_tid': util.u64(min_tid),
            'max_tid': util.u64(max_tid),
791
            'limit': '' if length is None else 'LIMIT %u' % length,
792
        })[0]
793 794 795
        if count:
            return count, a2b_hex(tid_checksum), util.p64(max_tid)
        return 0, ZERO_HASH, ZERO_TID
796

797
    def checkSerialRange(self, partition, length, min_tid, max_tid, min_oid):
798
        u64 = util.u64
799 800
        # We don't ask MySQL to compute everything (like in checkTIDRange)
        # because it's difficult to get the last serial _for the last oid_.
Julien Muchembled's avatar
Julien Muchembled committed
801
        # We would need a function (that could be named 'LAST') that returns the
802 803
        # last grouped value, instead of the greatest one.
        r = self.query(
804
            """SELECT tid, oid
805
               FROM obj
806
               WHERE `partition` = %(partition)s
807
                 AND tid <= %(max_tid)d
808 809 810
                 AND (tid > %(min_tid)d OR
                      tid = %(min_tid)d AND oid >= %(min_oid)d)
               ORDER BY tid, oid %(limit)s""" % {
811
            'min_oid': u64(min_oid),
812
            'min_tid': u64(min_tid),
813
            'max_tid': u64(max_tid),
814
            'limit': '' if length is None else 'LIMIT %u' % length,
815 816 817 818 819
            'partition': partition,
        })
        if r:
            p64 = util.p64
            return (len(r),
820
                    sha1(','.join(str(x[0]) for x in r)).digest(),
821
                    p64(r[-1][0]),
822
                    sha1(','.join(str(x[1]) for x in r)).digest(),
823
                    p64(r[-1][1]))
824
        return 0, ZERO_HASH, ZERO_TID, ZERO_HASH, ZERO_OID