summaryrefslogtreecommitdiff
path: root/src/mongo/db/storage/mobile/mobile_index.cpp
blob: a1c54273ce0a1e46b1c5f53d72062a338ce2a4c5 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
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
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
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
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
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
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
/**
 *    Copyright (C) 2018-present MongoDB, Inc.
 *
 *    This program is free software: you can redistribute it and/or modify
 *    it under the terms of the Server Side Public License, version 1,
 *    as published by MongoDB, Inc.
 *
 *    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
 *    Server Side Public License for more details.
 *
 *    You should have received a copy of the Server Side Public License
 *    along with this program. If not, see
 *    <http://www.mongodb.com/licensing/server-side-public-license>.
 *
 *    As a special exception, the copyright holders give permission to link the
 *    code of portions of this program with the OpenSSL library under certain
 *    conditions as described in each individual source file and distribute
 *    linked combinations including the program with the OpenSSL library. You
 *    must comply with the Server Side Public License in all respects for
 *    all of the code used other than as permitted herein. If you modify file(s)
 *    with this exception, you may extend this exception to your version of the
 *    file(s), but you are not obligated to do so. If you do not wish to do so,
 *    delete this exception statement from your version. If you delete this
 *    exception statement from all source files in the program, then also delete
 *    it in the license file.
 */

#include "mongo/platform/basic.h"

#include <sqlite3.h>

#include "mongo/bson/bsonobj.h"
#include "mongo/db/index/index_descriptor.h"
#include "mongo/db/operation_context.h"
#include "mongo/db/storage/key_string.h"
#include "mongo/db/storage/mobile/mobile_index.h"
#include "mongo/db/storage/mobile/mobile_recovery_unit.h"
#include "mongo/db/storage/mobile/mobile_sqlite_statement.h"
#include "mongo/db/storage/mobile/mobile_util.h"

namespace mongo {
namespace {

using std::shared_ptr;
using std::string;
using std::vector;

// BTree stuff

bool hasFieldNames(const BSONObj& obj) {
    BSONForEach(e, obj) {
        if (e.fieldName()[0])
            return true;
    }
    return false;
}

BSONObj stripFieldNames(const BSONObj& query) {
    if (!hasFieldNames(query))
        return query;

    BSONObjBuilder bb;
    BSONForEach(e, query) {
        bb.appendAs(e, StringData());
    }
    return bb.obj();
}

}  // namespace

MobileIndex::MobileIndex(OperationContext* opCtx,
                         const IndexDescriptor* desc,
                         const std::string& ident)
    : _isUnique(desc->unique()),
      _ordering(Ordering::make(desc->keyPattern())),
      _ident(ident),
      _collectionNamespace(desc->parentNS()),
      _indexName(desc->indexName()),
      _keyPattern(desc->keyPattern()) {}

StatusWith<SpecialFormatInserted> MobileIndex::insert(OperationContext* opCtx,
                                                      const BSONObj& key,
                                                      const RecordId& recId,
                                                      bool dupsAllowed) {
    invariant(recId.isValid());
    invariant(!hasFieldNames(key));

    return _insert(opCtx, key, recId, dupsAllowed);
}

template <typename ValueType>
StatusWith<SpecialFormatInserted> MobileIndex::doInsert(OperationContext* opCtx,
                                                        const KeyString& key,
                                                        const ValueType& value,
                                                        bool isTransactional) {
    MobileSession* session;
    if (isTransactional) {
        session = MobileRecoveryUnit::get(opCtx)->getSession(opCtx, false);
    } else {
        session = MobileRecoveryUnit::get(opCtx)->getSessionNoTxn(opCtx);
    }

    SqliteStatement insertStmt(
        *session, "INSERT INTO \"", _ident, "\" (key, value) VALUES (?, ?);");

    insertStmt.bindBlob(0, key.getBuffer(), key.getSize());
    insertStmt.bindBlob(1, value.getBuffer(), value.getSize());

    int status = insertStmt.step();
    if (status == SQLITE_CONSTRAINT) {
        insertStmt.setExceptionStatus(status);
        if (isUnique()) {
            // Return error if duplicate key inserted in a unique index.
            BSONObj bson =
                KeyString::toBson(key.getBuffer(), key.getSize(), _ordering, key.getTypeBits());
            return buildDupKeyErrorStatus(bson, _collectionNamespace, _indexName, _keyPattern);
        } else {
            // A record with same key could already be present in a standard index, that is OK. This
            // can happen when building a background index while documents are being written in
            // parallel.
            return StatusWith<SpecialFormatInserted>(
                SpecialFormatInserted::NoSpecialFormatInserted);
        }
    }
    embedded::checkStatus(status, SQLITE_DONE, "sqlite3_step");

    if (key.getTypeBits().isLongEncoding())
        return StatusWith<SpecialFormatInserted>(SpecialFormatInserted::LongTypeBitsInserted);

    return StatusWith<SpecialFormatInserted>(SpecialFormatInserted::NoSpecialFormatInserted);
}

void MobileIndex::unindex(OperationContext* opCtx,
                          const BSONObj& key,
                          const RecordId& recId,
                          bool dupsAllowed) {
    invariant(recId.isValid());
    invariant(!hasFieldNames(key));

    return _unindex(opCtx, key, recId, dupsAllowed);
}

void MobileIndex::_doDelete(OperationContext* opCtx, const KeyString& key, KeyString* value) {
    MobileSession* session = MobileRecoveryUnit::get(opCtx)->getSession(opCtx, false);

    SqliteStatement deleteStmt(
        *session, "DELETE FROM \"", _ident, "\" WHERE key = ?", value ? " AND value = ?" : "", ";");

    deleteStmt.bindBlob(0, key.getBuffer(), key.getSize());
    if (value) {
        deleteStmt.bindBlob(1, value->getBuffer(), value->getSize());
    }
    deleteStmt.step(SQLITE_DONE);
}

/**
 * Note: this validates the entire database file, not just the table used by this index.
 */
void MobileIndex::fullValidate(OperationContext* opCtx,
                               long long* numKeysOut,
                               ValidateResults* fullResults) const {
    if (fullResults) {
        embedded::doValidate(opCtx, fullResults);
        if (!fullResults->valid) {
            return;
        }
    }
    if (numKeysOut) {
        *numKeysOut = numEntries(opCtx);
    }
}

bool MobileIndex::appendCustomStats(OperationContext* opCtx,
                                    BSONObjBuilder* output,
                                    double scale) const {
    return false;
}

long long MobileIndex::getSpaceUsedBytes(OperationContext* opCtx) const {
    MobileSession* session = MobileRecoveryUnit::get(opCtx)->getSession(opCtx);

    // Sum the number of bytes in each column.
    // SQLite aggregate functions return null if the column is empty or has only nulls, so return 0
    // bytes if there is no data in the column.
    SqliteStatement sizeStmt(*session,
                             "SELECT IFNULL(SUM(LENGTH(key)), 0) + ",
                             "IFNULL(SUM(LENGTH(value)), 0) FROM \"",
                             _ident,
                             "\";");

    sizeStmt.step(SQLITE_ROW);

    long long dataSize = sizeStmt.getColInt(0);
    return dataSize;
}

long long MobileIndex::numEntries(OperationContext* opCtx) const {
    MobileSession* session = MobileRecoveryUnit::get(opCtx)->getSession(opCtx);

    SqliteStatement countStmt(*session, "SELECT COUNT(*) FROM \"", _ident, "\";");

    countStmt.step(SQLITE_ROW);
    long long numRecs = countStmt.getColInt(0);
    return numRecs;
}

bool MobileIndex::isEmpty(OperationContext* opCtx) {
    MobileSession* session = MobileRecoveryUnit::get(opCtx)->getSession(opCtx);

    SqliteStatement emptyCheckStmt(*session, "SELECT * FROM \"", _ident, "\" LIMIT 1;");

    int status = emptyCheckStmt.step();
    if (status == SQLITE_DONE) {
        return true;
    }
    embedded::checkStatus(status, SQLITE_ROW, "sqlite3_step");
    return false;
}

Status MobileIndex::initAsEmpty(OperationContext* opCtx) {
    // No-op.
    return Status::OK();
}

Status MobileIndex::create(OperationContext* opCtx, const std::string& ident) {
    MobileSession* session = MobileRecoveryUnit::get(opCtx)->getSessionNoTxn(opCtx);

    SqliteStatement createTableStmt(
        *session, "CREATE TABLE \"", ident, "\"(key BLOB PRIMARY KEY, value BLOB);");

    createTableStmt.step(SQLITE_DONE);
    return Status::OK();
}

Status MobileIndex::dupKeyCheck(OperationContext* opCtx, const BSONObj& key) {
    invariant(!hasFieldNames(key));
    invariant(_isUnique);

    if (_isDup(opCtx, key))
        return buildDupKeyErrorStatus(key, _collectionNamespace, _indexName, _keyPattern);
    return Status::OK();
}

bool MobileIndex::_isDup(OperationContext* opCtx, const BSONObj& key) {
    MobileSession* session = MobileRecoveryUnit::get(opCtx)->getSession(opCtx);

    SqliteStatement dupCheckStmt(*session, "SELECT COUNT(*) FROM \"", _ident, "\" WHERE key = ?;");

    KeyString keyStr(_keyStringVersion, key, _ordering);
    dupCheckStmt.bindBlob(0, keyStr.getBuffer(), keyStr.getSize());

    dupCheckStmt.step(SQLITE_ROW);
    long long records = dupCheckStmt.getColInt(0);
    return records > 1;
}

class MobileIndex::BulkBuilderBase : public SortedDataBuilderInterface {
public:
    BulkBuilderBase(MobileIndex* index,
                    OperationContext* opCtx,
                    bool dupsAllowed,
                    const NamespaceString& collectionNamespace,
                    const std::string& indexName,
                    const BSONObj& keyPattern)
        : _index(index),
          _opCtx(opCtx),
          _dupsAllowed(dupsAllowed),
          _collectionNamespace(collectionNamespace),
          _indexName(indexName),
          _keyPattern(keyPattern) {}

    virtual ~BulkBuilderBase() {}

    StatusWith<SpecialFormatInserted> addKey(const BSONObj& key, const RecordId& recId) override {
        invariant(recId.isValid());
        invariant(!hasFieldNames(key));

        Status status = _checkNextKey(key);
        if (!status.isOK()) {
            return status;
        }

        _lastKey = key.getOwned();

        return _addKey(key, recId);
    }

    SpecialFormatInserted commit(bool mayInterrupt) override {
        return SpecialFormatInserted::NoSpecialFormatInserted;
    }

protected:
    /**
     * Checks whether the new key to be inserted is > or >= the previous one depending
     * on _dupsAllowed.
     */
    Status _checkNextKey(const BSONObj& key) {
        const int cmp = key.woCompare(_lastKey, _index->getOrdering());
        if (!_dupsAllowed && cmp == 0) {
            return buildDupKeyErrorStatus(key, _collectionNamespace, _indexName, _keyPattern);
        } else if (cmp < 0) {
            return Status(ErrorCodes::InternalError, "expected higher RecordId in bulk builder");
        }
        return Status::OK();
    }

    virtual StatusWith<SpecialFormatInserted> _addKey(const BSONObj& key,
                                                      const RecordId& recId) = 0;

    MobileIndex* _index;
    OperationContext* const _opCtx;
    BSONObj _lastKey;
    const bool _dupsAllowed;
    const NamespaceString _collectionNamespace;
    const std::string _indexName;
    const BSONObj _keyPattern;
};

/**
 * Bulk builds a non-unique index.
 */
class MobileIndex::BulkBuilderStandard final : public BulkBuilderBase {
public:
    BulkBuilderStandard(MobileIndex* index,
                        OperationContext* opCtx,
                        bool dupsAllowed,
                        const NamespaceString& collectionNamespace,
                        const std::string& indexName,
                        const BSONObj& keyPattern)
        : BulkBuilderBase(index, opCtx, dupsAllowed, collectionNamespace, indexName, keyPattern) {}

protected:
    StatusWith<SpecialFormatInserted> _addKey(const BSONObj& key, const RecordId& recId) override {
        KeyString keyStr(_index->getKeyStringVersion(), key, _index->getOrdering(), recId);
        KeyString::TypeBits value = keyStr.getTypeBits();
        return _index->doInsert(_opCtx, keyStr, value, false);
    }
};

/**
 * Bulk builds a unique index.
 */
class MobileIndex::BulkBuilderUnique : public BulkBuilderBase {
public:
    BulkBuilderUnique(MobileIndex* index,
                      OperationContext* opCtx,
                      bool dupsAllowed,
                      const NamespaceString& collectionNamespace,
                      const std::string& indexName,
                      const BSONObj& keyPattern)
        : BulkBuilderBase(index, opCtx, dupsAllowed, collectionNamespace, indexName, keyPattern) {
        // Replication is not supported so dups are not allowed.
        invariant(!dupsAllowed);
    }

protected:
    StatusWith<SpecialFormatInserted> _addKey(const BSONObj& key, const RecordId& recId) override {
        const KeyString keyStr(_index->getKeyStringVersion(), key, _index->getOrdering());

        KeyString value(_index->getKeyStringVersion(), recId);
        KeyString::TypeBits typeBits = keyStr.getTypeBits();
        if (!typeBits.isAllZeros()) {
            value.appendTypeBits(typeBits);
        }

        return _index->doInsert(_opCtx, keyStr, value, false);
    }
};

namespace {

/**
 * Implements basic cursor functionality used by standard and unique indexes.
 */
class CursorBase : public SortedDataInterface::Cursor {
public:
    CursorBase(const MobileIndex& index, OperationContext* opCtx, bool isForward)
        : _index(index),
          _opCtx(opCtx),
          _isForward(isForward),
          _savedKey(index.getKeyStringVersion()),
          _savedRecId(0),
          _savedTypeBits(index.getKeyStringVersion()),
          _startPosition(index.getKeyStringVersion()) {
        MobileSession* session = MobileRecoveryUnit::get(opCtx)->getSession(opCtx);

        _stmt = stdx::make_unique<SqliteStatement>(*session,
                                                   "SELECT key, value FROM \"",
                                                   _index.getIdent(),
                                                   "\" WHERE key ",
                                                   (_isForward ? ">=" : "<="),
                                                   " ? ORDER BY key ",
                                                   (_isForward ? "ASC" : "DESC"),
                                                   ";");
    }

    virtual ~CursorBase() {}

    boost::optional<IndexKeyEntry> next(RequestedInfo parts) override {
        if (_isEOF) {
            return {};
        }

        _advance();
        _updatePosition();

        return getCurrentEntry(parts);
    }

    void setEndPosition(const BSONObj& key, bool inclusive) override {
        // Scan to end of index.
        if (key.isEmpty()) {
            _endPosition.reset();
            return;
        }

        // This uses the opposite rules as a normal seek because a forward scan should end after the
        // key if inclusive and before if exclusive.
        const auto discriminator =
            _isForward == inclusive ? KeyString::kExclusiveAfter : KeyString::kExclusiveBefore;
        _endPosition = stdx::make_unique<KeyString>(_index.getKeyStringVersion());
        _endPosition->resetToKey(stripFieldNames(key), _index.getOrdering(), discriminator);
    }

    boost::optional<IndexKeyEntry> seek(const BSONObj& key,
                                        bool inclusive,
                                        RequestedInfo parts) override {
        const BSONObj startKey = stripFieldNames(key);
        // By using a discriminator other than kInclusive, there is no need to distinguish
        // unique vs non-unique key formats since both start with the key.
        const auto discriminator =
            _isForward == inclusive ? KeyString::kExclusiveBefore : KeyString::kExclusiveAfter;
        _startPosition.resetToKey(startKey, _index.getOrdering(), discriminator);

        _doSeek();
        _updatePosition();

        return getCurrentEntry(parts);
    }

    boost::optional<IndexKeyEntry> seek(const IndexSeekPoint& seekPoint,
                                        RequestedInfo parts) override {
        BSONObj startKey = IndexEntryComparison::makeQueryObject(seekPoint, _isForward);

        const auto discriminator =
            _isForward ? KeyString::kExclusiveBefore : KeyString::kExclusiveAfter;
        _startPosition.resetToKey(startKey, _index.getOrdering(), discriminator);

        _doSeek();
        _updatePosition();

        return getCurrentEntry(parts);
    }

    // All work is done in restore().
    void save() override {
        // SQLite acquires implicit locks over the snapshot this cursor is using. It is important
        // to finalize the corresponding statement to release these locks.
        _stmt->finalize();
    }

    void saveUnpositioned() override {
        save();
    }

    void restore() override {
        if (_isEOF) {
            return;
        }

        // Obtaining a session starts a read transaction if not done already.
        MobileSession* session = MobileRecoveryUnit::get(_opCtx)->getSession(_opCtx);
        // save() finalized this cursor's SQLite statement. We need to prepare a new statement,
        // before re-positioning it at the saved state.
        _stmt->prepare(*session);

        _startPosition.resetFromBuffer(_savedKey.getBuffer(), _savedKey.getSize());
        bool isExactMatch = _doSeek();

        if (!isExactMatch) {
            _isEOF = false;
            _resetStatement();
        }
    }

    void detachFromOperationContext() override {
        _opCtx = nullptr;
    }

    void reattachToOperationContext(OperationContext* opCtx) override {
        _opCtx = opCtx;
    }

protected:
    /**
     * Advances the cursor and determines if end reached.
     */
    void _advance() {
        int status = _stmt->step();
        if (status == SQLITE_DONE) {
            _isEOF = true;
            return;
        }
        embedded::checkStatus(status, SQLITE_ROW, "sqlite3_step");

        _isEOF = false;

        const void* key = _stmt->getColBlob(0);
        const long long size = _stmt->getColBytes(0);

        KeyString currKey(_index.getKeyStringVersion());
        currKey.resetFromBuffer(key, size);

        // The cursor has reached EOF if the current row passes the end position.
        _isEOF = (_endPosition && _isForward && currKey > *_endPosition) ||
            (_endPosition && !_isForward && currKey < *_endPosition);
    }

    /**
     * Updates the cursor state to reflect current position by setting the current key value,
     * record id, and type bits.
     */
    void _updatePosition() {
        if (_isEOF) {
            return;
        }
        const void* key = _stmt->getColBlob(0);
        const long long size = _stmt->getColBytes(0);

        _savedKey.resetFromBuffer(key, size);
        _updateRecIdAndTypeBits();
    }

    /**
     * Returns the requested parts of the entry at the cursor's current position.
     */
    boost::optional<IndexKeyEntry> getCurrentEntry(RequestedInfo parts) const {
        if (_isEOF) {
            return {};
        }

        BSONObj bson;
        if (parts & kWantKey) {
            bson = KeyString::toBson(
                _savedKey.getBuffer(), _savedKey.getSize(), _index.getOrdering(), _savedTypeBits);
        }

        return {{std::move(bson), _savedRecId}};
    }

    /**
     * Moves the cursor to begin at the given position. Returns true if the new position matches
     * the saved position; returns false otherwise.
     */
    bool _doSeek() {
        _resetStatement();
        _bindStartPoint();

        _isEOF = false;

        _advance();

        if (_isEOF) {
            return false;
        }

        const void* key = _stmt->getColBlob(0);
        const long long size = _stmt->getColBytes(0);

        KeyString nearestKey(_index.getKeyStringVersion());
        nearestKey.resetFromBuffer(key, size);

        return nearestKey == _startPosition;
    }

    /**
     * Binds the start point for the cursor.
     */
    void _bindStartPoint() {
        _stmt->bindBlob(0, _startPosition.getBuffer(), _startPosition.getSize());
    }

    /**
     * Resets the prepared statement on the SQLite statement that performs the iteration.
     */
    void _resetStatement() {
        _stmt->reset();
    }

    virtual void _updateRecIdAndTypeBits() = 0;

    const MobileIndex& _index;
    OperationContext* _opCtx;  // Not owned.

    bool _isForward;
    bool _isEOF = true;

    KeyString _savedKey;
    RecordId _savedRecId;
    KeyString::TypeBits _savedTypeBits;

    // The statement executed to fetch rows from SQLite.
    std::unique_ptr<SqliteStatement> _stmt;

    KeyString _startPosition;
    std::unique_ptr<KeyString> _endPosition;
};

/**
 * Cursor for a non-unique index.
 */
class CursorStandard final : public CursorBase {
public:
    CursorStandard(const MobileIndex& index, OperationContext* opCtx, bool isForward)
        : CursorBase(index, opCtx, isForward) {}

protected:
    void _updateRecIdAndTypeBits() override {
        _savedRecId = KeyString::decodeRecordIdAtEnd(_savedKey.getBuffer(), _savedKey.getSize());

        const void* value = _stmt->getColBlob(1);
        const long long size = _stmt->getColBytes(1);
        BufReader br(value, size);
        _savedTypeBits.resetFromBuffer(&br);
    }
};

/**
 * Cursor for a unique index.
 */
class CursorUnique final : public CursorBase {
public:
    CursorUnique(const MobileIndex& index, OperationContext* opCtx, bool isForward)
        : CursorBase(index, opCtx, isForward) {}

protected:
    void _updateRecIdAndTypeBits() override {
        const void* value = _stmt->getColBlob(1);
        const long long size = _stmt->getColBytes(1);
        BufReader br(value, size);
        _savedRecId = KeyString::decodeRecordId(&br);
        _savedTypeBits.resetFromBuffer(&br);
    }
};
}  // namespace

MobileIndexStandard::MobileIndexStandard(OperationContext* opCtx,
                                         const IndexDescriptor* desc,
                                         const std::string& ident)
    : MobileIndex(opCtx, desc, ident) {}

SortedDataBuilderInterface* MobileIndexStandard::getBulkBuilder(OperationContext* opCtx,
                                                                bool dupsAllowed) {
    invariant(dupsAllowed);
    return new BulkBuilderStandard(
        this, opCtx, dupsAllowed, _collectionNamespace, _indexName, _keyPattern);
}

std::unique_ptr<SortedDataInterface::Cursor> MobileIndexStandard::newCursor(OperationContext* opCtx,
                                                                            bool isForward) const {
    return stdx::make_unique<CursorStandard>(*this, opCtx, isForward);
}

StatusWith<SpecialFormatInserted> MobileIndexStandard::_insert(OperationContext* opCtx,
                                                               const BSONObj& key,
                                                               const RecordId& recId,
                                                               bool dupsAllowed) {
    invariant(dupsAllowed);

    const KeyString keyStr(_keyStringVersion, key, _ordering, recId);
    const KeyString::TypeBits value = keyStr.getTypeBits();
    return doInsert(opCtx, keyStr, value);
}

void MobileIndexStandard::_unindex(OperationContext* opCtx,
                                   const BSONObj& key,
                                   const RecordId& recId,
                                   bool dupsAllowed) {
    invariant(dupsAllowed);

    const KeyString keyStr(_keyStringVersion, key, _ordering, recId);
    _doDelete(opCtx, keyStr);
}

MobileIndexUnique::MobileIndexUnique(OperationContext* opCtx,
                                     const IndexDescriptor* desc,
                                     const std::string& ident)
    : MobileIndex(opCtx, desc, ident), _isPartial(desc->isPartial()) {}

SortedDataBuilderInterface* MobileIndexUnique::getBulkBuilder(OperationContext* opCtx,
                                                              bool dupsAllowed) {
    // Replication is not supported so dups are not allowed.
    invariant(!dupsAllowed);
    return new BulkBuilderUnique(
        this, opCtx, dupsAllowed, _collectionNamespace, _indexName, _keyPattern);
}

std::unique_ptr<SortedDataInterface::Cursor> MobileIndexUnique::newCursor(OperationContext* opCtx,
                                                                          bool isForward) const {
    return stdx::make_unique<CursorUnique>(*this, opCtx, isForward);
}

StatusWith<SpecialFormatInserted> MobileIndexUnique::_insert(OperationContext* opCtx,
                                                             const BSONObj& key,
                                                             const RecordId& recId,
                                                             bool dupsAllowed) {
    // Replication is not supported so dups are not allowed.
    invariant(!dupsAllowed);
    const KeyString keyStr(_keyStringVersion, key, _ordering);

    KeyString value(_keyStringVersion, recId);
    KeyString::TypeBits typeBits = keyStr.getTypeBits();
    if (!typeBits.isAllZeros()) {
        value.appendTypeBits(typeBits);
    }

    return doInsert(opCtx, keyStr, value);
}

void MobileIndexUnique::_unindex(OperationContext* opCtx,
                                 const BSONObj& key,
                                 const RecordId& recId,
                                 bool dupsAllowed) {
    // Replication is not supported so dups are not allowed.
    invariant(!dupsAllowed);
    const KeyString keyStr(_keyStringVersion, key, _ordering);

    // A partial index may attempt to delete a non-existent record id. If it is a partial index, it
    // must delete a row that matches both key and value.
    if (_isPartial) {
        KeyString value(_keyStringVersion, recId);
        KeyString::TypeBits typeBits = keyStr.getTypeBits();
        if (!typeBits.isAllZeros()) {
            value.appendTypeBits(typeBits);
        }

        _doDelete(opCtx, keyStr, &value);
    } else {
        _doDelete(opCtx, keyStr);
    }
}

}  // namespace mongo