feat(mongodb): support safe index editing
This commit is contained in:
1 parent
880d635961
commit
799bdd1a62
27 files changed
+2754
-10
No files matched your search
Vendored
+486
-1
@@ -1,6 +1,6 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { createPinia, setActivePinia } from "pinia";
|
||||
import { shallowRef } from "vue";
|
||||
import { nextTick, shallowRef } from "vue";
|
||||
import type { TreeNode } from "@/types/database";
|
||||
import {
|
||||
cloneMongoCollectionError,
|
||||
@@ -8,19 +8,28 @@ import {
|
||||
cloneMongoCollectionName,
|
||||
mongoCreateIndexError,
|
||||
mongoCreateIndexForm,
|
||||
mongoEditIndexOriginalName,
|
||||
mongoIndexManagerError,
|
||||
mongoIndexManagerLoading,
|
||||
mongoIndexManagerMode,
|
||||
mongoIndexManagerRows,
|
||||
mongoIndexManagerSelectedName,
|
||||
resetMongoCreateIndexForm,
|
||||
resetMongoIndexManager,
|
||||
sidebarDangerTarget,
|
||||
sidebarFormTarget,
|
||||
showCloneMongoCollectionDialog,
|
||||
showCreateMongoIndexDialog,
|
||||
showDropAllMongoIndexesConfirm,
|
||||
showDropMongoCollectionConfirm,
|
||||
showMongoIndexManagerDialog,
|
||||
} from "@/components/sidebar/sidebarTreeDialogState";
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
toast: vi.fn(),
|
||||
ensureConnected: vi.fn().mockResolvedValue(undefined),
|
||||
loadIndexes: vi.fn().mockResolvedValue(undefined),
|
||||
mongoListIndexSpecs: vi.fn().mockResolvedValue([]),
|
||||
listMongoCompletionFields: vi.fn().mockResolvedValue([{ name: "email", type: "string" }]),
|
||||
loadMongoCollections: vi.fn().mockResolvedValue(undefined),
|
||||
loadMongoDatabases: vi.fn().mockResolvedValue(undefined),
|
||||
@@ -48,6 +57,7 @@ vi.mock("@/stores/connectionStore", () => ({
|
||||
}));
|
||||
|
||||
vi.mock("@/lib/backend/api", () => ({
|
||||
mongoListIndexSpecs: (...args: unknown[]) => mocks.mongoListIndexSpecs(...args),
|
||||
mongoCreateIndex: (...args: unknown[]) => mocks.mongoCreateIndex(...args),
|
||||
mongoCloneCollection: (...args: unknown[]) => mocks.mongoCloneCollection(...args),
|
||||
mongoDropCollection: (...args: unknown[]) => mocks.mongoDropCollection(...args),
|
||||
@@ -129,6 +139,13 @@ function mongoIndexNode(name: string, kind: "collection" | "view" | "timeseries"
|
||||
};
|
||||
}
|
||||
|
||||
/** Let the panel's fire-and-forget index load settle before asserting. */
|
||||
async function flush(): Promise<void> {
|
||||
await Promise.resolve();
|
||||
await Promise.resolve();
|
||||
await nextTick();
|
||||
}
|
||||
|
||||
function runtime(activeNode: TreeNode) {
|
||||
const indexesGroup = activeNode.type === "group-indexes" ? activeNode : mongoIndexesGroupNode();
|
||||
return useSidebarDatabaseSpecificMutationRuntime({
|
||||
@@ -153,6 +170,23 @@ describe("MongoDB sidebar mutation runtime", () => {
|
||||
mocks.getConfig.mockReturnValue(mongoConfig());
|
||||
mocks.ensureConnected.mockResolvedValue(undefined);
|
||||
mocks.loadIndexes.mockResolvedValue(undefined);
|
||||
mocks.mongoListIndexSpecs.mockResolvedValue([
|
||||
{ name: "_id_", keys: [{ field: "_id", direction: "1" }], is_unique: true, is_primary: true, is_sparse: false, expire_after_seconds: null, partial_filter_expression: null, background: false, bucket_size: null, hidden: false, properties_complete: true, extra_options: null },
|
||||
{
|
||||
name: "email_1",
|
||||
keys: [{ field: "email", direction: "1" }],
|
||||
is_unique: false,
|
||||
is_primary: false,
|
||||
is_sparse: true,
|
||||
expire_after_seconds: 3600,
|
||||
partial_filter_expression: '{"archived":false}',
|
||||
background: false,
|
||||
bucket_size: null,
|
||||
hidden: false,
|
||||
properties_complete: true,
|
||||
extra_options: null,
|
||||
},
|
||||
]);
|
||||
mocks.listMongoCompletionFields.mockResolvedValue([{ name: "email", type: "string" }]);
|
||||
mocks.loadMongoCollections.mockResolvedValue(undefined);
|
||||
mocks.loadMongoDatabases.mockResolvedValue(undefined);
|
||||
@@ -167,7 +201,9 @@ describe("MongoDB sidebar mutation runtime", () => {
|
||||
showCloneMongoCollectionDialog.value = false;
|
||||
showDropAllMongoIndexesConfirm.value = false;
|
||||
showDropMongoCollectionConfirm.value = false;
|
||||
showMongoIndexManagerDialog.value = false;
|
||||
resetMongoCreateIndexForm();
|
||||
resetMongoIndexManager();
|
||||
cloneMongoCollectionName.value = "";
|
||||
cloneMongoCollectionError.value = "";
|
||||
cloneMongoCollectionLoading.value = false;
|
||||
@@ -306,6 +342,10 @@ describe("MongoDB sidebar mutation runtime", () => {
|
||||
fields: [{ id: 7, path: "location", type: "2dsphere" }],
|
||||
unique: true,
|
||||
sparse: true,
|
||||
expireAfterSeconds: "600",
|
||||
partialFilterExpression: '{"active":true}',
|
||||
background: true,
|
||||
bucketSize: "32",
|
||||
};
|
||||
mongoCreateIndexError.value = "previous failure";
|
||||
|
||||
@@ -316,6 +356,11 @@ describe("MongoDB sidebar mutation runtime", () => {
|
||||
fields: [{ id: 1, path: "", type: "1" }],
|
||||
unique: false,
|
||||
sparse: false,
|
||||
expireAfterSeconds: "",
|
||||
partialFilterExpression: "",
|
||||
background: false,
|
||||
bucketSize: "",
|
||||
hidden: false,
|
||||
});
|
||||
expect(mongoCreateIndexError.value).toBe("");
|
||||
expect(showCreateMongoIndexDialog.value).toBe(true);
|
||||
@@ -333,6 +378,446 @@ describe("MongoDB sidebar mutation runtime", () => {
|
||||
expect(mocks.mongoCreateIndex).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("opens the index manager panel from a collection node and lists its indexes", async () => {
|
||||
const node = mongoCollectionNode();
|
||||
const feature = runtime(node);
|
||||
sidebarFormTarget.value = node;
|
||||
|
||||
expect(feature.canManageMongoIndexes.value).toBe(true);
|
||||
feature.prepareMongoIndexManagerDialog();
|
||||
await flush();
|
||||
|
||||
expect(showMongoIndexManagerDialog.value).toBe(true);
|
||||
expect(mocks.mongoListIndexSpecs).toHaveBeenCalledWith("conn-1", "app", "users");
|
||||
expect(mongoIndexManagerRows.value).toEqual([
|
||||
{
|
||||
name: "_id_",
|
||||
keys: "_id ASC",
|
||||
isUnique: true,
|
||||
isProtected: true,
|
||||
isSparse: false,
|
||||
expireAfterSeconds: undefined,
|
||||
partialFilterExpression: undefined,
|
||||
background: false,
|
||||
bucketSize: undefined,
|
||||
hidden: false,
|
||||
propertiesComplete: true,
|
||||
extraOptions: undefined,
|
||||
},
|
||||
{
|
||||
name: "email_1",
|
||||
keys: "email ASC",
|
||||
isUnique: false,
|
||||
isProtected: false,
|
||||
isSparse: true,
|
||||
expireAfterSeconds: 3600,
|
||||
partialFilterExpression: '{"archived":false}',
|
||||
background: false,
|
||||
bucketSize: undefined,
|
||||
hidden: false,
|
||||
propertiesComplete: true,
|
||||
extraOptions: undefined,
|
||||
},
|
||||
]);
|
||||
// The first row is auto-selected so the property pane is never blank.
|
||||
expect(mongoIndexManagerSelectedName.value).toBe("_id_");
|
||||
expect(feature.canDropSelectedMongoIndexRow.value).toBe(false);
|
||||
});
|
||||
|
||||
it("creates an index from the panel opened on a collection node and returns to view mode", async () => {
|
||||
const node = mongoCollectionNode();
|
||||
const feature = runtime(node);
|
||||
sidebarFormTarget.value = node;
|
||||
|
||||
feature.prepareMongoIndexManagerDialog();
|
||||
await flush();
|
||||
|
||||
feature.startCreateMongoIndexDraft();
|
||||
expect(mongoIndexManagerMode.value).toBe("create");
|
||||
mongoCreateIndexForm.value = { ...mongoCreateIndexForm.value, fields: [{ id: 1, path: "email", type: "1" }], expireAfterSeconds: "3600" };
|
||||
await feature.confirmCreateMongoIndex();
|
||||
await flush();
|
||||
|
||||
expect(mocks.mongoCreateIndex).toHaveBeenCalledWith("conn-1", "app", "users", '{"email":1}', '{"expireAfterSeconds":3600}');
|
||||
// The panel stays open, drops back to read-only, and selects the new index.
|
||||
expect(showMongoIndexManagerDialog.value).toBe(true);
|
||||
expect(mongoIndexManagerMode.value).toBe("view");
|
||||
expect(mongoIndexManagerSelectedName.value).toBe("email_1");
|
||||
});
|
||||
|
||||
it("drops the selected index from the panel while protecting the default index", async () => {
|
||||
const node = mongoCollectionNode();
|
||||
const feature = runtime(node);
|
||||
sidebarFormTarget.value = node;
|
||||
|
||||
feature.prepareMongoIndexManagerDialog();
|
||||
await flush();
|
||||
|
||||
feature.selectMongoIndexRow("email_1");
|
||||
expect(feature.canDropSelectedMongoIndexRow.value).toBe(true);
|
||||
await feature.dropSelectedMongoIndexRow();
|
||||
|
||||
expect(mocks.mongoDropIndexes).toHaveBeenCalledWith("conn-1", "app", "users", '"email_1"', true);
|
||||
|
||||
feature.selectMongoIndexRow("_id_");
|
||||
mocks.mongoDropIndexes.mockClear();
|
||||
await feature.dropSelectedMongoIndexRow();
|
||||
|
||||
expect(mocks.mongoDropIndexes).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("edits the selected index by dropping then creating and returns to view mode", async () => {
|
||||
const node = mongoCollectionNode();
|
||||
const feature = runtime(node);
|
||||
sidebarFormTarget.value = node;
|
||||
|
||||
feature.prepareMongoIndexManagerDialog();
|
||||
await flush();
|
||||
|
||||
feature.selectMongoIndexRow("email_1");
|
||||
expect(feature.canEditSelectedMongoIndexRow.value).toBe(true);
|
||||
|
||||
feature.startEditMongoIndexDraft();
|
||||
expect(mongoIndexManagerMode.value).toBe("edit");
|
||||
expect(mongoEditIndexOriginalName.value).toBe("email_1");
|
||||
// The form is prefilled from the selected row.
|
||||
expect(mongoCreateIndexForm.value.name).toBe("email_1");
|
||||
expect(mongoCreateIndexForm.value.fields).toEqual([{ id: 1, path: "email", type: "1" }]);
|
||||
expect(mongoCreateIndexForm.value.sparse).toBe(true);
|
||||
expect(mongoCreateIndexForm.value.expireAfterSeconds).toBe("3600");
|
||||
|
||||
// Rename: create new first, then drop old.
|
||||
mongoCreateIndexForm.value.name = "email_renamed";
|
||||
await feature.confirmEditMongoIndex();
|
||||
await flush();
|
||||
|
||||
// Re-read happens before any mutation; then create(new) before drop(old).
|
||||
expect(mocks.mongoListIndexSpecs).toHaveBeenCalledWith("conn-1", "app", "users");
|
||||
expect(mocks.mongoCreateIndex).toHaveBeenCalledWith("conn-1", "app", "users", '{"email":1}', '{"name":"email_renamed","sparse":true,"expireAfterSeconds":3600,"partialFilterExpression":{"archived":false}}');
|
||||
expect(mocks.mongoDropIndexes).toHaveBeenCalledWith("conn-1", "app", "users", '"email_1"', true);
|
||||
expect(mongoIndexManagerMode.value).toBe("view");
|
||||
expect(mongoEditIndexOriginalName.value).toBe("");
|
||||
expect(mongoIndexManagerSelectedName.value).toBe("email_1");
|
||||
});
|
||||
|
||||
it("does not edit the protected _id index", async () => {
|
||||
const node = mongoCollectionNode();
|
||||
const feature = runtime(node);
|
||||
sidebarFormTarget.value = node;
|
||||
|
||||
feature.prepareMongoIndexManagerDialog();
|
||||
await flush();
|
||||
|
||||
feature.selectMongoIndexRow("_id_");
|
||||
expect(feature.canEditSelectedMongoIndexRow.value).toBe(false);
|
||||
|
||||
feature.startEditMongoIndexDraft();
|
||||
expect(mongoIndexManagerMode.value).toBe("view");
|
||||
expect(mocks.mongoDropIndexes).not.toHaveBeenCalled();
|
||||
expect(mocks.mongoCreateIndex).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("does not edit or rename an index without a complete server specification", async () => {
|
||||
mocks.mongoListIndexSpecs.mockResolvedValueOnce([
|
||||
{ name: "_id_", keys: [{ field: "_id", direction: "1" }], is_unique: true, is_primary: true, is_sparse: false, expire_after_seconds: null, partial_filter_expression: null, background: false, bucket_size: null, hidden: false, properties_complete: true, extra_options: null },
|
||||
{
|
||||
name: "email_1",
|
||||
keys: [{ field: "email", direction: "1" }],
|
||||
is_unique: false,
|
||||
is_primary: false,
|
||||
is_sparse: false,
|
||||
expire_after_seconds: null,
|
||||
partial_filter_expression: null,
|
||||
background: false,
|
||||
bucket_size: null,
|
||||
hidden: false,
|
||||
properties_complete: false,
|
||||
extra_options: null,
|
||||
},
|
||||
]);
|
||||
const node = mongoCollectionNode();
|
||||
const feature = runtime(node);
|
||||
sidebarFormTarget.value = node;
|
||||
|
||||
feature.prepareMongoIndexManagerDialog();
|
||||
await flush();
|
||||
feature.selectMongoIndexRow("email_1");
|
||||
|
||||
expect(feature.canEditSelectedMongoIndexRow.value).toBe(false);
|
||||
feature.startEditMongoIndexDraft();
|
||||
expect(mongoIndexManagerMode.value).toBe("view");
|
||||
expect(mocks.mongoCreateIndex).not.toHaveBeenCalled();
|
||||
expect(mocks.mongoDropIndexes).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("creates the new index first when renaming and does not drop if create fails", async () => {
|
||||
const node = mongoCollectionNode();
|
||||
const feature = runtime(node);
|
||||
sidebarFormTarget.value = node;
|
||||
|
||||
feature.prepareMongoIndexManagerDialog();
|
||||
await flush();
|
||||
|
||||
feature.selectMongoIndexRow("email_1");
|
||||
feature.startEditMongoIndexDraft();
|
||||
mongoCreateIndexForm.value.name = "email_v2";
|
||||
|
||||
mocks.mongoCreateIndex.mockRejectedValueOnce(new Error("duplicate key"));
|
||||
await feature.confirmEditMongoIndex();
|
||||
await flush();
|
||||
|
||||
// Create was attempted; drop was never called because create failed.
|
||||
expect(mocks.mongoCreateIndex).toHaveBeenCalled();
|
||||
expect(mocks.mongoDropIndexes).not.toHaveBeenCalled();
|
||||
// The error surfaces in the panel.
|
||||
expect(mongoCreateIndexError.value).toContain("duplicate key");
|
||||
});
|
||||
|
||||
it("restores the complete original specification when a same-name rebuild fails", async () => {
|
||||
const node = mongoCollectionNode();
|
||||
const feature = runtime(node);
|
||||
sidebarFormTarget.value = node;
|
||||
|
||||
feature.prepareMongoIndexManagerDialog();
|
||||
await flush();
|
||||
|
||||
feature.selectMongoIndexRow("email_1");
|
||||
feature.startEditMongoIndexDraft();
|
||||
mongoCreateIndexForm.value.unique = true;
|
||||
|
||||
mocks.mongoCreateIndex.mockRejectedValueOnce(new Error("index build failed")).mockResolvedValueOnce({ name: "email_1" });
|
||||
await feature.confirmEditMongoIndex();
|
||||
await flush();
|
||||
|
||||
expect(mocks.mongoDropIndexes).toHaveBeenCalledWith("conn-1", "app", "users", '"email_1"', true);
|
||||
expect(mocks.mongoCreateIndex).toHaveBeenNthCalledWith(1, "conn-1", "app", "users", '{"email":1}', '{"name":"email_1","unique":true,"sparse":true,"expireAfterSeconds":3600,"partialFilterExpression":{"archived":false}}');
|
||||
expect(mocks.mongoCreateIndex).toHaveBeenNthCalledWith(2, "conn-1", "app", "users", '{"email":1}', '{"name":"email_1","sparse":true,"expireAfterSeconds":3600,"partialFilterExpression":{"archived":false}}');
|
||||
expect(mongoCreateIndexError.value).toContain("email_1");
|
||||
expect(mongoCreateIndexError.value).toContain("index build failed");
|
||||
expect(mongoCreateIndexError.value).toContain("mongoEditIndexCreateFailedRolledBack");
|
||||
});
|
||||
|
||||
it("reports both replacement and rollback errors when restoring a same-name index fails", async () => {
|
||||
const node = mongoCollectionNode();
|
||||
const feature = runtime(node);
|
||||
sidebarFormTarget.value = node;
|
||||
|
||||
feature.prepareMongoIndexManagerDialog();
|
||||
await flush();
|
||||
feature.selectMongoIndexRow("email_1");
|
||||
feature.startEditMongoIndexDraft();
|
||||
mongoCreateIndexForm.value.unique = true;
|
||||
|
||||
mocks.mongoCreateIndex.mockRejectedValueOnce(new Error("replacement failed")).mockRejectedValueOnce(new Error("rollback failed"));
|
||||
await feature.confirmEditMongoIndex();
|
||||
await flush();
|
||||
|
||||
expect(mocks.mongoCreateIndex).toHaveBeenCalledTimes(2);
|
||||
expect(mongoCreateIndexError.value).toContain("replacement failed");
|
||||
expect(mongoCreateIndexError.value).toContain("rollback failed");
|
||||
});
|
||||
|
||||
it("aborts the edit when the index no longer exists on the server", async () => {
|
||||
const node = mongoCollectionNode();
|
||||
const feature = runtime(node);
|
||||
sidebarFormTarget.value = node;
|
||||
|
||||
feature.prepareMongoIndexManagerDialog();
|
||||
await flush();
|
||||
|
||||
feature.selectMongoIndexRow("email_1");
|
||||
feature.startEditMongoIndexDraft();
|
||||
|
||||
// Simulate the index being deleted by another session before confirm.
|
||||
mocks.mongoListIndexSpecs.mockResolvedValueOnce([
|
||||
{ name: "_id_", keys: [{ field: "_id", direction: "1" }], is_unique: true, is_primary: true, is_sparse: false, expire_after_seconds: null, partial_filter_expression: null, background: false, bucket_size: null, hidden: false, properties_complete: true, extra_options: null },
|
||||
]);
|
||||
await feature.confirmEditMongoIndex();
|
||||
await flush();
|
||||
|
||||
expect(mocks.mongoDropIndexes).not.toHaveBeenCalled();
|
||||
expect(mocks.mongoCreateIndex).not.toHaveBeenCalled();
|
||||
expect(mongoCreateIndexError.value).toContain("email_1");
|
||||
});
|
||||
|
||||
it("aborts the edit when the index keys changed since the dialog was opened", async () => {
|
||||
const node = mongoCollectionNode();
|
||||
const feature = runtime(node);
|
||||
sidebarFormTarget.value = node;
|
||||
|
||||
feature.prepareMongoIndexManagerDialog();
|
||||
await flush();
|
||||
|
||||
feature.selectMongoIndexRow("email_1");
|
||||
feature.startEditMongoIndexDraft();
|
||||
|
||||
// Simulate the index being modified by another session (direction changed).
|
||||
mocks.mongoListIndexSpecs.mockResolvedValueOnce([
|
||||
{ name: "_id_", keys: [{ field: "_id", direction: "1" }], is_unique: true, is_primary: true, is_sparse: false, expire_after_seconds: null, partial_filter_expression: null, background: false, bucket_size: null, hidden: false, properties_complete: true, extra_options: null },
|
||||
{ name: "email_1", keys: [{ field: "email", direction: "-1" }], is_unique: false, is_primary: false, is_sparse: false, expire_after_seconds: null, partial_filter_expression: null, background: false, bucket_size: null, hidden: false, properties_complete: true, extra_options: null },
|
||||
]);
|
||||
await feature.confirmEditMongoIndex();
|
||||
await flush();
|
||||
|
||||
expect(mocks.mongoDropIndexes).not.toHaveBeenCalled();
|
||||
expect(mocks.mongoCreateIndex).not.toHaveBeenCalled();
|
||||
expect(mongoCreateIndexError.value).toContain("email_1");
|
||||
});
|
||||
|
||||
it("aborts the edit when the keys match but the complete server options changed", async () => {
|
||||
const node = mongoCollectionNode();
|
||||
const feature = runtime(node);
|
||||
sidebarFormTarget.value = node;
|
||||
|
||||
feature.prepareMongoIndexManagerDialog();
|
||||
await flush();
|
||||
feature.selectMongoIndexRow("email_1");
|
||||
feature.startEditMongoIndexDraft();
|
||||
|
||||
mocks.mongoListIndexSpecs.mockResolvedValueOnce([
|
||||
{ name: "_id_", keys: [{ field: "_id", direction: "1" }], is_unique: true, is_primary: true, is_sparse: false, expire_after_seconds: null, partial_filter_expression: null, background: false, bucket_size: null, hidden: false, properties_complete: true, extra_options: null },
|
||||
{
|
||||
name: "email_1",
|
||||
keys: [{ field: "email", direction: "1" }],
|
||||
is_unique: true,
|
||||
is_primary: false,
|
||||
is_sparse: true,
|
||||
expire_after_seconds: 3600,
|
||||
partial_filter_expression: '{"archived":false}',
|
||||
background: false,
|
||||
bucket_size: null,
|
||||
hidden: true,
|
||||
properties_complete: true,
|
||||
extra_options: '{"collation":{"locale":"fr"}}',
|
||||
},
|
||||
]);
|
||||
await feature.confirmEditMongoIndex();
|
||||
await flush();
|
||||
|
||||
expect(mocks.mongoDropIndexes).not.toHaveBeenCalled();
|
||||
expect(mocks.mongoCreateIndex).not.toHaveBeenCalled();
|
||||
expect(mongoCreateIndexError.value).toContain("mongoEditIndexStale");
|
||||
});
|
||||
|
||||
it("does not report a rename as successful when drop returns structured failures", async () => {
|
||||
const node = mongoCollectionNode();
|
||||
const feature = runtime(node);
|
||||
sidebarFormTarget.value = node;
|
||||
|
||||
feature.prepareMongoIndexManagerDialog();
|
||||
await flush();
|
||||
feature.selectMongoIndexRow("email_1");
|
||||
feature.startEditMongoIndexDraft();
|
||||
mongoCreateIndexForm.value.name = "email_v2";
|
||||
mocks.mongoCreateIndex.mockResolvedValueOnce({ name: "email_v2" });
|
||||
mocks.mongoDropIndexes.mockResolvedValueOnce({
|
||||
dropped_names: [],
|
||||
affected_rows: 0,
|
||||
failures: [{ name: "email_1", message: "not authorized" }],
|
||||
});
|
||||
|
||||
await feature.confirmEditMongoIndex();
|
||||
await flush();
|
||||
|
||||
expect(mocks.mongoCreateIndex).toHaveBeenCalledOnce();
|
||||
expect(mocks.mongoDropIndexes).toHaveBeenCalledOnce();
|
||||
expect(mongoIndexManagerMode.value).toBe("edit");
|
||||
expect(mongoCreateIndexError.value).toContain("not authorized");
|
||||
expect(mongoCreateIndexError.value).toContain("mongoEditIndexDropFailedAfterCreate");
|
||||
expect(mocks.toast).not.toHaveBeenCalledWith(expect.stringContaining("mongoEditIndexSuccess"), 3000);
|
||||
});
|
||||
|
||||
it("does not create or report rollback when a same-name drop returns structured failures", async () => {
|
||||
const node = mongoCollectionNode();
|
||||
const feature = runtime(node);
|
||||
sidebarFormTarget.value = node;
|
||||
|
||||
feature.prepareMongoIndexManagerDialog();
|
||||
await flush();
|
||||
feature.selectMongoIndexRow("email_1");
|
||||
feature.startEditMongoIndexDraft();
|
||||
mongoCreateIndexForm.value.unique = true;
|
||||
mocks.mongoDropIndexes.mockResolvedValueOnce({
|
||||
dropped_names: [],
|
||||
affected_rows: 0,
|
||||
failures: [{ name: "email_1", message: "index is busy" }],
|
||||
});
|
||||
|
||||
await feature.confirmEditMongoIndex();
|
||||
await flush();
|
||||
|
||||
expect(mocks.mongoCreateIndex).not.toHaveBeenCalled();
|
||||
expect(mongoIndexManagerMode.value).toBe("edit");
|
||||
expect(mongoCreateIndexError.value).toContain("index is busy");
|
||||
expect(mongoCreateIndexError.value).toContain("mongoEditIndexDropFailed");
|
||||
expect(mongoCreateIndexError.value).not.toContain("mongoEditIndexCreateFailedRolledBack");
|
||||
});
|
||||
|
||||
it("preserves extra options (collation, wildcardProjection) through the edit", async () => {
|
||||
const node = mongoCollectionNode();
|
||||
const feature = runtime(node);
|
||||
sidebarFormTarget.value = node;
|
||||
|
||||
// Seed the list with an index that has extraOptions.
|
||||
mocks.mongoListIndexSpecs.mockReturnValue([
|
||||
{ name: "_id_", keys: [{ field: "_id", direction: "1" }], is_unique: true, is_primary: true, is_sparse: false, expire_after_seconds: null, partial_filter_expression: null, background: false, bucket_size: null, hidden: false, properties_complete: true, extra_options: null },
|
||||
{
|
||||
name: "wild_1",
|
||||
keys: [{ field: "x", direction: "1" }],
|
||||
is_unique: false,
|
||||
is_primary: false,
|
||||
is_sparse: false,
|
||||
expire_after_seconds: null,
|
||||
partial_filter_expression: null,
|
||||
background: false,
|
||||
bucket_size: null,
|
||||
hidden: false,
|
||||
properties_complete: true,
|
||||
extra_options: '{"wildcardProjection":{"x":1}}',
|
||||
},
|
||||
]);
|
||||
|
||||
feature.prepareMongoIndexManagerDialog();
|
||||
await flush();
|
||||
|
||||
feature.selectMongoIndexRow("wild_1");
|
||||
feature.startEditMongoIndexDraft();
|
||||
mongoCreateIndexForm.value.name = "wild_v2";
|
||||
await feature.confirmEditMongoIndex();
|
||||
await flush();
|
||||
|
||||
expect(mocks.mongoCreateIndex).toHaveBeenCalled();
|
||||
const createArgs = mocks.mongoCreateIndex.mock.calls[0];
|
||||
const optionsJson = createArgs[4];
|
||||
expect(optionsJson).toContain("wildcardProjection");
|
||||
});
|
||||
|
||||
it("surfaces an index-list failure in the panel instead of showing a stale list", async () => {
|
||||
const node = mongoCollectionNode();
|
||||
const feature = runtime(node);
|
||||
sidebarFormTarget.value = node;
|
||||
mocks.mongoListIndexSpecs.mockRejectedValueOnce(new Error("listIndexes failed"));
|
||||
|
||||
feature.prepareMongoIndexManagerDialog();
|
||||
await flush();
|
||||
|
||||
expect(mongoIndexManagerRows.value).toEqual([]);
|
||||
expect(mongoIndexManagerSelectedName.value).toBe("");
|
||||
expect(mongoIndexManagerError.value).toContain("listIndexes failed");
|
||||
expect(mongoIndexManagerLoading.value).toBe(false);
|
||||
});
|
||||
|
||||
it("does not open the index manager panel for read-only MongoDB connections", () => {
|
||||
mocks.getConfig.mockReturnValue({ ...mongoConfig(), read_only: true });
|
||||
const node = mongoCollectionNode();
|
||||
const feature = runtime(node);
|
||||
|
||||
feature.prepareMongoIndexManagerDialog();
|
||||
|
||||
expect(showMongoIndexManagerDialog.value).toBe(false);
|
||||
expect(mocks.mongoListIndexSpecs).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("does not clear indexes through a collection node", async () => {
|
||||
const node = mongoCollectionNode();
|
||||
const feature = runtime(node);
|
||||
|
||||
@@ -13,8 +13,11 @@ import {
|
||||
isCloneableMongoCollection,
|
||||
isProtectedMongoIndex,
|
||||
isRenamableMongoCollection,
|
||||
mergeExtraOptionsIntoRequest,
|
||||
mongoCollectionKindFromNode,
|
||||
mongoCloneCollectionPreview,
|
||||
mongoCreateIndexRequestFromSpec,
|
||||
mongoCreateIndexFormFromRow,
|
||||
mongoCreateIndexPreview,
|
||||
mongoDropAllIndexesPreview,
|
||||
mongoDropCollectionPreview,
|
||||
@@ -22,6 +25,12 @@ import {
|
||||
mongoDropDatabasePreview,
|
||||
mongoDropIndexPreview,
|
||||
mongoRenameCollectionPreview,
|
||||
mongoReplaceIndexPreview,
|
||||
preflightEditIndexSpec,
|
||||
snapshotMongoIndexSpec,
|
||||
toMongoIndexRow,
|
||||
type MongoCreateIndexRequest,
|
||||
type MongoIndexSpecSnapshot,
|
||||
} from "@/lib/sidebar/mongoCollectionMutation";
|
||||
import { supportsMongoAllDriverMutations, supportsMongoIndexMutations, supportsNativeMongoDriverMutations } from "@/lib/mongo/mongoCapabilities";
|
||||
import { runMongoSidebarMutation } from "@/lib/sidebar/runMongoSidebarMutation";
|
||||
@@ -66,6 +75,14 @@ import {
|
||||
mongoCreateIndexError,
|
||||
mongoCreateIndexLoading,
|
||||
resetMongoCreateIndexForm,
|
||||
showMongoIndexManagerDialog,
|
||||
mongoIndexManagerRows,
|
||||
mongoIndexManagerLoading,
|
||||
mongoIndexManagerError,
|
||||
mongoIndexManagerSelectedName,
|
||||
mongoIndexManagerMode,
|
||||
mongoEditIndexOriginalName,
|
||||
resetMongoIndexManager,
|
||||
} from "@/components/sidebar/sidebarTreeDialogState";
|
||||
|
||||
interface SidebarDatabaseSpecificMutationRuntimeOptions {
|
||||
@@ -84,6 +101,8 @@ export function useSidebarDatabaseSpecificMutationRuntime(options: SidebarDataba
|
||||
const { t } = useI18n();
|
||||
const { toast } = useToast();
|
||||
const { activeNode, connectionStore } = options;
|
||||
let mongoIndexSpecsByName = new Map<string, MongoIndexSpecSnapshot>();
|
||||
let mongoEditIndexOriginalSpec: MongoIndexSpecSnapshot | undefined;
|
||||
|
||||
function usesAnyMongoDriver(node: Pick<TreeNode, "connectionId">): boolean {
|
||||
return !!node.connectionId && supportsMongoAllDriverMutations(connectionStore.getConfig(node.connectionId));
|
||||
@@ -240,11 +259,25 @@ export function useSidebarDatabaseSpecificMutationRuntime(options: SidebarDataba
|
||||
return node.type === "group-indexes" ? node.tableName || "" : "";
|
||||
}
|
||||
|
||||
/**
|
||||
* The manager panel is also reachable from the collection node, while direct
|
||||
* create / drop-all actions stay scoped to the Indexes group.
|
||||
*/
|
||||
function mongoIndexPanelCollectionName(node: TreeNode): string {
|
||||
if (node.type === "mongo-collection") return node.label;
|
||||
return mongoIndexCollectionName(node);
|
||||
}
|
||||
|
||||
function canManageMongoIndexPanelNode(node: TreeNode): boolean {
|
||||
return !!mongoIndexPanelCollectionName(node) && !!node.database && canMutateMongoIndexes(node);
|
||||
}
|
||||
|
||||
function canManageMongoIndexesNode(node: TreeNode): boolean {
|
||||
return !!mongoIndexCollectionName(node) && !!node.database && canMutateMongoIndexes(node);
|
||||
}
|
||||
|
||||
const canDropAllMongoIndexes = computed(() => canManageMongoIndexesNode(activeNode.value));
|
||||
const canManageMongoIndexes = computed(() => canManageMongoIndexPanelNode(activeNode.value));
|
||||
|
||||
function mongoIndexDropPreview(node: Pick<TreeNode, "database" | "tableName">, indexName: string): string {
|
||||
return mongoDropIndexPreview(node.database || "", node.tableName || "", indexName);
|
||||
@@ -259,7 +292,8 @@ export function useSidebarDatabaseSpecificMutationRuntime(options: SidebarDataba
|
||||
}
|
||||
|
||||
const canCreateMongoIndex = computed(() => canCreateMongoIndexNode(activeNode.value));
|
||||
const mongoCreateIndexCanSubmit = computed(() => mongoCreateIndexForm.value.fields.length > 0 && mongoCreateIndexForm.value.fields.every((field) => !!field.path.trim()));
|
||||
/** Mirror the full request validation so the button never invites a known error. */
|
||||
const mongoCreateIndexCanSubmit = computed(() => buildMongoCreateIndexRequest(mongoCreateIndexForm.value).valid);
|
||||
const mongoCreateIndexCanAddField = computed(() => mongoCreateIndexForm.value.fields.every((field) => !!field.path.trim()));
|
||||
|
||||
watch(
|
||||
@@ -286,6 +320,155 @@ export function useSidebarDatabaseSpecificMutationRuntime(options: SidebarDataba
|
||||
});
|
||||
}
|
||||
|
||||
async function loadMongoIndexManagerRows() {
|
||||
const node = sidebarFormTarget.value ?? activeNode.value;
|
||||
const connectionId = node.connectionId;
|
||||
const database = node.database;
|
||||
const collection = mongoIndexPanelCollectionName(node);
|
||||
if (!connectionId || !database || !collection) return;
|
||||
|
||||
mongoIndexManagerLoading.value = true;
|
||||
mongoIndexManagerError.value = "";
|
||||
try {
|
||||
await connectionStore.ensureConnected(connectionId);
|
||||
// MongoDB-specific read: the shared IndexInfo shape cannot carry sparse,
|
||||
// TTL, background or bucketSize. The backend degrades to the generic
|
||||
// listing for Legacy Agent connections and flags it there.
|
||||
const specs = await api.mongoListIndexSpecs(connectionId, database, collection);
|
||||
mongoIndexSpecsByName = new Map(specs.map((spec) => [spec.name, snapshotMongoIndexSpec(spec)] as const));
|
||||
mongoIndexManagerRows.value = specs.map(toMongoIndexRow);
|
||||
const selected = mongoIndexManagerSelectedName.value;
|
||||
if (!selected || !mongoIndexManagerRows.value.some((row) => row.name === selected)) {
|
||||
mongoIndexManagerSelectedName.value = mongoIndexManagerRows.value[0]?.name ?? "";
|
||||
}
|
||||
} catch (error) {
|
||||
mongoIndexSpecsByName.clear();
|
||||
mongoIndexManagerRows.value = [];
|
||||
mongoIndexManagerSelectedName.value = "";
|
||||
mongoIndexManagerError.value = translateBackendError(t, errorMessage(error));
|
||||
} finally {
|
||||
mongoIndexManagerLoading.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
function prepareMongoIndexManagerDialog() {
|
||||
const node = activeNode.value;
|
||||
if (!canManageMongoIndexPanelNode(node) || !node.connectionId || !node.database) return;
|
||||
resetMongoIndexManager();
|
||||
resetMongoCreateIndexForm();
|
||||
mongoIndexSpecsByName.clear();
|
||||
mongoEditIndexOriginalSpec = undefined;
|
||||
showMongoIndexManagerDialog.value = true;
|
||||
void loadMongoIndexManagerRows();
|
||||
}
|
||||
|
||||
const mongoIndexManagerSelected = computed(() => mongoIndexManagerRows.value.find((row) => row.name === mongoIndexManagerSelectedName.value));
|
||||
|
||||
/** Resolve against the dialog's own target so the header survives tree selection changes. */
|
||||
const mongoIndexManagerCollectionName = computed(() => mongoIndexPanelCollectionName(sidebarFormTarget.value ?? activeNode.value));
|
||||
|
||||
function selectMongoIndexRow(name: string) {
|
||||
if (mongoIndexManagerMode.value === "create" || mongoIndexManagerMode.value === "edit") return;
|
||||
mongoIndexManagerSelectedName.value = name;
|
||||
}
|
||||
|
||||
/** Switch the property pane into an editable draft for a brand new index. */
|
||||
function startCreateMongoIndexDraft() {
|
||||
const node = sidebarFormTarget.value ?? activeNode.value;
|
||||
resetMongoCreateIndexForm();
|
||||
mongoIndexManagerMode.value = "create";
|
||||
mongoIndexManagerError.value = "";
|
||||
if (!node.connectionId || !node.database) return;
|
||||
const collection = mongoIndexPanelCollectionName(node);
|
||||
if (!collection) return;
|
||||
void connectionStore
|
||||
.listMongoCompletionFields(node.connectionId, node.database, collection)
|
||||
.then((fields) => {
|
||||
if (showMongoIndexManagerDialog.value) mongoCreateIndexFieldOptions.value = fields.map((field) => field.name);
|
||||
})
|
||||
.catch(() => {
|
||||
// MongoDB is schemaless; a field that was never sampled is still valid.
|
||||
});
|
||||
}
|
||||
|
||||
function cancelMongoIndexDraft() {
|
||||
mongoIndexManagerMode.value = "view";
|
||||
mongoEditIndexOriginalName.value = "";
|
||||
mongoEditIndexOriginalSpec = undefined;
|
||||
resetMongoCreateIndexForm();
|
||||
}
|
||||
|
||||
/** The default _id index is never droppable, so the panel must not offer it. */
|
||||
const canDropSelectedMongoIndexRow = computed(() => {
|
||||
if (mongoIndexManagerMode.value === "create" || mongoIndexManagerMode.value === "edit") return false;
|
||||
const row = mongoIndexManagerSelected.value;
|
||||
return !!row && !row.isProtected;
|
||||
});
|
||||
|
||||
/** Editing requires a complete server specification so no unmodeled options are lost. */
|
||||
const canEditSelectedMongoIndexRow = computed(() => {
|
||||
if (mongoIndexManagerMode.value === "create" || mongoIndexManagerMode.value === "edit") return false;
|
||||
const row = mongoIndexManagerSelected.value;
|
||||
return !!row && !row.isProtected && row.propertiesComplete;
|
||||
});
|
||||
|
||||
/** Prefill the create form from the selected index row and enter edit mode. */
|
||||
function startEditMongoIndexDraft() {
|
||||
const node = sidebarFormTarget.value ?? activeNode.value;
|
||||
const row = mongoIndexManagerSelected.value;
|
||||
if (!canEditSelectedMongoIndexRow.value || !row || !node.connectionId || !node.database) return;
|
||||
const originalSpec = mongoIndexSpecsByName.get(row.name);
|
||||
if (!originalSpec) return;
|
||||
mongoCreateIndexForm.value = mongoCreateIndexFormFromRow(row);
|
||||
mongoEditIndexOriginalName.value = row.name;
|
||||
mongoEditIndexOriginalSpec = originalSpec;
|
||||
mongoIndexManagerMode.value = "edit";
|
||||
mongoIndexManagerError.value = "";
|
||||
const collection = mongoIndexPanelCollectionName(node);
|
||||
if (!collection) return;
|
||||
void connectionStore
|
||||
.listMongoCompletionFields(node.connectionId, node.database, collection)
|
||||
.then((fields) => {
|
||||
if (showMongoIndexManagerDialog.value) mongoCreateIndexFieldOptions.value = fields.map((field) => field.name);
|
||||
})
|
||||
.catch(() => {
|
||||
// MongoDB is schemaless; a field that was never sampled is still valid.
|
||||
});
|
||||
}
|
||||
|
||||
async function dropSelectedMongoIndexRow() {
|
||||
const node = sidebarFormTarget.value ?? activeNode.value;
|
||||
const connectionId = node.connectionId;
|
||||
const database = node.database;
|
||||
const collection = mongoIndexPanelCollectionName(node);
|
||||
const row = mongoIndexManagerSelected.value;
|
||||
if (!canDropSelectedMongoIndexRow.value || !row || !connectionId || !database || !collection) return;
|
||||
|
||||
await runMongoSidebarMutation({
|
||||
connection: connectionStore.getConfig(connectionId),
|
||||
database,
|
||||
reviewText: mongoDropIndexPreview(database, collection, row.name),
|
||||
source: t("production.sourceSidebar"),
|
||||
loading: mongoIndexManagerLoading,
|
||||
beforeExecute: () => connectionStore.ensureConnected(connectionId),
|
||||
execute: () => api.mongoDropIndexes(connectionId, database, collection, JSON.stringify(row.name), true),
|
||||
onSuccess: async (result) => {
|
||||
const failed = mongoDropIndexFailureCount(result);
|
||||
if (failed > 0) {
|
||||
toast(t("contextMenu.dropIndexesPartialFailure", { success: result.dropped_names.length, failed }), 5000);
|
||||
} else {
|
||||
toast(t("contextMenu.dropTableChildObjectSuccess", { name: row.name }), 3000);
|
||||
}
|
||||
mongoIndexManagerSelectedName.value = "";
|
||||
await refreshMongoIndexTreeAfterMutation({ ...node, tableName: collection });
|
||||
await loadMongoIndexManagerRows();
|
||||
},
|
||||
onError: (error) => {
|
||||
mongoIndexManagerError.value = translateBackendError(t, errorMessage(error));
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
function addMongoCreateIndexField() {
|
||||
if (!mongoCreateIndexCanAddField.value) return;
|
||||
const nextId = Math.max(0, ...mongoCreateIndexForm.value.fields.map((field) => field.id)) + 1;
|
||||
@@ -297,16 +480,34 @@ export function useSidebarDatabaseSpecificMutationRuntime(options: SidebarDataba
|
||||
mongoCreateIndexForm.value.fields = mongoCreateIndexForm.value.fields.filter((field) => field.id !== id);
|
||||
}
|
||||
|
||||
function mongoCreateIndexRequestErrorText(request: Extract<MongoCreateIndexRequest, { valid: false }>): string {
|
||||
switch (request.error) {
|
||||
case "field-duplicate":
|
||||
return t("mongo.duplicateField", { field: request.field });
|
||||
case "ttl-invalid":
|
||||
return t("contextMenu.createMongoIndexTtlInvalid");
|
||||
case "filter-invalid":
|
||||
return t("contextMenu.createMongoIndexFilterInvalid");
|
||||
case "bucket-size-invalid":
|
||||
return t("contextMenu.createMongoIndexBucketSizeInvalid");
|
||||
default:
|
||||
return t("contextMenu.createMongoIndexFieldRequired");
|
||||
}
|
||||
}
|
||||
|
||||
async function confirmCreateMongoIndex() {
|
||||
const node = sidebarFormTarget.value ?? activeNode.value;
|
||||
const connectionId = node.connectionId;
|
||||
const database = node.database;
|
||||
const collectionName = mongoIndexCollectionName(node);
|
||||
if (!canCreateMongoIndexNode(node) || !connectionId || !database || !collectionName) return;
|
||||
// When called from the manager panel the node may be a collection node;
|
||||
// when called from the standalone create dialog it is always a group-indexes node.
|
||||
const collectionName = showMongoIndexManagerDialog.value ? mongoIndexPanelCollectionName(node) : mongoIndexCollectionName(node);
|
||||
const canProceed = showMongoIndexManagerDialog.value ? canManageMongoIndexPanelNode(node) : canCreateMongoIndexNode(node);
|
||||
if (!canProceed || !connectionId || !database || !collectionName) return;
|
||||
|
||||
const request = buildMongoCreateIndexRequest(mongoCreateIndexForm.value);
|
||||
if (!request.valid) {
|
||||
mongoCreateIndexError.value = request.error === "field-duplicate" ? t("mongo.duplicateField", { field: request.field }) : t("contextMenu.createMongoIndexFieldRequired");
|
||||
mongoCreateIndexError.value = mongoCreateIndexRequestErrorText(request);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -322,6 +523,126 @@ export function useSidebarDatabaseSpecificMutationRuntime(options: SidebarDataba
|
||||
onSuccess: async (created) => {
|
||||
showCreateMongoIndexDialog.value = false;
|
||||
toast(t("contextMenu.createMongoIndexSuccess", { name: created.name, collection: collectionName }), 3000);
|
||||
// In the manager panel the dialog stays open: return the property pane to
|
||||
// read-only and reload the list so the new index shows up selected.
|
||||
if (showMongoIndexManagerDialog.value) {
|
||||
mongoIndexManagerMode.value = "view";
|
||||
mongoIndexManagerSelectedName.value = created.name;
|
||||
resetMongoCreateIndexForm();
|
||||
await loadMongoIndexManagerRows();
|
||||
}
|
||||
await refreshMongoIndexTreeAfterMutation({ ...node, tableName: collectionName });
|
||||
},
|
||||
onError: (error) => {
|
||||
mongoCreateIndexError.value = translateBackendError(t, errorMessage(error));
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Edit an existing index by drop + recreate. The form was prefilled by
|
||||
* {@link startEditMongoIndexDraft}; this runs the two backend calls in
|
||||
* sequence inside the production-gated mutation shell.
|
||||
*
|
||||
* Safety strategy:
|
||||
* 1. Merge `extraOptions` (collation, wildcardProjection, weights, …) back
|
||||
* into the create request so no server-reported option is silently lost.
|
||||
* 2. Re-read the current index spec from the server before any destructive
|
||||
* operation and compare it with the complete immutable opening snapshot.
|
||||
* 3. When the user renamed the index, create the new one first, then drop
|
||||
* the old one — if create fails the original index is untouched.
|
||||
* 4. When the name is unchanged (same-name rebuild), preserve a complete
|
||||
* rollback request and recreate the original index if the new build fails.
|
||||
*/
|
||||
async function confirmEditMongoIndex() {
|
||||
const node = sidebarFormTarget.value ?? activeNode.value;
|
||||
const connectionId = node.connectionId;
|
||||
const database = node.database;
|
||||
const collectionName = showMongoIndexManagerDialog.value ? mongoIndexPanelCollectionName(node) : mongoIndexCollectionName(node);
|
||||
const originalName = mongoEditIndexOriginalName.value;
|
||||
const originalSpec = mongoEditIndexOriginalSpec;
|
||||
if (!connectionId || !database || !collectionName || !originalName || !originalSpec || mongoIndexManagerMode.value !== "edit") return;
|
||||
|
||||
const request = buildMongoCreateIndexRequest(mongoCreateIndexForm.value);
|
||||
if (!request.valid) {
|
||||
mongoCreateIndexError.value = mongoCreateIndexRequestErrorText(request);
|
||||
return;
|
||||
}
|
||||
|
||||
// Preserve server-reported options the form does not model (collation,
|
||||
// wildcardProjection, weights, text defaults, geo options, …).
|
||||
const merged = mergeExtraOptionsIntoRequest(request, originalSpec.extraOptions);
|
||||
|
||||
const newName = mongoCreateIndexForm.value.name.trim();
|
||||
const isRename = newName && newName !== originalName;
|
||||
if (!isRename && !originalSpec.propertiesComplete) {
|
||||
mongoCreateIndexError.value = t("contextMenu.mongoEditIndexIncompleteSameName", { name: originalName });
|
||||
return;
|
||||
}
|
||||
|
||||
mongoCreateIndexError.value = "";
|
||||
await runMongoSidebarMutation({
|
||||
connection: connectionStore.getConfig(connectionId),
|
||||
database,
|
||||
// Review text shows both commands so production confirmation is explicit.
|
||||
reviewText: mongoReplaceIndexPreview(database, collectionName, originalName, merged.keysJson, merged.optionsJson),
|
||||
source: t("production.sourceSidebar"),
|
||||
loading: mongoCreateIndexLoading,
|
||||
beforeExecute: () => connectionStore.ensureConnected(connectionId),
|
||||
execute: async () => {
|
||||
// Re-read the current spec from the server to guard against concurrent
|
||||
// modifications between when the dialog was opened and when the user
|
||||
// confirmed the edit.
|
||||
const specs = await api.mongoListIndexSpecs(connectionId, database, collectionName);
|
||||
const preflight = preflightEditIndexSpec(specs, originalSpec);
|
||||
if (!preflight.safe) {
|
||||
throw new Error(preflight.reason === "not-found" ? t("contextMenu.mongoEditIndexNotFound", { name: originalName }) : t("contextMenu.mongoEditIndexStale", { name: originalName }));
|
||||
}
|
||||
|
||||
if (isRename) {
|
||||
// Safe rename: create the new index first. If create fails, the
|
||||
// original index is untouched and the error surfaces cleanly.
|
||||
const created = await api.mongoCreateIndex(connectionId, database, collectionName, merged.keysJson, merged.optionsJson);
|
||||
const dropResult = await api.mongoDropIndexes(connectionId, database, collectionName, JSON.stringify(originalName), true);
|
||||
if (mongoDropIndexFailureCount(dropResult) > 0) {
|
||||
const error = dropResult.failures?.map((failure) => `${failure.name}: ${failure.message}`).join("; ") || originalName;
|
||||
throw new Error(t("contextMenu.mongoEditIndexDropFailedAfterCreate", { oldName: originalName, newName: created.name, error }));
|
||||
}
|
||||
return created;
|
||||
}
|
||||
|
||||
const rollbackRequest = mongoCreateIndexRequestFromSpec(originalSpec);
|
||||
const dropResult = await api.mongoDropIndexes(connectionId, database, collectionName, JSON.stringify(originalName), true);
|
||||
if (mongoDropIndexFailureCount(dropResult) > 0) {
|
||||
const error = dropResult.failures?.map((failure) => `${failure.name}: ${failure.message}`).join("; ") || originalName;
|
||||
throw new Error(t("contextMenu.mongoEditIndexDropFailed", { name: originalName, error }));
|
||||
}
|
||||
try {
|
||||
return await api.mongoCreateIndex(connectionId, database, collectionName, merged.keysJson, merged.optionsJson);
|
||||
} catch (createError) {
|
||||
const createErrorMessage = errorMessage(createError);
|
||||
try {
|
||||
await api.mongoCreateIndex(connectionId, database, collectionName, rollbackRequest.keysJson, rollbackRequest.optionsJson);
|
||||
} catch (rollbackError) {
|
||||
throw new Error(
|
||||
t("contextMenu.mongoEditIndexCreateAndRollbackFailed", {
|
||||
name: originalName,
|
||||
createError: createErrorMessage,
|
||||
rollbackError: errorMessage(rollbackError),
|
||||
}),
|
||||
);
|
||||
}
|
||||
throw new Error(t("contextMenu.mongoEditIndexCreateFailedRolledBack", { name: originalName, error: createErrorMessage }));
|
||||
}
|
||||
},
|
||||
onSuccess: async (created) => {
|
||||
toast(t("contextMenu.mongoEditIndexSuccess", { oldName: originalName, newName: created.name, collection: collectionName }), 3000);
|
||||
mongoIndexManagerMode.value = "view";
|
||||
mongoEditIndexOriginalName.value = "";
|
||||
mongoEditIndexOriginalSpec = undefined;
|
||||
mongoIndexManagerSelectedName.value = created.name;
|
||||
resetMongoCreateIndexForm();
|
||||
await loadMongoIndexManagerRows();
|
||||
await refreshMongoIndexTreeAfterMutation({ ...node, tableName: collectionName });
|
||||
},
|
||||
onError: (error) => {
|
||||
@@ -640,6 +961,7 @@ export function useSidebarDatabaseSpecificMutationRuntime(options: SidebarDataba
|
||||
mongoDropAllIndexesPreview: mongoDropAllIndexesPreviewForNode,
|
||||
refreshMongoIndexTreeAfterMutation,
|
||||
canCreateMongoIndex,
|
||||
canManageMongoIndexes,
|
||||
mongoIndexKeyTypes: MONGO_INDEX_KEY_TYPES,
|
||||
mongoCreateIndexCanSubmit,
|
||||
mongoCreateIndexCanAddField,
|
||||
@@ -647,6 +969,18 @@ export function useSidebarDatabaseSpecificMutationRuntime(options: SidebarDataba
|
||||
addMongoCreateIndexField,
|
||||
removeMongoCreateIndexField,
|
||||
confirmCreateMongoIndex,
|
||||
prepareMongoIndexManagerDialog,
|
||||
loadMongoIndexManagerRows,
|
||||
mongoIndexManagerSelected,
|
||||
mongoIndexManagerCollectionName,
|
||||
selectMongoIndexRow,
|
||||
startCreateMongoIndexDraft,
|
||||
startEditMongoIndexDraft,
|
||||
cancelMongoIndexDraft,
|
||||
dropSelectedMongoIndexRow,
|
||||
canDropSelectedMongoIndexRow,
|
||||
canEditSelectedMongoIndexRow,
|
||||
confirmEditMongoIndex,
|
||||
openCreateNacosNamespaceDialog,
|
||||
confirmCreateNacosNamespace,
|
||||
openEditNacosNamespaceDialog,
|
||||
|
||||
Reference in new issue
Block a user