summaryrefslogtreecommitdiff
path: root/jstests/core/collmod_convert_index_uniqueness.js
blob: f041f0473aadfee02d4524887833b9fda4740b48 (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
/**
 * Basic js tests for the collMod command converting between regular indexes and unique indexes.
 *
 * @tags: [
 *  # Cannot implicitly shard accessed collections because of collection existing when none
 *  # expected.
 *  assumes_no_implicit_collection_creation_after_drop,  # common tag in collMod tests.
 *  requires_fcv_52,
 *  requires_non_retryable_commands, # common tag in collMod tests.
 *  # TODO(SERVER-61182): Fix WiredTigerKVEngine::alterIdentMetadata() under inMemory.
 *  requires_persistence,
 *  # The 'prepareUnique' field may cause the migration to fail.
 *  tenant_migration_incompatible,
 * ]
 */

(function() {
'use strict';

load("jstests/libs/feature_flag_util.js");

if (!FeatureFlagUtil.isEnabled(db, "CollModIndexUnique")) {
    jsTestLog('Skipping test because the collMod unique index feature flag is disabled.');
    return;
}

const collName = 'collmod_convert_to_unique';
const coll = db.getCollection(collName);
coll.drop();
assert.commandWorked(db.createCollection(collName));

function countUnique(key) {
    const all = coll.getIndexes().filter(function(z) {
        return z.unique && friendlyEqual(z.key, key);
    });
    return all.length;
}

// Creates a regular index and use collMod to convert it to a unique index.
assert.commandWorked(coll.createIndex({a: 1}));

// Tries to convert to unique without setting `prepareUnique`.
assert.commandFailedWithCode(
    db.runCommand({collMod: collName, index: {keyPattern: {a: 1}, unique: true}}),
    ErrorCodes.InvalidOptions);

// First sets 'prepareUnique' before converting the index to unique.
assert.commandWorked(
    db.runCommand({collMod: collName, index: {keyPattern: {a: 1}, prepareUnique: true}}));

// Tries to modify with a string 'unique' value.
assert.commandFailedWithCode(
    db.runCommand({collMod: collName, index: {keyPattern: {a: 1}, unique: '100'}}),
    ErrorCodes.TypeMismatch);

// Tries to modify with a false 'unique' value.
assert.commandFailedWithCode(db.runCommand({
    collMod: collName,
    index: {keyPattern: {a: 1}, unique: false},
}),
                             ErrorCodes.BadValue);

// Tries to modify a non-existent collection.
assert.commandFailedWithCode(db.runCommand({
    collMod: collName + '_missing',
    index: {keyPattern: {a: 1}, unique: true},
}),
                             ErrorCodes.NamespaceNotFound);

// Conversion should fail when there are existing duplicates.
assert.commandWorked(
    db.runCommand({collMod: collName, index: {keyPattern: {a: 1}, prepareUnique: false}}));
assert.commandWorked(coll.insert({_id: 1, a: 100}));
assert.commandWorked(coll.insert({_id: 2, a: 100}));
assert.commandWorked(
    db.runCommand({collMod: collName, index: {keyPattern: {a: 1}, prepareUnique: true}}));
const cannotConvertIndexToUniqueError = assert.commandFailedWithCode(
    db.runCommand({collMod: collName, index: {keyPattern: {a: 1}, unique: true}}),
    ErrorCodes.CannotConvertIndexToUnique);
jsTestLog('Cannot enable index constraint error from failed conversion: ' +
          tojson(cannotConvertIndexToUniqueError));

assert.commandWorked(coll.remove({_id: 2}));

//
// Dry-run mode tests.
//

// Currently, support for dry run mode should be limited to unique conversion.
assert.commandFailedWithCode(db.runCommand({
    collMod: collName,
    index: {keyPattern: {a: 1}, hidden: true},
    dryRun: true,
}),
                             ErrorCodes.InvalidOptions);
assert.commandFailedWithCode(db.runCommand({
    collMod: collName,
    validationLevel: 'off',
    dryRun: true,
}),
                             ErrorCodes.InvalidOptions);

// Unique may not be combined with any other modification in dry run mode.
assert.commandFailedWithCode(db.runCommand({
    collMod: collName,
    index: {keyPattern: {a: 1}, hidden: true, unique: true},
    dryRun: true,
}),
                             ErrorCodes.InvalidOptions);
assert.commandFailedWithCode(db.runCommand({
    collMod: collName,
    index: {keyPattern: {a: 1}, unique: true},
    validationLevel: 'off',
    dryRun: true,
}),
                             ErrorCodes.InvalidOptions);

// Conversion should not update the catalog in dry run mode.
assert.commandWorked(
    db.runCommand({collMod: collName, index: {keyPattern: {a: 1}, unique: true}, dryRun: true}));
assert.eq(countUnique({a: 1}), 0, 'index should not be unique: ' + tojson(coll.getIndexes()));

// Conversion should report errors if there are duplicates.
assert.commandWorked(
    db.runCommand({collMod: collName, index: {keyPattern: {a: 1}, prepareUnique: false}}));
assert.commandWorked(coll.insert({_id: 3, a: 100}));
assert.commandWorked(
    db.runCommand({collMod: collName, index: {keyPattern: {a: 1}, prepareUnique: true}}));
assert.commandFailedWithCode(
    db.runCommand({collMod: collName, index: {keyPattern: {a: 1}, unique: true}, dryRun: true}),
    ErrorCodes.CannotConvertIndexToUnique);
assert.commandWorked(coll.remove({_id: 3}));

// Successfully converts to a unique index.
let result = assert.commandWorked(
    db.runCommand({collMod: collName, index: {keyPattern: {a: 1}, unique: true}}));

// New index state should be reflected in 'unique_new' field in collMod response.
const assertUniqueNew = function(result) {
    assert(result.hasOwnProperty('unique_new'), tojson(result));
    assert(result.unique_new, tojson(result));
};
if (db.getMongo().isMongos()) {
    // Check the first shard's result from mongos.
    assert(result.hasOwnProperty('raw'), tojson(result));
    assertUniqueNew(Object.values(result.raw)[0]);
} else {
    assertUniqueNew(result);
}

// Look up index details in listIndexes output.
assert.eq(countUnique({a: 1}), 1, 'index should be unique now: ' + tojson(coll.getIndexes()));

// Test uniqueness constraint.
assert.commandFailedWithCode(coll.insert({_id: 100, a: 100}), ErrorCodes.DuplicateKey);

//
// Converting to non-unique index tests.
//

// Tries to modify with a false 'forceNonUnique' value.
assert.commandFailedWithCode(db.runCommand({
    collMod: collName,
    index: {keyPattern: {a: 1}, forceNonUnique: false},
}),
                             ErrorCodes.BadValue);

// Successfully converts to a regular index.
result = assert.commandWorked(
    db.runCommand({collMod: collName, index: {keyPattern: {a: 1}, forceNonUnique: true}}));

// New index state should be reflected in 'forceNonUnique_new' field in collMod response.
const assertForceNonUniqueNew = function(result) {
    assert(result.hasOwnProperty('forceNonUnique_new'), tojson(result));
    assert(result.forceNonUnique_new, tojson(result));
};
if (db.getMongo().isMongos()) {
    // Checks the first shard's result from mongos.
    assert(result.hasOwnProperty('raw'), tojson(result));
    assertForceNonUniqueNew(Object.values(result.raw)[0]);
} else {
    assertForceNonUniqueNew(result);
}

// Tests the index now accepts duplicate keys.
assert.commandWorked(coll.insert({_id: 100, a: 100}));
})();