feat(mongodb): rename collections from sidebar
This commit is contained in:
1 parent
809500fd52
commit
9a83b46f00
26 files changed
+1105
-93
No files matched your search
@@ -458,6 +458,7 @@ export const vectorGetCollectionDetail = forward("vectorGetCollectionDetail");
|
||||
export const mongoCreateDatabase = forward("mongoCreateDatabase");
|
||||
export const mongoDropDatabase = forward("mongoDropDatabase");
|
||||
export const mongoDropCollection = forward("mongoDropCollection");
|
||||
export const mongoRenameCollection = forward("mongoRenameCollection");
|
||||
export const documentFindDocuments = forward("documentFindDocuments");
|
||||
export const mongoFindDocuments = forward("mongoFindDocuments");
|
||||
export const mongoParseShellCommand = forward("mongoParseShellCommand");
|
||||
|
||||
@@ -2080,6 +2080,10 @@ export async function mongoDropCollection(connectionId: string, database: string
|
||||
await post("/api/mongo/drop-collection", { connectionId, database, collection });
|
||||
}
|
||||
|
||||
export async function mongoRenameCollection(connectionId: string, database: string, collection: string, newName: string): Promise<void> {
|
||||
await post("/api/mongo/rename-collection", { connectionId, database, collection, newName });
|
||||
}
|
||||
|
||||
export async function elasticsearchListIndices(connectionId: string): Promise<string[]> {
|
||||
const collections = await documentListCollections(connectionId, "default");
|
||||
return collections.map((c) => c.name);
|
||||
|
||||
@@ -1872,6 +1872,10 @@ export async function mongoDropCollection(connectionId: string, database: string
|
||||
return invoke("mongo_drop_collection", { connectionId, database, collection });
|
||||
}
|
||||
|
||||
export async function mongoRenameCollection(connectionId: string, database: string, collection: string, newName: string): Promise<void> {
|
||||
return invoke("mongo_rename_collection", { connectionId, database, collection, newName });
|
||||
}
|
||||
|
||||
export async function elasticsearchListIndices(connectionId: string): Promise<string[]> {
|
||||
const collections = await documentListCollections(connectionId, "default");
|
||||
return collections.map((c) => c.name);
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { createPinia, setActivePinia } from "pinia";
|
||||
import { executeWithProductionSqlGuard } from "../productionExecutionGuard";
|
||||
import { executeWithProductionContextGuard, executeWithProductionSqlGuard } from "../productionExecutionGuard";
|
||||
import { useProductionSafetyStore } from "@/stores/productionSafetyStore";
|
||||
import type { ConnectionConfig } from "@/types/database";
|
||||
|
||||
@@ -117,3 +117,67 @@ describe("production SQL execution guard", () => {
|
||||
expect(execute).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe("production context execution guard (non-SQL)", () => {
|
||||
beforeEach(() => {
|
||||
setActivePinia(createPinia());
|
||||
});
|
||||
|
||||
it("waits for confirmation before executing production non-SQL mutations", async () => {
|
||||
const execute = vi.fn().mockResolvedValue("renamed");
|
||||
const reviewText = 'db.getSiblingDB("app").getCollection("users").renameCollection("accounts")';
|
||||
const pendingExecution = executeWithProductionContextGuard({
|
||||
connection: connection({ db_type: "mongodb", is_production: true }),
|
||||
database: "app",
|
||||
reviewText,
|
||||
source: "Object tree",
|
||||
execute,
|
||||
});
|
||||
|
||||
await Promise.resolve();
|
||||
const store = useProductionSafetyStore();
|
||||
expect(store.pending).toMatchObject({
|
||||
sql: reviewText,
|
||||
database: "app",
|
||||
source: "Object tree",
|
||||
});
|
||||
expect(execute).not.toHaveBeenCalled();
|
||||
|
||||
store.confirm();
|
||||
await expect(pendingExecution).resolves.toBe("renamed");
|
||||
expect(execute).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("cancels production non-SQL mutations without executing the callback", async () => {
|
||||
const execute = vi.fn().mockResolvedValue("renamed");
|
||||
const pendingExecution = executeWithProductionContextGuard({
|
||||
connection: connection({ db_type: "mongodb", production_databases: ["app"] }),
|
||||
database: "app",
|
||||
reviewText: 'db.getCollection("users").renameCollection("accounts")',
|
||||
source: "Object tree",
|
||||
execute,
|
||||
});
|
||||
|
||||
await Promise.resolve();
|
||||
useProductionSafetyStore().cancel();
|
||||
|
||||
await expect(pendingExecution).resolves.toBeUndefined();
|
||||
expect(execute).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("executes non-production non-SQL mutations immediately", async () => {
|
||||
const execute = vi.fn().mockResolvedValue("renamed");
|
||||
await expect(
|
||||
executeWithProductionContextGuard({
|
||||
connection: connection({ db_type: "mongodb" }),
|
||||
database: "scratch",
|
||||
reviewText: 'db.getCollection("users").renameCollection("accounts")',
|
||||
source: "Object tree",
|
||||
execute,
|
||||
}),
|
||||
).resolves.toBe("renamed");
|
||||
|
||||
expect(useProductionSafetyStore().pending).toBeUndefined();
|
||||
expect(execute).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
@@ -7,8 +7,12 @@ export function shouldIncludeDefaultDatabaseNode(connection: Pick<ConnectionConf
|
||||
return connection?.db_type === "mysql" && databases.some((database) => !database.name.trim());
|
||||
}
|
||||
|
||||
export function compareSidebarNames(left: string, right: string): number {
|
||||
return sidebarNameCollator.compare(left, right);
|
||||
}
|
||||
|
||||
export function sortSidebarNames(names: readonly string[]): string[] {
|
||||
return [...names].sort((left, right) => sidebarNameCollator.compare(left, right));
|
||||
return [...names].sort(compareSidebarNames);
|
||||
}
|
||||
|
||||
export function sortSidebarDatabases(databases: readonly DatabaseInfo[]): DatabaseInfo[] {
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { useProductionSafetyStore } from "@/stores/productionSafetyStore";
|
||||
import { assessProductionSql } from "@/lib/database/productionSafety";
|
||||
import { assessProductionSql, productionContextForDatabase } from "@/lib/database/productionSafety";
|
||||
import type { ConnectionConfig } from "@/types/database";
|
||||
|
||||
export interface ProductionSqlExecutionGuardOptions<T> {
|
||||
@@ -26,3 +26,31 @@ export async function executeWithProductionSqlGuard<T>(options: ProductionSqlExe
|
||||
}
|
||||
return options.execute();
|
||||
}
|
||||
|
||||
export interface ProductionContextExecutionGuardOptions<T> {
|
||||
connection?: ConnectionConfig;
|
||||
database?: string | null;
|
||||
/** Review text shown in the production confirmation dialog (SQL or shell preview). */
|
||||
reviewText: string;
|
||||
source?: string;
|
||||
execute: () => Promise<T>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gate non-SQL mutations (Mongo shell commands, structured editors, etc.) using
|
||||
* connection/database production scope rather than SQL risk classification.
|
||||
*/
|
||||
export async function executeWithProductionContextGuard<T>(options: ProductionContextExecutionGuardOptions<T>): Promise<T | undefined> {
|
||||
const productionContext = productionContextForDatabase(options.connection, options.database);
|
||||
if (productionContext.active) {
|
||||
const confirmed = await useProductionSafetyStore().requestConfirmation({
|
||||
sql: options.reviewText,
|
||||
connectionName: options.connection?.name,
|
||||
database: options.database ?? undefined,
|
||||
productionDatabases: productionContext.databases,
|
||||
source: options.source,
|
||||
});
|
||||
if (!confirmed) return undefined;
|
||||
}
|
||||
return options.execute();
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { isRenamableMongoCollection, mongoCollectionKindFromNode, mongoDropAllIndexesPreview, mongoDropCollectionPreview, mongoDropIndexPreview, mongoRenameCollectionPreview, toMongoCollectionKind } from "../mongoCollectionMutation";
|
||||
|
||||
describe("isRenamableMongoCollection", () => {
|
||||
it("allows ordinary collections and defaults", () => {
|
||||
expect(isRenamableMongoCollection("users")).toBe(true);
|
||||
expect(isRenamableMongoCollection("users", "collection")).toBe(true);
|
||||
});
|
||||
|
||||
it("rejects views, time-series collections, and system namespaces", () => {
|
||||
expect(isRenamableMongoCollection("users_view", "view")).toBe(false);
|
||||
expect(isRenamableMongoCollection("metrics", "timeseries")).toBe(false);
|
||||
expect(isRenamableMongoCollection("system.views", "collection")).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("mongoCollectionKindFromNode", () => {
|
||||
it("reads collectionKind from node meta without using SQL tableType", () => {
|
||||
expect(mongoCollectionKindFromNode({ meta: { collectionKind: "view" } })).toBe("view");
|
||||
expect(mongoCollectionKindFromNode({ meta: { collectionKind: "timeseries" } })).toBe("timeseries");
|
||||
expect(mongoCollectionKindFromNode({ meta: { collectionKind: "collection" } })).toBe("collection");
|
||||
expect(mongoCollectionKindFromNode({})).toBe("collection");
|
||||
});
|
||||
});
|
||||
|
||||
describe("toMongoCollectionKind", () => {
|
||||
it("normalizes wire kinds", () => {
|
||||
expect(toMongoCollectionKind("view")).toBe("view");
|
||||
expect(toMongoCollectionKind("timeseries")).toBe("timeseries");
|
||||
expect(toMongoCollectionKind("bucket")).toBe("collection");
|
||||
expect(toMongoCollectionKind(undefined)).toBe("collection");
|
||||
});
|
||||
});
|
||||
|
||||
describe("mongo shell previews", () => {
|
||||
it("preserves identifier whitespace in rename preview", () => {
|
||||
expect(mongoRenameCollectionPreview("app", " users ", " renamed ")).toBe('db.getSiblingDB("app").getCollection(" users ").renameCollection(" renamed ")');
|
||||
});
|
||||
|
||||
it("builds drop previews with database scope", () => {
|
||||
expect(mongoDropCollectionPreview("app", "users")).toBe('db.getSiblingDB("app").getCollection("users").drop()');
|
||||
expect(mongoDropIndexPreview("app", "users", "idx_name")).toBe('db.getSiblingDB("app").getCollection("users").dropIndex("idx_name")');
|
||||
expect(mongoDropAllIndexesPreview("app", "users")).toBe('db.getSiblingDB("app").getCollection("users").dropIndexes()');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,166 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { createPinia, setActivePinia } from "pinia";
|
||||
import { ref } from "vue";
|
||||
import { runMongoSidebarMutation } from "../runMongoSidebarMutation";
|
||||
import { useProductionSafetyStore } from "@/stores/productionSafetyStore";
|
||||
import type { ConnectionConfig } from "@/types/database";
|
||||
|
||||
function connection(overrides: Partial<ConnectionConfig> = {}): ConnectionConfig {
|
||||
return {
|
||||
id: "conn-1",
|
||||
name: "Mongo",
|
||||
db_type: "mongodb",
|
||||
host: "localhost",
|
||||
port: 27017,
|
||||
username: "op",
|
||||
password: "",
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
describe("runMongoSidebarMutation", () => {
|
||||
beforeEach(() => {
|
||||
setActivePinia(createPinia());
|
||||
});
|
||||
|
||||
it("calls onSuccess for void execute results (not treated as cancel)", async () => {
|
||||
const loading = ref(false);
|
||||
const execute = vi.fn().mockResolvedValue(undefined);
|
||||
const onSuccess = vi.fn();
|
||||
const beforeExecute = vi.fn().mockResolvedValue(undefined);
|
||||
|
||||
await runMongoSidebarMutation({
|
||||
connection: connection(),
|
||||
database: "app",
|
||||
reviewText: 'db.getCollection("users").renameCollection("accounts")',
|
||||
source: "Object tree",
|
||||
loading,
|
||||
beforeExecute,
|
||||
execute,
|
||||
onSuccess,
|
||||
});
|
||||
|
||||
expect(beforeExecute).toHaveBeenCalledTimes(1);
|
||||
expect(execute).toHaveBeenCalledTimes(1);
|
||||
expect(onSuccess).toHaveBeenCalledTimes(1);
|
||||
expect(onSuccess).toHaveBeenCalledWith(undefined);
|
||||
expect(loading.value).toBe(false);
|
||||
});
|
||||
|
||||
it("passes through non-void execute results to onSuccess", async () => {
|
||||
const loading = ref(false);
|
||||
const result = { dropped_names: ["a", "b"] };
|
||||
const onSuccess = vi.fn();
|
||||
|
||||
await runMongoSidebarMutation({
|
||||
connection: connection(),
|
||||
database: "app",
|
||||
reviewText: 'db.getCollection("users").dropIndexes()',
|
||||
source: "Object tree",
|
||||
loading,
|
||||
execute: async () => result,
|
||||
onSuccess,
|
||||
});
|
||||
|
||||
expect(onSuccess).toHaveBeenCalledWith(result);
|
||||
});
|
||||
|
||||
it("does not execute or call onSuccess when production confirmation is cancelled", async () => {
|
||||
const loading = ref(false);
|
||||
const execute = vi.fn().mockResolvedValue(undefined);
|
||||
const onSuccess = vi.fn();
|
||||
const beforeExecute = vi.fn();
|
||||
|
||||
const pending = runMongoSidebarMutation({
|
||||
connection: connection({ is_production: true }),
|
||||
database: "app",
|
||||
reviewText: 'db.getCollection("users").drop()',
|
||||
source: "Object tree",
|
||||
loading,
|
||||
beforeExecute,
|
||||
execute,
|
||||
onSuccess,
|
||||
});
|
||||
|
||||
await Promise.resolve();
|
||||
expect(useProductionSafetyStore().pending).toBeTruthy();
|
||||
expect(loading.value).toBe(false);
|
||||
expect(execute).not.toHaveBeenCalled();
|
||||
|
||||
useProductionSafetyStore().cancel();
|
||||
await pending;
|
||||
|
||||
expect(beforeExecute).not.toHaveBeenCalled();
|
||||
expect(execute).not.toHaveBeenCalled();
|
||||
expect(onSuccess).not.toHaveBeenCalled();
|
||||
expect(loading.value).toBe(false);
|
||||
});
|
||||
|
||||
it("executes after production confirmation", async () => {
|
||||
const loading = ref(false);
|
||||
const execute = vi.fn().mockResolvedValue(undefined);
|
||||
const onSuccess = vi.fn();
|
||||
|
||||
const pending = runMongoSidebarMutation({
|
||||
connection: connection({ is_production: true }),
|
||||
database: "app",
|
||||
reviewText: 'db.getCollection("users").drop()',
|
||||
source: "Object tree",
|
||||
loading,
|
||||
execute,
|
||||
onSuccess,
|
||||
});
|
||||
|
||||
await Promise.resolve();
|
||||
useProductionSafetyStore().confirm();
|
||||
await pending;
|
||||
|
||||
expect(execute).toHaveBeenCalledTimes(1);
|
||||
expect(onSuccess).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("routes existing-target reject to onError without onSuccess", async () => {
|
||||
// Mongo rename of an existing target fails at the server (no dropTarget).
|
||||
const loading = ref(false);
|
||||
const onError = vi.fn();
|
||||
const onSuccess = vi.fn();
|
||||
const existingTargetError = new Error("Command failed: Namespace app.accounts already exists. target namespace exists");
|
||||
|
||||
await runMongoSidebarMutation({
|
||||
connection: connection(),
|
||||
database: "app",
|
||||
reviewText: 'db.getSiblingDB("app").getCollection("users").renameCollection("accounts")',
|
||||
source: "Object tree",
|
||||
loading,
|
||||
execute: async () => {
|
||||
throw existingTargetError;
|
||||
},
|
||||
onSuccess,
|
||||
onError,
|
||||
});
|
||||
|
||||
expect(onSuccess).not.toHaveBeenCalled();
|
||||
expect(onError).toHaveBeenCalledTimes(1);
|
||||
expect(onError.mock.calls[0]?.[0]).toBe(existingTargetError);
|
||||
expect(loading.value).toBe(false);
|
||||
});
|
||||
|
||||
it("skips work when already loading", async () => {
|
||||
const loading = ref(true);
|
||||
const execute = vi.fn();
|
||||
const onSuccess = vi.fn();
|
||||
|
||||
await runMongoSidebarMutation({
|
||||
connection: connection(),
|
||||
database: "app",
|
||||
reviewText: "drop",
|
||||
source: "Object tree",
|
||||
loading,
|
||||
execute,
|
||||
onSuccess,
|
||||
});
|
||||
|
||||
expect(execute).not.toHaveBeenCalled();
|
||||
expect(onSuccess).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,45 @@
|
||||
import type { MongoCollectionKind, TreeNode } from "@/types/database";
|
||||
|
||||
/**
|
||||
* MongoDB only supports renameCollection for ordinary, non-system collections.
|
||||
* Views, time-series collections, and reserved system namespaces must not expose a rename action.
|
||||
* @see https://www.mongodb.com/docs/manual/reference/command/renameCollection/
|
||||
*/
|
||||
export function isRenamableMongoCollection(name: string, kind: MongoCollectionKind = "collection"): boolean {
|
||||
return kind === "collection" && !name.startsWith("system.");
|
||||
}
|
||||
|
||||
export function mongoCollectionKindFromNode(node: Pick<TreeNode, "meta">): MongoCollectionKind {
|
||||
const meta = node.meta;
|
||||
if (meta && "collectionKind" in meta && meta.collectionKind) {
|
||||
return meta.collectionKind;
|
||||
}
|
||||
return "collection";
|
||||
}
|
||||
|
||||
export function toMongoCollectionKind(kind?: string | null): MongoCollectionKind {
|
||||
const normalized = (kind || "collection").toLowerCase();
|
||||
if (normalized === "view") return "view";
|
||||
if (normalized === "timeseries") return "timeseries";
|
||||
return "collection";
|
||||
}
|
||||
|
||||
export function mongoRenameCollectionPreview(database: string, oldName: string, newName: string): string {
|
||||
return `db.getSiblingDB(${JSON.stringify(database)}).getCollection(${JSON.stringify(oldName)}).renameCollection(${JSON.stringify(newName)})`;
|
||||
}
|
||||
|
||||
export function mongoDropCollectionPreview(database: string, collection: string): string {
|
||||
return `db.getSiblingDB(${JSON.stringify(database)}).getCollection(${JSON.stringify(collection)}).drop()`;
|
||||
}
|
||||
|
||||
export function mongoDropDatabasePreview(database: string): string {
|
||||
return `db.getSiblingDB(${JSON.stringify(database)}).dropDatabase()`;
|
||||
}
|
||||
|
||||
export function mongoDropIndexPreview(database: string, collection: string, indexName: string): string {
|
||||
return `db.getSiblingDB(${JSON.stringify(database)}).getCollection(${JSON.stringify(collection)}).dropIndex(${JSON.stringify(indexName)})`;
|
||||
}
|
||||
|
||||
export function mongoDropAllIndexesPreview(database: string, collection: string): string {
|
||||
return `db.getSiblingDB(${JSON.stringify(database)}).getCollection(${JSON.stringify(collection)}).dropIndexes()`;
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
import type { Ref } from "vue";
|
||||
import type { ConnectionConfig } from "@/types/database";
|
||||
import { executeWithProductionContextGuard } from "@/lib/database/productionExecutionGuard";
|
||||
|
||||
export type RunMongoSidebarMutationOptions<T> = {
|
||||
connection?: ConnectionConfig;
|
||||
database: string;
|
||||
reviewText: string;
|
||||
source: string;
|
||||
loading: Ref<boolean>;
|
||||
/** Runs after production confirmation and after loading is set (e.g. ensureConnected). */
|
||||
beforeExecute?: () => Promise<void>;
|
||||
execute: () => Promise<T>;
|
||||
onSuccess: (result: T) => void;
|
||||
onError?: (error: unknown) => void;
|
||||
};
|
||||
|
||||
/**
|
||||
* Shared production-gated mutation shell for Mongo sidebar writes.
|
||||
* Production confirmation runs before loading so cancel never shows a busy state.
|
||||
*
|
||||
* Success is boxed as `{ result }` so void executes are not confused with cancel
|
||||
* (`executeWithProductionContextGuard` returns `undefined` only when cancelled).
|
||||
*/
|
||||
export async function runMongoSidebarMutation<T>(options: RunMongoSidebarMutationOptions<T>): Promise<void> {
|
||||
if (options.loading.value) return;
|
||||
try {
|
||||
const executed = await executeWithProductionContextGuard({
|
||||
connection: options.connection,
|
||||
database: options.database,
|
||||
reviewText: options.reviewText,
|
||||
source: options.source,
|
||||
execute: async () => {
|
||||
options.loading.value = true;
|
||||
if (options.beforeExecute) {
|
||||
await options.beforeExecute();
|
||||
}
|
||||
const result = await options.execute();
|
||||
return { result };
|
||||
},
|
||||
});
|
||||
// Cancel only: guard returns undefined when the user declines production confirmation.
|
||||
if (executed === undefined) return;
|
||||
options.onSuccess(executed.result);
|
||||
} catch (error: unknown) {
|
||||
options.onError?.(error);
|
||||
} finally {
|
||||
options.loading.value = false;
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user