summaryrefslogtreecommitdiff
path: root/jstests/core/collection_truncate.js
blob: bc7b07f6ebcfd8a9b12c0a95b766f02651865226 (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
/*
 * SERVER-15033 truncate on a regular collection
 *
 * @tags: [
 *   requires_collstats,
 *   requires_non_retryable_commands,
 *   uses_testing_only_commands,
 *   requires_emptycapped,
 *   uses_full_validation,
 *   no_selinux,
 *   # TODO SERVER-60823 re-add transaction support
 *   does_not_support_transactions,
 * ]
 */

(function() {
'use strict';

var t = db.getCollection('collection_truncate');
t.drop();

function truncate() {
    // Until SERVER-15274 is implemented, this is the only way to truncate a collection.
    assert.commandWorked(t.runCommand('emptycapped'));  // works on non-capped as well.
}

function assertEmpty() {
    var stats = t.stats();

    assert.eq(stats.count, 0);
    assert.eq(stats.size, 0);

    assert.eq(t.count(), 0);
    assert.eq(t.find().itcount(), 0);

    var res = t.validate({full: true});
    assert.commandWorked(res);
    assert(res.valid, "failed validate(): " + tojson(res));
}

// Single record case.
t.insert({a: 1});
truncate();
assertEmpty();

// Multi-extent case.
const initialStorageSize = t.stats().storageSize;
const long_string = Array(1024 * 1024).toString();

let idx = 0;
while (t.stats().storageSize == initialStorageSize) {
    let bulk = t.initializeUnorderedBulkOp();
    const nDocs = 300;
    for (let i = 0; i < nDocs; i++) {
        bulk.insert({a: ++idx, text: long_string});
    }
    assert.commandWorked(bulk.execute());
}
jsTest.log("Initial storage size: " + initialStorageSize);
jsTest.log("Num inserts: " + idx);
jsTest.log("Storage size after inserts: " + t.stats().storageSize);

truncate();
assertEmpty();

// Already empty case.
truncate();
assertEmpty();
}());