feat(solr): add Apache Solr connection support
This commit is contained in:
1 parent
7b407ccbfc
commit
3687a9cbfb
75 files changed
+5596
-82
No files matched your search
+103
@@ -0,0 +1,103 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { buildAiContext, buildSystemPrompt, type AiContext } from "@/lib/ai/ai";
|
||||
import type { ConnectionConfig, QueryTab } from "@/types/database";
|
||||
|
||||
const apiMock = vi.hoisted(() => ({
|
||||
listTables: vi.fn(),
|
||||
getColumns: vi.fn(),
|
||||
listIndexes: vi.fn(),
|
||||
listForeignKeys: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("@/lib/backend/api", () => apiMock);
|
||||
|
||||
function solrConnection(): ConnectionConfig {
|
||||
return {
|
||||
id: "solr-1",
|
||||
name: "Solr",
|
||||
db_type: "solr",
|
||||
host: "127.0.0.1",
|
||||
port: 8983,
|
||||
username: "",
|
||||
password: "",
|
||||
};
|
||||
}
|
||||
|
||||
function queryTab(): QueryTab {
|
||||
return {
|
||||
id: "tab-1",
|
||||
title: "Query",
|
||||
connectionId: "solr-1",
|
||||
database: "default",
|
||||
sql: "GET /products/select?q=*:*",
|
||||
isExecuting: false,
|
||||
isCancelling: false,
|
||||
isExplaining: false,
|
||||
mode: "query",
|
||||
};
|
||||
}
|
||||
|
||||
function solrAiContext(): AiContext {
|
||||
return {
|
||||
connectionId: "solr-1",
|
||||
connectionName: "Solr",
|
||||
databaseType: "solr",
|
||||
database: "default",
|
||||
currentSql: "GET /products/select?q=*:*",
|
||||
tables: [
|
||||
{
|
||||
name: "products",
|
||||
tableType: "CORE",
|
||||
columns: [
|
||||
{ name: "id", data_type: "string", is_primary_key: true, is_nullable: false, column_default: null, extra: null },
|
||||
{ name: "title", data_type: "text_general", is_primary_key: false, is_nullable: true, column_default: null, extra: null },
|
||||
],
|
||||
},
|
||||
],
|
||||
sqlFiles: [],
|
||||
csvFiles: [],
|
||||
schemaScope: "database",
|
||||
truncated: false,
|
||||
};
|
||||
}
|
||||
|
||||
describe("Solr AI context", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
apiMock.listTables.mockResolvedValue([{ name: "products", table_type: "CORE" }]);
|
||||
apiMock.getColumns.mockResolvedValue([]);
|
||||
apiMock.listIndexes.mockResolvedValue([]);
|
||||
apiMock.listForeignKeys.mockResolvedValue([]);
|
||||
});
|
||||
|
||||
it("loads Solr cores as schema tables through the generic metadata path", async () => {
|
||||
const context = await buildAiContext(queryTab(), solrConnection());
|
||||
|
||||
expect(context.databaseType).toBe("solr");
|
||||
expect(apiMock.listTables).toHaveBeenCalledWith("solr-1", "default", "default");
|
||||
expect(apiMock.getColumns).toHaveBeenCalledWith("solr-1", "default", "default", "products");
|
||||
expect(context.tables.map((table) => table.name)).toEqual(["products"]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("Solr AI system prompt", () => {
|
||||
it("describes the REST-console request format instead of SQL", () => {
|
||||
const prompt = buildSystemPrompt("generate", solrAiContext(), "ask");
|
||||
|
||||
expect(prompt).toContain("Apache Solr");
|
||||
expect(prompt).toContain("METHOD /path");
|
||||
expect(prompt).toContain("Solr");
|
||||
// The prompt must not instruct the model to emit SQL for Solr.
|
||||
expect(prompt).not.toContain("adapt SQL to the active database dialect");
|
||||
expect(prompt).not.toContain("Generate SQL and explanations only");
|
||||
});
|
||||
|
||||
it("frames agent-mode tools with core semantics", () => {
|
||||
const prompt = buildSystemPrompt("query", solrAiContext(), "agent");
|
||||
|
||||
expect(prompt).toContain("list_tables");
|
||||
expect(prompt).toContain("execute_query");
|
||||
expect(prompt).toContain("METHOD /path");
|
||||
expect(prompt).toContain("core");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,23 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { documentStoreProviderFor } from "@/lib/app/documentStoreProvider";
|
||||
|
||||
describe("Solr document store provider", () => {
|
||||
it("uses the Solr document provider", () => {
|
||||
const provider = documentStoreProviderFor("solr");
|
||||
|
||||
expect(provider.kind).toBe("solr");
|
||||
const preview = provider.queryPreview({
|
||||
collection: "mycore",
|
||||
filterJson: '{"status":"paid"}',
|
||||
sortJson: '{"id":1}',
|
||||
skip: 0,
|
||||
limit: 100,
|
||||
});
|
||||
expect(preview).toContain("DBX SOLR QUERY DOCUMENTS");
|
||||
expect(preview).toContain('core: "mycore"');
|
||||
expect(preview).toContain("offset: 0");
|
||||
expect(preview).toContain("limit: 100");
|
||||
expect(preview).not.toContain("/_search");
|
||||
expect(preview).not.toContain("_routing");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,80 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { applyParsedConnectionUrl, connectionProfileForScheme, parseConnectionUrl } from "@/lib/connection/connectionUrl";
|
||||
import type { ConnectionConfig } from "@/types/database";
|
||||
|
||||
describe("Solr connection URLs", () => {
|
||||
it("rejects an empty host URL", () => {
|
||||
expect(() => parseConnectionUrl("", "solr")).toThrow("Connection URL is empty");
|
||||
});
|
||||
|
||||
it("parses the dedicated scheme with the default port and credentials", () => {
|
||||
expect(parseConnectionUrl("solr://solr:SolrRocks@search.example.com")).toMatchObject({
|
||||
dbType: "solr",
|
||||
driverProfile: "solr",
|
||||
driverLabel: "Apache Solr",
|
||||
host: "search.example.com",
|
||||
port: 8983,
|
||||
username: "solr",
|
||||
password: "SolrRocks",
|
||||
database: undefined,
|
||||
ssl: false,
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps Solr selected for HTTP/HTTPS URLs", () => {
|
||||
expect(parseConnectionUrl("http://search.example.com:8984", "solr")).toMatchObject({
|
||||
dbType: "solr",
|
||||
host: "search.example.com",
|
||||
port: 8984,
|
||||
ssl: false,
|
||||
});
|
||||
expect(parseConnectionUrl("https://search.example.com?insecure=true", "solr")).toMatchObject({
|
||||
dbType: "solr",
|
||||
host: "search.example.com",
|
||||
port: 8983,
|
||||
urlParams: "insecure=true",
|
||||
ssl: true,
|
||||
});
|
||||
});
|
||||
|
||||
it("does not treat the /solr context path as a database", () => {
|
||||
// The driver appends /solr itself; storing it as the database would make the
|
||||
// parsed value look like a selectable namespace that does not exist.
|
||||
for (const url of ["solr://search.example.com/solr", "http://search.example.com:8983/solr", "https://search.example.com/solr/"]) {
|
||||
expect(parseConnectionUrl(url, "solr")).toMatchObject({
|
||||
dbType: "solr",
|
||||
database: undefined,
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
it("does not resurrect a database through applyParsedConnectionUrl", () => {
|
||||
const parsed = parseConnectionUrl("solr://search.example.com/solr", "solr");
|
||||
const config = applyParsedConnectionUrl(
|
||||
{
|
||||
db_type: "solr",
|
||||
driver_profile: "solr",
|
||||
driver_label: "Apache Solr",
|
||||
host: "localhost",
|
||||
port: 8983,
|
||||
username: "",
|
||||
password: "",
|
||||
database: "stale-core",
|
||||
url_params: "",
|
||||
ssl: false,
|
||||
} as Omit<ConnectionConfig, "id">,
|
||||
parsed,
|
||||
);
|
||||
|
||||
expect(config.database).toBeUndefined();
|
||||
});
|
||||
|
||||
it("exposes the Solr scheme profile", () => {
|
||||
expect(connectionProfileForScheme("solr")).toEqual({
|
||||
type: "solr",
|
||||
profile: "solr",
|
||||
label: "Apache Solr",
|
||||
defaultPort: 8983,
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -28,7 +28,7 @@ describe("Cloud Spanner connection dialog", () => {
|
||||
// database that opts out of one of them means updating the string here too.
|
||||
expect(dialogSource).toContain("<div v-if=\"form.db_type !== 'meilisearch' && form.db_type !== 'spanner'\" class=\"grid grid-cols-4 items-center gap-4\">");
|
||||
expect(dialogSource).toContain('<div v-if="form.db_type !== \'spanner\'" class="grid grid-cols-4 items-center gap-4">');
|
||||
expect(dialogSource).toContain("<div v-if=\"form.db_type !== 'hbase' && form.db_type !== 'meilisearch' && form.db_type !== 'spanner'\" class=\"grid grid-cols-4 items-center gap-4\">");
|
||||
expect(dialogSource).toContain("<div v-if=\"form.db_type !== 'hbase' && form.db_type !== 'meilisearch' && form.db_type !== 'solr' && form.db_type !== 'spanner'\" class=\"grid grid-cols-4 items-center gap-4\">");
|
||||
// Switching to the Spanner profile clears host and credentials.
|
||||
expect(dialogSource).toContain('if (profile.type === "spanner") {');
|
||||
// Save/Test gating and submit-time normalization.
|
||||
|
||||
@@ -0,0 +1,83 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { classifySqlRisk, classifySqlStatementRisk } from "@/lib/sql/sqlRisk";
|
||||
import { sqlLooksLikeMutation } from "@/lib/database/readOnlyWriteAccess";
|
||||
|
||||
const SEARCH_REQUEST = 'POST /solr/mycore/select\n{\n "query": "*:*",\n "limit": 100\n}';
|
||||
|
||||
describe("Solr request risk", () => {
|
||||
it("treats queries and other retrieval requests as reads", () => {
|
||||
expect(classifySqlRisk(SEARCH_REQUEST, { dialect: "solr" }).risk).toBe("read");
|
||||
expect(classifySqlRisk("GET /solr/mycore/select?q=*:*", { dialect: "solr" }).risk).toBe("read");
|
||||
expect(classifySqlRisk("GET /solr/admin/cores?action=STATUS", { dialect: "solr" }).risk).toBe("read");
|
||||
expect(classifySqlRisk("HEAD /solr/mycore/admin/ping", { dialect: "solr" }).risk).toBe("read");
|
||||
expect(classifySqlRisk('POST /solr/mycore/query\n{"query":"*:*"}', { dialect: "solr" }).risk).toBe("read");
|
||||
expect(classifySqlRisk('POST /mycore/suggest\n{"suggest":{"q":"sol"}}', { dialect: "solr" }).risk).toBe("read");
|
||||
});
|
||||
|
||||
it("treats document updates as writes and admin/schema changes as dangerous", () => {
|
||||
expect(classifySqlRisk('POST /solr/mycore/update\n{"add":{"doc":{"id":"1"}}}', { dialect: "solr" }).risk).toBe("write");
|
||||
expect(classifySqlRisk('POST /mycore/update/json/docs\n{"a":1}', { dialect: "solr" }).risk).toBe("write");
|
||||
expect(classifySqlRisk('POST /solr/mycore/update?commit=true\n{"delete":{"query":"*:*"}}', { dialect: "solr" }).risk).toBe("write");
|
||||
expect(classifySqlRisk("POST /solr/admin/cores?action=CREATE&name=x", { dialect: "solr" }).risk).toBe("ddl");
|
||||
expect(classifySqlRisk('POST /solr/mycore/schema\n{"add-field":{"name":"f","type":"string"}}', { dialect: "solr" }).risk).toBe("ddl");
|
||||
expect(classifySqlRisk("DELETE /solr/mycore/update", { dialect: "solr" }).risk).toBe("write");
|
||||
expect(classifySqlRisk("DELETE /solr/mycore/config", { dialect: "solr" }).risk).toBe("ddl");
|
||||
});
|
||||
|
||||
it("treats GET-driven update and admin actions as mutations", () => {
|
||||
// Solr update handlers answer GET (commit/optimize/stream.body) and
|
||||
// CoreAdmin actions ride on GET as well, so the method alone cannot mark
|
||||
// these paths read-only.
|
||||
expect(classifySqlRisk("GET /solr/mycore/update?commit=true", { dialect: "solr" }).risk).toBe("write");
|
||||
expect(classifySqlRisk("GET /solr/admin/cores?action=CREATE&name=x", { dialect: "solr" }).risk).toBe("ddl");
|
||||
expect(classifySqlRisk("GET /solr/admin/cores?action=UNLOAD&core=mycore", { dialect: "solr" }).risk).toBe("ddl");
|
||||
expect(classifySqlRisk("GET /solr/admin/cores?action=REQUESTSTATUS&requestid=1", { dialect: "solr" }).risk).toBe("read");
|
||||
expect(classifySqlRisk("GET /solr/admin/info/system", { dialect: "solr" }).risk).toBe("read");
|
||||
});
|
||||
|
||||
it("treats GET replication commands outside the read whitelist as dangerous", () => {
|
||||
expect(classifySqlRisk("GET /solr/mycore/replication?command=details", { dialect: "solr" }).risk).toBe("read");
|
||||
expect(classifySqlRisk("GET /solr/mycore/replication?command=restorestatus", { dialect: "solr" }).risk).toBe("read");
|
||||
expect(classifySqlRisk("GET /solr/mycore/replication?command=filelist", { dialect: "solr" }).risk).toBe("read");
|
||||
expect(classifySqlRisk("GET /solr/mycore/replication", { dialect: "solr" }).risk).toBe("read");
|
||||
expect(classifySqlRisk("GET /solr/mycore/replication?command=disablereplication", { dialect: "solr" }).risk).toBe("ddl");
|
||||
expect(classifySqlRisk("GET /solr/mycore/replication?command=enablereplication", { dialect: "solr" }).risk).toBe("ddl");
|
||||
expect(classifySqlRisk("GET /solr/mycore/replication?command=fetchindex", { dialect: "solr" }).risk).toBe("ddl");
|
||||
});
|
||||
|
||||
it("reports the highest risk across every request in the editor text", () => {
|
||||
const source = `${SEARCH_REQUEST}\n\nPOST /solr/admin/cores?action=UNLOAD&core=mycore`;
|
||||
expect(classifySqlRisk(source, { dialect: "solr" }).risk).toBe("ddl");
|
||||
expect(classifySqlStatementRisk(SEARCH_REQUEST, { dialect: "solr" }).risk).toBe("read");
|
||||
});
|
||||
|
||||
it("reads the request line through query strings, trailing slashes and CRLF endings", () => {
|
||||
expect(classifySqlRisk("GET /solr/mycore/select?q=*:*&rows=1", { dialect: "solr" }).risk).toBe("read");
|
||||
expect(classifySqlRisk("post /solr/mycore/select/\r\n{}", { dialect: "solr" }).risk).toBe("read");
|
||||
expect(classifySqlRisk('POST /solr/mycore/update?commitWithin=500\n{"delete":{"id":"1"}}', { dialect: "solr" }).risk).toBe("write");
|
||||
expect(classifySqlRisk(" GET /solr/mycore/select // inline comment", { dialect: "solr" }).risk).toBe("read");
|
||||
});
|
||||
|
||||
it("ignores commented-out requests", () => {
|
||||
expect(classifySqlRisk(`# DELETE /solr/mycore/config\n// DELETE /solr/mycore/config\n/* DELETE /solr/mycore/config */\n${SEARCH_REQUEST}`, { dialect: "solr" }).risk).toBe("read");
|
||||
expect(classifySqlRisk("/*\nDELETE /solr/mycore/config\n*/\nGET /solr/mycore/select", { dialect: "solr" }).risk).toBe("read");
|
||||
});
|
||||
|
||||
it("leaves text that does not start with a request line to the SQL rules", () => {
|
||||
// The backend anchors on the first line too, so a stray request line further
|
||||
// down must not turn unparseable text into a read.
|
||||
expect(classifySqlRisk('{"query":"*:*"}\nGET /solr/mycore/select', { dialect: "solr" }).risk).toBe("unknown");
|
||||
});
|
||||
|
||||
it("keeps REST requests classified as SQL for other database types", () => {
|
||||
expect(classifySqlRisk(SEARCH_REQUEST, { dialect: "mysql" }).risk).toBe("unknown");
|
||||
expect(classifySqlRisk(SEARCH_REQUEST, { dialect: "elasticsearch" }).risk).not.toBe("read");
|
||||
});
|
||||
|
||||
it("does not ask a read-only connection to unlock writes for a search", () => {
|
||||
expect(sqlLooksLikeMutation(SEARCH_REQUEST, "solr")).toBe(false);
|
||||
expect(sqlLooksLikeMutation("GET /solr/mycore/select?q=*:*", "solr")).toBe(false);
|
||||
expect(sqlLooksLikeMutation('POST /solr/mycore/update\n{"delete":{"query":"*:*"}}', "solr")).toBe(true);
|
||||
expect(sqlLooksLikeMutation("POST /solr/admin/cores?action=CREATE&name=x", "solr")).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -32,6 +32,7 @@ function dbLabel(dbType: DatabaseType): string {
|
||||
milvus: "Milvus",
|
||||
weaviate: "Weaviate",
|
||||
chromadb: "ChromaDB",
|
||||
solr: "Apache Solr",
|
||||
};
|
||||
return labels[dbType] || dbType;
|
||||
}
|
||||
@@ -318,6 +319,9 @@ export function buildSystemPrompt(action: AiAction, context: AiContext, mode: Ai
|
||||
if (context.databaseType === "redis") {
|
||||
return buildRedisSystemPrompt(context, mode, custom);
|
||||
}
|
||||
if (context.databaseType === "solr") {
|
||||
return buildSolrSystemPrompt(context, mode, custom);
|
||||
}
|
||||
const schema = formatSchema(context);
|
||||
const resultPreview = context.lastResultPreview ? `\nLast result preview:\n${context.lastResultPreview}\n` : "";
|
||||
const lastError = context.lastError ? `\nLast error:\n${context.lastError}\n` : "";
|
||||
@@ -397,6 +401,59 @@ function buildRedisSystemPrompt(context: AiContext, mode: AiAssistantMode, custo
|
||||
return lines.filter(Boolean).join("\n");
|
||||
}
|
||||
|
||||
/**
|
||||
* Solr prompt: Solr speaks REST, not SQL, so the generic dialect instructions
|
||||
* would push the model toward SELECT statements that the Solr driver rejects.
|
||||
* The query surface is the DBX REST console (`METHOD /path` + optional JSON
|
||||
* body); schema context entries are Solr cores whose "columns" are schema
|
||||
* fields (the PK-flagged field is the core's uniqueKey).
|
||||
*/
|
||||
function buildSolrSystemPrompt(context: AiContext, mode: AiAssistantMode, custom?: CustomPromptContext): string {
|
||||
const isZh = isChineseLocale(currentLocale());
|
||||
const schema = formatSchema(context);
|
||||
const resultPreview = context.lastResultPreview ? `\nLast result preview:\n${context.lastResultPreview}\n` : "";
|
||||
const lastError = context.lastError ? `\nLast error:\n${context.lastError}\n` : "";
|
||||
const referencedSqlFiles = formatReferencedSqlFiles(context);
|
||||
const lines: string[] = [
|
||||
isZh ? "你是 DBX 内置的 Apache Solr 助手。用中文回复。" : "You are DBX's built-in Apache Solr assistant. Reply in English.",
|
||||
isZh
|
||||
? 'Solr 不使用 SQL。查询一律使用 DBX REST 控制台格式:首行 `METHOD /path`,后续可选 JSON 请求体,例如 `GET /{core}/select?q=*:*&rows=20`、`POST /{core}/query` 加 {"query":"..."} JSON body。路径可以省略开头的 /solr 段,wt=json 会自动补上。'
|
||||
: 'Solr does not use SQL. Always express queries in the DBX REST-console format: `METHOD /path` on the first line plus an optional JSON body, e.g. `GET /{core}/select?q=*:*&rows=20` or `POST /{core}/query` with a body such as {"query":"..."}. A leading /solr path segment may be omitted and wt=json is appended automatically.',
|
||||
isZh
|
||||
? "Schema 上下文中每个条目是一个 Solr core(类型标注为 CORE);其下列出的是 schema fields,标记为 PK 的字段是该 core 的唯一键(uniqueKey)。用真实字段名构造 q/fq 参数,不要编造不存在的字段。"
|
||||
: "Each entry in the schema context is a Solr core (marked CORE); the listed items are its schema fields and the PK-flagged field is the core's uniqueKey. Build q/fq parameters from real field names and never invent fields that are not listed.",
|
||||
...buildModePromptLines(mode, isZh, context.databaseType),
|
||||
...buildRichContentPromptLines(isZh),
|
||||
...buildCustomInstructionLines(custom, isZh),
|
||||
attachmentSafetyInstruction(isZh),
|
||||
// The ```sql fence is only a transport convention: the editor treats the
|
||||
// block content as a Solr REST request, never as SQL.
|
||||
isZh ? "返回请求时放在 ```sql 代码块中,块内容是 Solr REST 请求文本而非 SQL。额外说明简短实用。" : "Put the request in a fenced ```sql code block; the block holds Solr REST request text, not SQL. Keep extra explanation short and practical.",
|
||||
"",
|
||||
"Database type: solr",
|
||||
`Connection: ${context.connectionName}`,
|
||||
`Database: ${context.database}`,
|
||||
context.schema ? `Selected schema: ${context.schema}` : "",
|
||||
schemaCoverageLine(context, isZh),
|
||||
"",
|
||||
`Current request:\n${context.currentSql.trim() || "(empty)"}`,
|
||||
referencedSqlFiles,
|
||||
lastError,
|
||||
resultPreview,
|
||||
`Schema:\n${schema}`,
|
||||
];
|
||||
|
||||
if (context.schemaScope === "focused_table") {
|
||||
lines.push(
|
||||
isZh
|
||||
? "Schema 上下文只覆盖当前打开的 core;连接中可能还有其他 core。用户询问有哪些 core 或提到上下文中不存在的 core 时,不要直接断言不存在,先用 list_tables 确认。"
|
||||
: "Schema context covers only the currently opened core; the connection may contain other cores. When the user asks what cores exist or mentions a core absent from context, do not conclude it is missing; use list_tables to verify first.",
|
||||
);
|
||||
}
|
||||
|
||||
return lines.filter(Boolean).join("\n");
|
||||
}
|
||||
|
||||
function buildBasePromptLines(isZh: boolean): string[] {
|
||||
return [
|
||||
isZh ? "你是 DBX 内置的数据库助手。用中文回复。" : "You are DBX's built-in database assistant. Reply in English.",
|
||||
@@ -554,6 +611,28 @@ function buildModePromptLines(mode: AiAssistantMode, isZh: boolean, databaseType
|
||||
currentTimeGuidance,
|
||||
];
|
||||
}
|
||||
if (databaseType === "solr") {
|
||||
if (mode === "agent") {
|
||||
return [
|
||||
isZh
|
||||
? "你处于 Solr Agent 模式。你有以下工具可用:list_tables(列出 Solr cores)、get_columns(返回某个 core 的 schema fields)、execute_query、get_current_time。"
|
||||
: "You are in Solr Agent mode. You have the following tools available: list_tables (lists Solr cores), get_columns (returns a core's schema fields), execute_query, get_current_time.",
|
||||
isZh
|
||||
? "execute_query 接受 DBX REST 控制台格式的 Solr 请求而不是 SQL:首行 `METHOD /path`,后续可选 JSON body,例如 `GET /{core}/select?q=*:*&rows=20` 或 `POST /{core}/query` 加 JSON body。用户提出数据查询意图时,必须调用该工具获取真实结果后再回答。"
|
||||
: "execute_query accepts Solr REST-console requests, not SQL: `METHOD /path` on the first line plus an optional JSON body, for example `GET /{core}/select?q=*:*&rows=20` or `POST /{core}/query` with a JSON body. For data queries, call the tool and answer from its actual results.",
|
||||
currentTimeGuidance,
|
||||
isZh
|
||||
? "禁止不经确认直接执行 Solr 写请求(`/{core}/update`、commit、schema/admin 变更);如果安全执行条件不满足,先说明原因,再给出只读替代方案。"
|
||||
: "Never execute Solr write requests (`/{core}/update`, commits, schema/admin changes) without confirmation. If safe execution requirements are not met, explain why and provide a read-only alternative.",
|
||||
];
|
||||
}
|
||||
return [
|
||||
isZh
|
||||
? "你处于 Solr Ask 模式。只生成 Solr REST 请求(`METHOD /path` + 可选 JSON body)和说明,不要生成 SQL,也不要暗示已经执行或即将自动执行。"
|
||||
: "You are in Solr Ask mode. Generate Solr REST requests (`METHOD /path` plus optional JSON body) and explanations only, not SQL, and do not imply that anything has run or will auto-run.",
|
||||
currentTimeGuidance,
|
||||
];
|
||||
}
|
||||
if (mode === "agent") {
|
||||
return [
|
||||
isZh ? "你处于 Agent 模式。你有以下工具可用:list_tables、get_columns、execute_query、get_sample_data、get_current_time。" : "You are in Agent mode. You have the following tools available: list_tables, get_columns, execute_query, get_sample_data, get_current_time.",
|
||||
|
||||
@@ -41,6 +41,9 @@ export function documentStoreValueForGrid(value: unknown, kind: DocumentStoreKin
|
||||
export function serializeDocumentStoreId(value: unknown, kind: DocumentStoreKind): string {
|
||||
if (kind !== "mongodb" && isLosslessJsonNumber(value)) return value.raw;
|
||||
if (kind === "elasticsearch") return String(value);
|
||||
// Solr document ids are the uniqueKey field value verbatim — no quoting or
|
||||
// sentinel encoding like Meilisearch's string-id marker.
|
||||
if (kind === "solr") return String(value);
|
||||
if (kind === "meilisearch") return typeof value === "string" ? `__dbx_meilisearch_string_id__${JSON.stringify(value)}` : String(value);
|
||||
if (kind === "dynamodb") return stringifyJsonPreservingLargeNumbers(value);
|
||||
return serializeMongoDocumentId(value);
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
import type { ComposerTranslation } from "vue-i18n";
|
||||
import { normalizeJsonArgument } from "@dbx-app/mongo-shell";
|
||||
import { isElasticsearchCompatibleDatabaseType, isMeilisearchDatabaseType, type DatabaseType } from "@/types/database";
|
||||
import { isElasticsearchCompatibleDatabaseType, isMeilisearchDatabaseType, isSolrDatabaseType, type DatabaseType } from "@/types/database";
|
||||
import { quoteUnquotedObjectKeys } from "@/lib/mongo/mongoShellCommand";
|
||||
import { formatMongoShellLiteral } from "@/lib/mongo/mongoDocumentValues";
|
||||
|
||||
export type DocumentStoreKind = "mongodb" | "dynamodb" | "elasticsearch" | "meilisearch";
|
||||
export type DocumentStoreKind = "mongodb" | "dynamodb" | "elasticsearch" | "meilisearch" | "solr";
|
||||
export type DocumentFilterMode = "equals" | "not-equals" | "like" | "not-like" | "begins-with" | "ends-with" | "greater-than" | "greater-than-or-equal" | "less-than" | "less-than-or-equal" | "in" | "not-in" | "between" | "not-between" | "is-null" | "is-not-null";
|
||||
export type DocumentFilterValueType = "auto" | "string" | "number" | "boolean" | "object-id" | "date" | "int32" | "int64" | "decimal128" | "json";
|
||||
export type ElasticsearchBoolClause = "filter" | "must" | "should" | "must_not";
|
||||
@@ -80,7 +80,9 @@ const MONGO_ONLY_DOCUMENT_FILTER_MODES = new Set<DocumentFilterMode>(["begins-wi
|
||||
|
||||
export function documentFilterModeOptionsFor(kind: DocumentStoreKind): Array<{ value: DocumentFilterMode; labelKey: string }> {
|
||||
if (kind === "meilisearch") return documentFilterModeOptions.filter((option) => option.value !== "like" && option.value !== "not-like" && !MONGO_ONLY_DOCUMENT_FILTER_MODES.has(option.value));
|
||||
if (kind === "mongodb") return documentFilterModeOptions;
|
||||
// Solr's driver translates every mode — including $in/$nin and range pairs —
|
||||
// into fq clauses, so the full Mongo-style operator set is available.
|
||||
if (kind === "mongodb" || kind === "solr") return documentFilterModeOptions;
|
||||
return documentFilterModeOptions.filter((option) => !MONGO_ONLY_DOCUMENT_FILTER_MODES.has(option.value));
|
||||
}
|
||||
|
||||
@@ -166,6 +168,22 @@ const meilisearchDocumentProvider: DocumentStoreProvider = {
|
||||
sortInputForColumn: mongoDocumentProvider.sortInputForColumn,
|
||||
};
|
||||
|
||||
const solrDocumentProvider: DocumentStoreProvider = {
|
||||
kind: "solr",
|
||||
filterInputLabel: "filter",
|
||||
sortInputLabel: "sort",
|
||||
documentsLabel: ({ total }) => `${total} Documents`,
|
||||
queryPreview: ({ collection, filterJson, sortJson, skip, limit }) => {
|
||||
const lines = ["DBX SOLR QUERY DOCUMENTS", `core: ${JSON.stringify(collection)}`, `offset: ${skip}`, `limit: ${limit}`];
|
||||
const filter = documentStorePreviewJson(filterJson);
|
||||
if (filter) lines.push("filter:", filter);
|
||||
const sort = documentStorePreviewJson(sortJson);
|
||||
if (sort) lines.push("sort:", sort);
|
||||
return lines.join("\n");
|
||||
},
|
||||
sortInputForColumn: mongoDocumentProvider.sortInputForColumn,
|
||||
};
|
||||
|
||||
const dynamodbDocumentProvider: DocumentStoreProvider = {
|
||||
kind: "dynamodb",
|
||||
filterInputLabel: "filter",
|
||||
@@ -197,6 +215,7 @@ export function documentStoreProviderFor(databaseType?: DatabaseType): DocumentS
|
||||
if (databaseType === "dynamodb") return dynamodbDocumentProvider;
|
||||
if (isElasticsearchCompatibleDatabaseType(databaseType)) return elasticsearchDocumentProvider;
|
||||
if (isMeilisearchDatabaseType(databaseType)) return meilisearchDocumentProvider;
|
||||
if (isSolrDatabaseType(databaseType)) return solrDocumentProvider;
|
||||
return mongoDocumentProvider;
|
||||
}
|
||||
|
||||
@@ -590,7 +609,10 @@ function escapeRegexLiteral(value: string): string {
|
||||
}
|
||||
|
||||
function mongoDocumentFilterKind(options: DocumentFilterParseOptions): boolean {
|
||||
return options.kind === undefined || options.kind === "mongodb";
|
||||
// Solr shares the Mongo-style filter document — the driver translates $in,
|
||||
// $gte/$lte and anchored $regex into fq clauses — so it uses the same
|
||||
// operator-rich condition shapes.
|
||||
return options.kind === undefined || options.kind === "mongodb" || options.kind === "solr";
|
||||
}
|
||||
|
||||
/** Splits a comma/newline separated filter value list, keeping quoted values intact. */
|
||||
@@ -824,6 +846,7 @@ const documentQueryInputNormalizers: Record<DocumentStoreKind, DocumentQueryInpu
|
||||
dynamodb: quoteUnquotedObjectKeys,
|
||||
elasticsearch: quoteUnquotedObjectKeys,
|
||||
meilisearch: quoteUnquotedObjectKeys,
|
||||
solr: quoteUnquotedObjectKeys,
|
||||
};
|
||||
|
||||
function normalizeDocumentQueryObjectInput(input: string, kind?: DocumentStoreKind): string {
|
||||
|
||||
@@ -14,6 +14,13 @@ export function formatMeilisearchDocumentOperationPreview(options: { action: "in
|
||||
return lines.join("\n");
|
||||
}
|
||||
|
||||
export function formatSolrDocumentOperationPreview(options: { action: "insert" | "upsert" | "update" | "delete"; core: string; id?: unknown; document?: Record<string, unknown> }): string {
|
||||
const lines = [`DBX SOLR ${options.action.toUpperCase()} DOCUMENT`, `core: ${JSON.stringify(options.core)}`];
|
||||
if (options.id !== undefined) lines.push(`id: ${stringifyDocumentStoreValue(options.id, "solr")}`);
|
||||
if (options.document) lines.push("document:", stringifyDocumentStoreValue(options.document, "solr", 2));
|
||||
return lines.join("\n");
|
||||
}
|
||||
|
||||
/**
|
||||
* Write a document body under a known identity.
|
||||
* - `put`: Elasticsearch index-by-id / Mongo update-by-id (identity via path, not body).
|
||||
|
||||
@@ -142,6 +142,7 @@ export function connectionDisplayUrlScheme(connection: Pick<ConnectionConfig, "d
|
||||
case "elasticsearch":
|
||||
case "easysearch":
|
||||
case "meilisearch":
|
||||
case "solr":
|
||||
case "qdrant":
|
||||
case "milvus":
|
||||
case "weaviate":
|
||||
@@ -233,6 +234,9 @@ export function connectionUrlPlaceholder(dbType: DatabaseType, driverProfile?: s
|
||||
case "meilisearch":
|
||||
return "http://host:port/base/path";
|
||||
|
||||
case "solr":
|
||||
return "http://user:password@host:8983";
|
||||
|
||||
case "dameng":
|
||||
return "dm://user:password@host:port";
|
||||
|
||||
|
||||
@@ -59,6 +59,7 @@ const SCHEME_PROFILES: Record<string, ConnectionProfile> = {
|
||||
elasticsearch: { type: "elasticsearch", profile: "elasticsearch", label: "Elasticsearch", defaultPort: 9200 },
|
||||
easysearch: { type: "easysearch", profile: "easysearch", label: "Easysearch", defaultPort: 9200 },
|
||||
meilisearch: { type: "meilisearch", profile: "meilisearch", label: "Meilisearch", defaultPort: 7700 },
|
||||
solr: { type: "solr", profile: "solr", label: "Apache Solr", defaultPort: 8983 },
|
||||
qdrant: { type: "qdrant", profile: "qdrant", label: "Qdrant", defaultPort: 6333 },
|
||||
milvus: { type: "milvus", profile: "milvus", label: "Milvus", defaultPort: 19530 },
|
||||
weaviate: { type: "weaviate", profile: "weaviate", label: "Weaviate", defaultPort: 8080 },
|
||||
@@ -97,6 +98,7 @@ const HTTP_SELECTED_PROFILES: Record<string, ConnectionProfile> = {
|
||||
elasticsearch: SCHEME_PROFILES.elasticsearch,
|
||||
easysearch: SCHEME_PROFILES.easysearch,
|
||||
meilisearch: SCHEME_PROFILES.meilisearch,
|
||||
solr: SCHEME_PROFILES.solr,
|
||||
qdrant: SCHEME_PROFILES.qdrant,
|
||||
milvus: SCHEME_PROFILES.milvus,
|
||||
weaviate: SCHEME_PROFILES.weaviate,
|
||||
@@ -795,7 +797,7 @@ export function parseConnectionUrl(value: string, preferredProfile?: string): Pa
|
||||
...(profile.type === "sqlserver" && parsed.port ? { portExplicit: true } : {}),
|
||||
username: jdbcCredentials?.username ?? decodeUrlPart(parsed.username),
|
||||
password: jdbcCredentials?.password ?? decodeUrlPart(parsed.password),
|
||||
database: profile.type === "victoriametrics" ? "metrics" : profile.type === "dynamodb" ? dynamodbRegionFromHost(parsed.hostname) : isMeilisearch ? undefined : pathDatabase,
|
||||
database: profile.type === "victoriametrics" ? "metrics" : profile.type === "dynamodb" ? dynamodbRegionFromHost(parsed.hostname) : isMeilisearch || profile.type === "solr" ? undefined : pathDatabase,
|
||||
urlParams: effectiveUrlParams,
|
||||
ssl: scheme === "rediss" || scheme === "https" || (redisPath?.tls ?? false) || urlParamsRequireTls(profile.type, effectiveUrlParams) || (profile.type === "mysql" && isTidbCloudHost(parsed.hostname)),
|
||||
...(profile.type === "victoriametrics" ? { apiPath: parsed.pathname.replace(/\/+$/, "") } : {}),
|
||||
|
||||
@@ -74,7 +74,7 @@ const STANDARD_URL_SCHEMES: Partial<Record<DatabaseType, string>> = {
|
||||
};
|
||||
|
||||
/** Schemes that are plain HTTP(S) endpoints. */
|
||||
const HTTP_URL_DB_TYPES = new Set<DatabaseType>(["elasticsearch", "easysearch", "meilisearch", "qdrant", "milvus", "weaviate", "chromadb", "rqlite", "consul", "victoriametrics", "influxdb", "influxdb3", "dynamodb"]);
|
||||
const HTTP_URL_DB_TYPES = new Set<DatabaseType>(["elasticsearch", "easysearch", "meilisearch", "solr", "qdrant", "milvus", "weaviate", "chromadb", "rqlite", "consul", "victoriametrics", "influxdb", "influxdb3", "dynamodb"]);
|
||||
|
||||
/**
|
||||
* Generic `prefix://host:port/db` JDBC dialects. Dialects with a different URL
|
||||
|
||||
@@ -5,7 +5,7 @@ const DRAFT_VISIBLE_DATABASES_PREFIX = "__visible_draft_";
|
||||
|
||||
// Turso and Cloudflare D1 target one fixed SQLite-compatible `main` namespace;
|
||||
// non-database services expose their own root objects rather than database namespaces.
|
||||
const UNSUPPORTED_VISIBLE_DATABASE_TYPES = new Set<DatabaseType>(["turso", "cloudflare-d1", "dynamodb", "elasticsearch", "easysearch", "meilisearch", "qdrant", "milvus", "weaviate", "chromadb", "etcd", "zookeeper", "mq", "nacos", "consul", "plugin"]);
|
||||
const UNSUPPORTED_VISIBLE_DATABASE_TYPES = new Set<DatabaseType>(["turso", "cloudflare-d1", "dynamodb", "elasticsearch", "easysearch", "meilisearch", "solr", "qdrant", "milvus", "weaviate", "chromadb", "etcd", "zookeeper", "mq", "nacos", "consul", "plugin"]);
|
||||
|
||||
type VisibleDatabaseConnectionFields = Pick<
|
||||
ConnectionConfig,
|
||||
|
||||
@@ -25,7 +25,7 @@ export function isColumnNameCopySeparator(value: unknown): value is ColumnNameCo
|
||||
}
|
||||
|
||||
// SQL 执行能力是产品能力,不代表数据库支持 SQL 标识符引用。
|
||||
const NON_SQL_DATABASE_TYPES = new Set<DatabaseType>(["redis", "mongodb", "elasticsearch", "easysearch", "meilisearch", "qdrant", "milvus", "weaviate", "chromadb", "etcd", "zookeeper", "consul", "mq", "nacos", "victoriametrics"]);
|
||||
const NON_SQL_DATABASE_TYPES = new Set<DatabaseType>(["redis", "mongodb", "elasticsearch", "easysearch", "meilisearch", "solr", "qdrant", "milvus", "weaviate", "chromadb", "etcd", "zookeeper", "consul", "mq", "nacos", "victoriametrics"]);
|
||||
// quoteTableIdentifier 对 jdbc/iotdb 原样返回(无引用字符可用)。
|
||||
const UNQUOTABLE_DATABASE_TYPES = new Set<DatabaseType>(["jdbc", "iotdb"]);
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { isElasticsearchCompatibleDatabaseType, type DatabaseType } from "@/types/database";
|
||||
import { isElasticsearchCompatibleDatabaseType, isSolrDatabaseType, type DatabaseType } from "@/types/database";
|
||||
|
||||
/**
|
||||
* Resolve the data type to display in a data-grid column header.
|
||||
@@ -207,6 +207,13 @@ const INTEGER_COLUMN_TYPE_BASES = new Set([
|
||||
// BYTE is binary), so they only apply to Elasticsearch-compatible databases.
|
||||
const ELASTICSEARCH_ONLY_INTEGER_COLUMN_TYPE_BASES = new Set(["byte", "short", "long"]);
|
||||
|
||||
// Solr schema field types: point/trie numerics and dates carry a `p`/`t`
|
||||
// prefix, and analyzed text fields are named `text_*` — none of those names
|
||||
// exist in the SQL type palette, so they resolve only under a Solr connection.
|
||||
const SOLR_INTEGER_COLUMN_TYPE_BASES = new Set(["pint", "plong", "tint", "tlong", "sint", "slong"]);
|
||||
const SOLR_NUMERIC_COLUMN_TYPE_BASES = new Set(["pfloat", "pdouble", "tfloat", "tdouble", "sfloat", "sdouble", "pcurrency", "currency"]);
|
||||
const SOLR_TEMPORAL_COLUMN_TYPE_BASES = new Set(["pdate", "tdate"]);
|
||||
|
||||
const STRING_COLUMN_TYPE_BASES = new Set([
|
||||
"varchar",
|
||||
"varchar2",
|
||||
@@ -300,8 +307,14 @@ export function resolveDataGridTypeVisualKind(dataType: string | undefined, data
|
||||
if (array) return "structured";
|
||||
if (databaseType === "sqlserver" && (base === "timestamp" || base === "rowversion")) return "binary";
|
||||
if (databaseType === "postgres" && (base === "bit" || base === "bit varying")) return "binary";
|
||||
if (isElasticsearchCompatibleDatabaseType(databaseType) && ELASTICSEARCH_ONLY_INTEGER_COLUMN_TYPE_BASES.has(base)) return "integer";
|
||||
if ((isElasticsearchCompatibleDatabaseType(databaseType) || isSolrDatabaseType(databaseType)) && ELASTICSEARCH_ONLY_INTEGER_COLUMN_TYPE_BASES.has(base)) return "integer";
|
||||
if (INTEGER_COLUMN_TYPE_BASES.has(base)) return "integer";
|
||||
if (isSolrDatabaseType(databaseType)) {
|
||||
if (SOLR_INTEGER_COLUMN_TYPE_BASES.has(base)) return "integer";
|
||||
if (SOLR_NUMERIC_COLUMN_TYPE_BASES.has(base)) return "numeric";
|
||||
if (SOLR_TEMPORAL_COLUMN_TYPE_BASES.has(base)) return "temporal";
|
||||
if (base.startsWith("text")) return "string";
|
||||
}
|
||||
if (isNumericColumnType(dataType)) return "numeric";
|
||||
if (BOOLEAN_COLUMN_TYPE_BASES.has(base)) return "boolean";
|
||||
if (TEMPORAL_COLUMN_TYPE_BASES.has(base) || base.startsWith("timestamp_")) return "temporal";
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import type { DatabaseType } from "@/types/database";
|
||||
|
||||
const NON_SQL_PREVIEW_DATABASE_TYPES: ReadonlySet<DatabaseType> = new Set<DatabaseType>(["mongodb", "elasticsearch", "easysearch", "meilisearch"]);
|
||||
const NON_SQL_PREVIEW_DATABASE_TYPES: ReadonlySet<DatabaseType> = new Set<DatabaseType>(["mongodb", "elasticsearch", "easysearch", "meilisearch", "solr"]);
|
||||
|
||||
export function dataGridPreviewLabelKey(databaseType?: DatabaseType): "toolbar.previewQuery" | "toolbar.previewSql" {
|
||||
return databaseType && NON_SQL_PREVIEW_DATABASE_TYPES.has(databaseType) ? "toolbar.previewQuery" : "toolbar.previewSql";
|
||||
|
||||
@@ -33,6 +33,7 @@ export const DATABASE_NAMESPACE_CREATION_MATRIX = {
|
||||
elasticsearch: { deferred: "index creation is not modeled as database creation" },
|
||||
easysearch: { deferred: "index creation is not modeled as database creation" },
|
||||
meilisearch: { deferred: "index creation is not modeled as database creation" },
|
||||
solr: { deferred: "core creation is not modeled as database creation" },
|
||||
hbase: { deferred: "namespace creation needs dedicated HBase namespace options" },
|
||||
qdrant: { deferred: "collection creation is separate from database creation" },
|
||||
milvus: { deferred: "collection/database lifecycle needs a dedicated vector workflow" },
|
||||
|
||||
@@ -33,6 +33,7 @@ export const DATABASE_PROPERTY_EDITING_MATRIX = {
|
||||
elasticsearch: { deferred: "index settings are not database properties" },
|
||||
easysearch: { deferred: "index settings are not database properties" },
|
||||
meilisearch: { deferred: "index settings are not database properties" },
|
||||
solr: { deferred: "core settings are not database properties" },
|
||||
hbase: { deferred: "namespace and table properties need a dedicated HBase workflow" },
|
||||
qdrant: { deferred: "collection settings are not database properties" },
|
||||
milvus: { deferred: "collection/database settings need a dedicated vector workflow" },
|
||||
|
||||
@@ -110,6 +110,7 @@ const SQL_EXECUTION_TARGET_REGISTRY: Partial<Record<DatabaseType, SqlExecutionTa
|
||||
elasticsearch: { scope: "connection" },
|
||||
easysearch: { scope: "connection" },
|
||||
meilisearch: { scope: "connection" },
|
||||
solr: { scope: "connection" },
|
||||
qdrant: { scope: "connection" },
|
||||
milvus: { scope: "connection" },
|
||||
weaviate: { scope: "connection" },
|
||||
|
||||
@@ -70,7 +70,7 @@ function decorationsForHints(hints: readonly InsertValueHint[]): DecorationSet {
|
||||
* keep this list in sync instead of re-inlining it at call sites.
|
||||
*/
|
||||
export function supportsInsertValueHints(databaseType: string | undefined | null): boolean {
|
||||
return databaseType !== "redis" && databaseType !== "mongodb" && databaseType !== "elasticsearch" && databaseType !== "easysearch" && databaseType !== "meilisearch" && databaseType !== "victoriametrics";
|
||||
return databaseType !== "redis" && databaseType !== "mongodb" && databaseType !== "elasticsearch" && databaseType !== "easysearch" && databaseType !== "meilisearch" && databaseType !== "solr" && databaseType !== "victoriametrics";
|
||||
}
|
||||
|
||||
export function buildInsertValueHintDecorations(hints: readonly InsertValueHint[]): DecorationSet {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { isElasticsearchCompatibleDatabaseType, type DatabaseType, type QueryResult } from "@/types/database";
|
||||
import { isElasticsearchCompatibleDatabaseType, isSolrDatabaseType, type DatabaseType, type QueryResult } from "@/types/database";
|
||||
import { stripLeadingElasticsearchComments } from "@/lib/sql/sqlStatementRanges";
|
||||
|
||||
export interface ElasticsearchJsonResponse {
|
||||
@@ -9,11 +9,12 @@ export interface ElasticsearchJsonResponse {
|
||||
const ELASTICSEARCH_REST_STATEMENT = /^(?:GET|POST|PUT|DELETE|HEAD)\s+\S+/i;
|
||||
|
||||
/**
|
||||
* Detect the raw HTTP result emitted for an Elasticsearch REST request.
|
||||
* DBX asks unformatted CAT requests for JSON so they use this response panel.
|
||||
* Detect the raw HTTP result emitted for a search-engine REST request.
|
||||
* Elasticsearch asks unformatted CAT requests for JSON; Solr REST passthrough
|
||||
* emits the same `status`/`response` shape, so both share this response panel.
|
||||
*/
|
||||
export function elasticsearchJsonResponseForResult(databaseType: DatabaseType | undefined, sourceStatement: string | undefined, result: QueryResult | undefined): ElasticsearchJsonResponse | undefined {
|
||||
if (!isElasticsearchCompatibleDatabaseType(databaseType) || !result || typeof sourceStatement !== "string") return undefined;
|
||||
if ((!isElasticsearchCompatibleDatabaseType(databaseType) && !isSolrDatabaseType(databaseType)) || !result || typeof sourceStatement !== "string") return undefined;
|
||||
if (!ELASTICSEARCH_REST_STATEMENT.test(stripLeadingElasticsearchComments(sourceStatement))) return undefined;
|
||||
if (result.columns.length !== 2 || result.columns[0] !== "status" || result.columns[1] !== "response" || result.rows.length !== 1) return undefined;
|
||||
|
||||
|
||||
@@ -71,7 +71,7 @@ function orderSidebarTreeChildrenForParent(parent: Pick<TreeNode, "type">, child
|
||||
const regularChildren = normalized.filter((child) => child.type !== "user-admin" && child.type !== "dameng-users" && child.type !== "dameng-roles" && child.type !== "saved-sql-root");
|
||||
const withConnectionUtilityOrder = (children: TreeNode[]) => [...savedSqlNodes, ...children, ...userAdminNodes];
|
||||
|
||||
if (databaseType === "mongodb" || databaseType === "elasticsearch" || databaseType === "easysearch" || databaseType === "meilisearch" || databaseType === "qdrant" || databaseType === "milvus" || databaseType === "weaviate" || databaseType === "chromadb") {
|
||||
if (databaseType === "mongodb" || databaseType === "elasticsearch" || databaseType === "easysearch" || databaseType === "meilisearch" || databaseType === "solr" || databaseType === "qdrant" || databaseType === "milvus" || databaseType === "weaviate" || databaseType === "chromadb") {
|
||||
const meilisearchSystem = regularChildren.filter((child) => child.type === "meilisearch-system");
|
||||
const databaseObjects = regularChildren.filter((child) => child.type !== "meilisearch-system");
|
||||
return withConnectionUtilityOrder([...sortByLabel(databaseObjects), ...meilisearchSystem]);
|
||||
|
||||
@@ -0,0 +1,572 @@
|
||||
import { executeQuery } from "@/lib/backend/api";
|
||||
import { parseJsonPreservingLargeNumbers } from "@/lib/common/safeJsonFormat";
|
||||
|
||||
/**
|
||||
* Solr Admin 面板的数据层:所有请求复用 REST 控制台链路
|
||||
* (execute_query → solr_driver::execute_rest_query),后端零新增命令。
|
||||
* 非表格化 JSON 响应由驱动包装为 [status, response] 单行返回;
|
||||
* /response/docs 形态走 elasticsearch_raw_body 透出原文。
|
||||
*/
|
||||
|
||||
export interface SolrAdminResponse {
|
||||
status: number;
|
||||
/** 解析后的 JSON;非 JSON 时为原始文本;空响应为 null。 */
|
||||
body: unknown;
|
||||
rawBody: string;
|
||||
elapsedMs: number;
|
||||
}
|
||||
|
||||
export type SolrAdminMethod = "GET" | "POST" | "PUT" | "DELETE" | "HEAD";
|
||||
|
||||
export async function solrAdminRequest(connectionId: string, method: SolrAdminMethod, path: string, body?: string): Promise<SolrAdminResponse> {
|
||||
const sql = body ? `${method} ${path}\n${body}` : `${method} ${path}`;
|
||||
const result = await executeQuery(connectionId, "", sql);
|
||||
const status = typeof result.rows?.[0]?.[0] === "number" ? result.rows[0][0] : 200;
|
||||
const rawBody = result.elasticsearch_raw_body ?? (typeof result.rows?.[0]?.[1] === "string" ? result.rows[0][1] : "");
|
||||
let parsed: unknown = null;
|
||||
if (rawBody) {
|
||||
try {
|
||||
parsed = parseJsonPreservingLargeNumbers(rawBody);
|
||||
} catch {
|
||||
parsed = rawBody;
|
||||
}
|
||||
}
|
||||
return { status, body: parsed, rawBody, elapsedMs: result.execution_time_ms };
|
||||
}
|
||||
|
||||
export function solrAdminGet(connectionId: string, path: string): Promise<SolrAdminResponse> {
|
||||
return solrAdminRequest(connectionId, "GET", path);
|
||||
}
|
||||
|
||||
/** Solr 错误体 {"error":{"msg","code"}} → 可读消息;用于写操作的状态判定。 */
|
||||
export function solrAdminErrorMessage(res: SolrAdminResponse): string | null {
|
||||
if (res.status < 400) return null;
|
||||
const body = res.body as Record<string, unknown> | null;
|
||||
const msg = body?.error && typeof body.error === "object" ? (body.error as Record<string, unknown>).msg : undefined;
|
||||
return `Solr error (${res.status}): ${typeof msg === "string" ? msg : res.rawBody.slice(0, 500)}`;
|
||||
}
|
||||
|
||||
/** 服务端点(server scope)与 core 端点(core scope,{core} 占位)。 */
|
||||
export interface SolrAdminViewDef {
|
||||
id: SolrAdminViewId;
|
||||
scope: "server" | "core";
|
||||
/** REST 路径模板;core scope 中 {core} 会被替换。 */
|
||||
path: string;
|
||||
/** 需要专用渲染而非通用 JSON 树。 */
|
||||
view: "generic" | "dashboard" | "properties" | "logging" | "coreAdmin" | "overview" | "ping" | "schema" | "analysis" | "segments" | "queryForm" | "replication" | "action";
|
||||
}
|
||||
|
||||
export type SolrAdminViewId = "dashboard" | "logging" | "javaProps" | "threads" | "coreAdmin" | "metrics" | "overview" | "analysis" | "documents" | "paramsets" | "files" | "ping" | "plugins" | "query" | "replication" | "schema" | "segments";
|
||||
|
||||
export const SOLR_ADMIN_SERVER_VIEWS: readonly SolrAdminViewDef[] = [
|
||||
{ id: "dashboard", scope: "server", path: "/admin/info/system", view: "dashboard" },
|
||||
{ id: "logging", scope: "server", path: "/admin/info/logging", view: "logging" },
|
||||
{ id: "javaProps", scope: "server", path: "/admin/info/properties", view: "properties" },
|
||||
{ id: "threads", scope: "server", path: "/admin/info/threads", view: "generic" },
|
||||
{ id: "coreAdmin", scope: "server", path: "/admin/cores?action=STATUS", view: "coreAdmin" },
|
||||
{ id: "metrics", scope: "server", path: "/admin/metrics", view: "generic" },
|
||||
];
|
||||
|
||||
export const SOLR_ADMIN_CORE_VIEWS: readonly SolrAdminViewDef[] = [
|
||||
{ id: "overview", scope: "core", path: "/{core}/admin/luke?show=index", view: "overview" },
|
||||
{ id: "analysis", scope: "core", path: "/{core}/analysis/field", view: "analysis" },
|
||||
{ id: "documents", scope: "core", path: "", view: "action" },
|
||||
{ id: "paramsets", scope: "core", path: "/{core}/config/params", view: "generic" },
|
||||
{ id: "files", scope: "core", path: "/{core}/admin/file", view: "generic" },
|
||||
{ id: "ping", scope: "core", path: "/{core}/admin/ping", view: "ping" },
|
||||
{ id: "plugins", scope: "core", path: "/{core}/admin/mbeans?stats=true", view: "generic" },
|
||||
{ id: "query", scope: "core", path: "", view: "queryForm" },
|
||||
{ id: "replication", scope: "core", path: "/{core}/replication?command=details", view: "replication" },
|
||||
{ id: "schema", scope: "core", path: "/{core}/schema", view: "schema" },
|
||||
{ id: "segments", scope: "core", path: "/{core}/admin/segments", view: "segments" },
|
||||
];
|
||||
|
||||
export function solrAdminViewById(id: SolrAdminViewId): SolrAdminViewDef | undefined {
|
||||
return [...SOLR_ADMIN_SERVER_VIEWS, ...SOLR_ADMIN_CORE_VIEWS].find((view) => view.id === id);
|
||||
}
|
||||
|
||||
export function solrAdminPath(view: SolrAdminViewDef, core: string): string {
|
||||
return view.path.replace("{core}", encodeURIComponent(core));
|
||||
}
|
||||
|
||||
/* ---------- Core Admin ---------- */
|
||||
|
||||
export interface SolrCoreStatus {
|
||||
name: string;
|
||||
instanceDir?: string;
|
||||
dataDir?: string;
|
||||
config?: string;
|
||||
schema?: string;
|
||||
startTime?: string;
|
||||
uptime?: number;
|
||||
numDocs?: number;
|
||||
maxDoc?: number;
|
||||
deletedDocs?: number;
|
||||
sizeInBytes?: number;
|
||||
version?: number;
|
||||
segmentCount?: number;
|
||||
}
|
||||
|
||||
export function parseCoreStatus(body: unknown): SolrCoreStatus[] {
|
||||
const status = (body as Record<string, unknown> | null)?.status;
|
||||
if (!status || typeof status !== "object" || Array.isArray(status)) return [];
|
||||
return Object.entries(status as Record<string, Record<string, unknown>>).map(([name, info]) => {
|
||||
const index = (info?.index ?? {}) as Record<string, unknown>;
|
||||
return {
|
||||
name: typeof info?.name === "string" ? info.name : name,
|
||||
instanceDir: info?.instanceDir as string | undefined,
|
||||
dataDir: info?.dataDir as string | undefined,
|
||||
config: info?.config as string | undefined,
|
||||
schema: info?.schema as string | undefined,
|
||||
startTime: info?.startTime as string | undefined,
|
||||
uptime: typeof info?.uptime === "number" ? info.uptime : undefined,
|
||||
numDocs: typeof index.numDocs === "number" ? index.numDocs : undefined,
|
||||
maxDoc: typeof index.maxDoc === "number" ? index.maxDoc : undefined,
|
||||
deletedDocs: typeof index.deletedDocs === "number" ? index.deletedDocs : undefined,
|
||||
sizeInBytes: typeof index.sizeInBytes === "number" ? index.sizeInBytes : typeof index.size === "number" ? index.size : undefined,
|
||||
version: typeof index.version === "number" ? index.version : undefined,
|
||||
segmentCount: typeof index.segmentCount === "number" ? index.segmentCount : undefined,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
export type SolrCoreAction = "CREATE" | "RELOAD" | "UNLOAD" | "RENAME" | "SWAP";
|
||||
|
||||
/** CoreAdmin 写操作统一走 GET /admin/cores(Solr 官方形态),参数全部由 UI 收集。 */
|
||||
export function solrCoreAdminRequest(connectionId: string, params: Record<string, string>): Promise<SolrAdminResponse> {
|
||||
const query = new URLSearchParams(params).toString();
|
||||
return solrAdminRequest(connectionId, "GET", `/admin/cores?${query}`);
|
||||
}
|
||||
|
||||
/* ---------- Schema ---------- */
|
||||
|
||||
export interface SolrSchemaField {
|
||||
name: string;
|
||||
type?: string;
|
||||
stored?: boolean;
|
||||
indexed?: boolean;
|
||||
required?: boolean;
|
||||
multiValued?: boolean;
|
||||
docValues?: boolean;
|
||||
uninvertible?: boolean;
|
||||
}
|
||||
|
||||
export interface SolrSchemaInfo {
|
||||
name?: string;
|
||||
version?: string;
|
||||
uniqueKey?: string;
|
||||
fields: SolrSchemaField[];
|
||||
dynamicFields: SolrSchemaField[];
|
||||
copyFields: Array<{ source: string; dest: string; maxChars?: number }>;
|
||||
fieldTypeCount: number;
|
||||
}
|
||||
|
||||
export function parseSolrSchema(body: unknown): SolrSchemaInfo {
|
||||
const root = (body as Record<string, unknown> | null)?.schema ?? body;
|
||||
const schema = (root ?? {}) as Record<string, unknown>;
|
||||
const fields = Array.isArray(schema.fields) ? (schema.fields as SolrSchemaField[]) : [];
|
||||
const dynamicFields = Array.isArray(schema.dynamicFields) ? (schema.dynamicFields as SolrSchemaField[]) : [];
|
||||
const copyFields = Array.isArray(schema.copyFields) ? (schema.copyFields as Array<{ source: string; dest: string; maxChars?: number }>) : [];
|
||||
const fieldTypes = Array.isArray(schema.fieldTypes) ? schema.fieldTypes : [];
|
||||
return {
|
||||
name: schema.name as string | undefined,
|
||||
version: schema.version != null ? String(schema.version) : undefined,
|
||||
uniqueKey: schema.uniqueKey as string | undefined,
|
||||
fields,
|
||||
dynamicFields,
|
||||
copyFields,
|
||||
fieldTypeCount: fieldTypes.length,
|
||||
};
|
||||
}
|
||||
|
||||
/* ---------- Analysis ---------- */
|
||||
|
||||
export interface SolrAnalysisStage {
|
||||
/** 分析器类名,如 org.apache.lucene.analysis.standard.StandardTokenizer */
|
||||
name: string;
|
||||
tokens: string[];
|
||||
}
|
||||
|
||||
export interface SolrAnalysisResult {
|
||||
/** index 侧阶段链 */
|
||||
index: SolrAnalysisStage[];
|
||||
/** query 侧阶段链 */
|
||||
query: SolrAnalysisStage[];
|
||||
}
|
||||
|
||||
/**
|
||||
* /analysis/field 响应:analysis.field_names.{f}.index 是
|
||||
* [ [stageName, [tokenObj...]], ... ] 交替数组;query 侧结构相同。
|
||||
*/
|
||||
export function parseAnalysisResponse(body: unknown, fieldName: string): SolrAnalysisResult {
|
||||
const analysis = (body as Record<string, unknown> | null)?.analysis as Record<string, unknown> | undefined;
|
||||
const fieldNames = analysis?.field_names as Record<string, unknown> | undefined;
|
||||
const entry = (fieldName ? fieldNames?.[fieldName] : undefined) ?? (fieldNames ? Object.values(fieldNames)[0] : undefined);
|
||||
const stages = (entry ?? {}) as Record<string, unknown>;
|
||||
const parseStages = (raw: unknown): SolrAnalysisStage[] => {
|
||||
if (!Array.isArray(raw)) return [];
|
||||
const stages: SolrAnalysisStage[] = [];
|
||||
for (const item of raw) {
|
||||
if (!Array.isArray(item) || item.length < 2) continue;
|
||||
const name = typeof item[0] === "string" ? item[0] : String(item[0]);
|
||||
const tokenObjs = Array.isArray(item[1]) ? item[1] : [];
|
||||
const tokens = tokenObjs.map((token) => {
|
||||
if (token && typeof token === "object" && !Array.isArray(token)) {
|
||||
const text = (token as Record<string, unknown>).text;
|
||||
return text != null ? String(text) : JSON.stringify(token);
|
||||
}
|
||||
return String(token);
|
||||
});
|
||||
stages.push({ name, tokens });
|
||||
}
|
||||
return stages;
|
||||
};
|
||||
return { index: parseStages(stages.index), query: parseStages(stages.query) };
|
||||
}
|
||||
|
||||
export function solrAnalysisPath(core: string, fieldName: string, fieldValue: string, queryValue?: string): string {
|
||||
const params = new URLSearchParams();
|
||||
params.set("analysis.fieldname", fieldName);
|
||||
params.set("analysis.fieldvalue", fieldValue);
|
||||
if (queryValue) params.set("analysis.query", queryValue);
|
||||
return `/${encodeURIComponent(core)}/analysis/field?${params.toString()}`;
|
||||
}
|
||||
|
||||
/* ---------- Query Builder(对标官方 Admin UI Query 表单) ---------- */
|
||||
|
||||
export interface SolrQueryParam {
|
||||
key: string;
|
||||
value: string;
|
||||
}
|
||||
|
||||
export interface SolrQueryFormState {
|
||||
/** Request-Handler,如 /select、/query */
|
||||
handler: string;
|
||||
q: string;
|
||||
qop: "" | "AND" | "OR";
|
||||
fq: string[];
|
||||
sort: string;
|
||||
start: string;
|
||||
rows: string;
|
||||
fl: string;
|
||||
df: string;
|
||||
/** paramset 名(useParams 参数,逗号拼接) */
|
||||
useParams: string[];
|
||||
wt: string;
|
||||
indent: boolean;
|
||||
debugQuery: boolean;
|
||||
defType: string;
|
||||
hl: { enabled: boolean; fl: string; snippets: string; fragsize: string; simplePre: string; simplePost: string; requireFieldMatch: boolean; mergeContiguous: boolean };
|
||||
facet: { enabled: boolean; queries: string[]; fields: string[]; prefix: string; sort: string; limit: string; offset: string; mincount: string; missing: boolean };
|
||||
spatial: { enabled: boolean; pt: string; sfield: string; d: string; geofilt: boolean; bbox: boolean };
|
||||
spellcheck: { enabled: boolean; q: string; build: boolean; collate: boolean; count: string; dictionary: string; onlyMorePopular: boolean };
|
||||
rawParams: SolrQueryParam[];
|
||||
/** 非空时改用 JSON Request DSL:POST {handler} + body,与参数表单互斥 */
|
||||
jsonQuery: string;
|
||||
}
|
||||
|
||||
export function defaultSolrQueryForm(): SolrQueryFormState {
|
||||
return {
|
||||
handler: "/select",
|
||||
q: "*:*",
|
||||
qop: "",
|
||||
fq: [],
|
||||
sort: "",
|
||||
start: "0",
|
||||
rows: "10",
|
||||
fl: "",
|
||||
df: "",
|
||||
useParams: [],
|
||||
wt: "json",
|
||||
indent: true,
|
||||
debugQuery: false,
|
||||
defType: "",
|
||||
hl: { enabled: false, fl: "", snippets: "", fragsize: "", simplePre: "", simplePost: "", requireFieldMatch: false, mergeContiguous: false },
|
||||
facet: { enabled: false, queries: [], fields: [], prefix: "", sort: "", limit: "", offset: "", mincount: "", missing: false },
|
||||
spatial: { enabled: false, pt: "", sfield: "", d: "", geofilt: false, bbox: false },
|
||||
spellcheck: { enabled: false, q: "", build: false, collate: false, count: "", dictionary: "", onlyMorePopular: false },
|
||||
rawParams: [],
|
||||
jsonQuery: "",
|
||||
};
|
||||
}
|
||||
|
||||
export interface SolrBuiltQuery {
|
||||
/** REST 控制台可执行文本:"GET /path?qs" 或 "POST /path\n{json}" */
|
||||
text: string;
|
||||
jsonMode: boolean;
|
||||
}
|
||||
|
||||
const nonEmpty = (v: string) => v.trim() !== "";
|
||||
|
||||
/** 表单 → REST 文本。重复参数(fq/facet.field…)经 URLSearchParams.append 保留多值。 */
|
||||
export function buildSolrQuery(core: string, state: SolrQueryFormState): SolrBuiltQuery {
|
||||
const handler = state.handler.trim() || "/select";
|
||||
const base = `/${encodeURIComponent(core)}${handler.startsWith("/") ? handler : `/${handler}`}`;
|
||||
|
||||
if (nonEmpty(state.jsonQuery)) {
|
||||
return { text: `POST ${base}\n${state.jsonQuery.trim()}`, jsonMode: true };
|
||||
}
|
||||
|
||||
const params = new URLSearchParams();
|
||||
const set = (key: string, value: string | undefined) => {
|
||||
if (value != null && nonEmpty(value)) params.set(key, value.trim());
|
||||
};
|
||||
const appendEach = (key: string, values: string[]) => {
|
||||
for (const v of values) if (nonEmpty(v)) params.append(key, v.trim());
|
||||
};
|
||||
|
||||
set("q", state.q || "*:*");
|
||||
set("q.op", state.qop);
|
||||
appendEach("fq", state.fq);
|
||||
set("sort", state.sort);
|
||||
set("start", state.start);
|
||||
set("rows", state.rows);
|
||||
set("fl", state.fl);
|
||||
set("df", state.df);
|
||||
if (state.useParams.length) params.set("useParams", state.useParams.join(","));
|
||||
set("wt", state.wt);
|
||||
if (state.indent) params.set("indent", "on");
|
||||
if (state.debugQuery) params.set("debugQuery", "true");
|
||||
set("defType", state.defType);
|
||||
|
||||
const hl = state.hl;
|
||||
if (hl.enabled) {
|
||||
params.set("hl", "true");
|
||||
set("hl.fl", hl.fl);
|
||||
set("hl.snippets", hl.snippets);
|
||||
set("hl.fragsize", hl.fragsize);
|
||||
set("hl.simple.pre", hl.simplePre);
|
||||
set("hl.simple.post", hl.simplePost);
|
||||
if (hl.requireFieldMatch) params.set("hl.requireFieldMatch", "true");
|
||||
if (hl.mergeContiguous) params.set("hl.mergeContiguous", "true");
|
||||
}
|
||||
|
||||
const facet = state.facet;
|
||||
if (facet.enabled) {
|
||||
params.set("facet", "true");
|
||||
appendEach("facet.query", facet.queries);
|
||||
appendEach("facet.field", facet.fields);
|
||||
set("facet.prefix", facet.prefix);
|
||||
set("facet.sort", facet.sort);
|
||||
set("facet.limit", facet.limit);
|
||||
set("facet.offset", facet.offset);
|
||||
set("facet.mincount", facet.mincount);
|
||||
if (facet.missing) params.set("facet.missing", "true");
|
||||
}
|
||||
|
||||
const spatial = state.spatial;
|
||||
if (spatial.enabled) {
|
||||
set("pt", spatial.pt);
|
||||
set("sfield", spatial.sfield);
|
||||
set("d", spatial.d);
|
||||
// 官方 UI 的 geofilt/bbox 以 fq 函数查询注入
|
||||
if (spatial.geofilt) params.append("fq", "{!geofilt}");
|
||||
if (spatial.bbox) params.append("fq", "{!bbox}");
|
||||
}
|
||||
|
||||
const sc = state.spellcheck;
|
||||
if (sc.enabled) {
|
||||
params.set("spellcheck", "true");
|
||||
set("spellcheck.q", sc.q);
|
||||
if (sc.build) params.set("spellcheck.build", "true");
|
||||
if (sc.collate) params.set("spellcheck.collate", "true");
|
||||
set("spellcheck.count", sc.count);
|
||||
set("spellcheck.dictionary", sc.dictionary);
|
||||
if (sc.onlyMorePopular) params.set("spellcheck.onlyMorePopular", "true");
|
||||
}
|
||||
|
||||
for (const rp of state.rawParams) {
|
||||
if (nonEmpty(rp.key) && nonEmpty(rp.value)) params.append(rp.key.trim(), rp.value.trim());
|
||||
}
|
||||
|
||||
return { text: `GET ${base}?${params.toString()}`, jsonMode: false };
|
||||
}
|
||||
|
||||
/** /{core}/config/params 响应 → paramset 名列表,供 useParams 选择。 */
|
||||
export function parseParamsetNames(body: unknown): string[] {
|
||||
const params = (body as Record<string, unknown> | null)?.response as Record<string, unknown> | undefined;
|
||||
const named = params?.params;
|
||||
if (!named || typeof named !== "object" || Array.isArray(named)) return [];
|
||||
return Object.keys(named as Record<string, unknown>).sort();
|
||||
}
|
||||
|
||||
/** select 响应体 → numFound;非 select/出错为 null。 */
|
||||
export function parseSolrNumFound(rawBody: string): number | null {
|
||||
try {
|
||||
const body = parseJsonPreservingLargeNumbers(rawBody) as Record<string, unknown> | null;
|
||||
const num = (body?.response as Record<string, unknown> | undefined)?.numFound;
|
||||
return typeof num === "number" ? num : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/* ---------- Overview(对标官方 UI:Statistics / Instance / Replication / Healthcheck 组合) ---------- */
|
||||
|
||||
/** luke ?show=index 的 index 块 → Statistics 行 */
|
||||
export interface SolrIndexStats {
|
||||
lastModified?: string;
|
||||
numDocs?: number;
|
||||
maxDoc?: number;
|
||||
deletedDocs?: number;
|
||||
version?: number;
|
||||
segmentCount?: number;
|
||||
current?: boolean;
|
||||
/** Lucene Directory 实现类(org.apache.lucene.store.NRTCachingDirectory 等) */
|
||||
directoryImpl?: string;
|
||||
}
|
||||
|
||||
export function parseIndexStats(body: unknown): SolrIndexStats {
|
||||
const index = (body as Record<string, unknown> | null)?.index as Record<string, unknown> | undefined;
|
||||
if (!index) return {};
|
||||
const directory = typeof index.directory === "string" ? index.directory : undefined;
|
||||
return {
|
||||
lastModified: index.lastModified as string | undefined,
|
||||
numDocs: typeof index.numDocs === "number" ? index.numDocs : undefined,
|
||||
maxDoc: typeof index.maxDoc === "number" ? index.maxDoc : undefined,
|
||||
deletedDocs: typeof index.deletedDocs === "number" ? index.deletedDocs : undefined,
|
||||
version: typeof index.version === "number" ? index.version : undefined,
|
||||
segmentCount: typeof index.segmentCount === "number" ? index.segmentCount : undefined,
|
||||
current: typeof index.current === "boolean" ? index.current : undefined,
|
||||
directoryImpl: directory?.split(":")[0],
|
||||
};
|
||||
}
|
||||
|
||||
/** replication?command=details 的 details 块 */
|
||||
export interface SolrReplicationDetails {
|
||||
isLeader: boolean;
|
||||
isFollower: boolean;
|
||||
indexSize?: string;
|
||||
indexPath?: string;
|
||||
indexVersion?: string;
|
||||
generation?: number;
|
||||
replicableVersion?: number;
|
||||
replicableGeneration?: number;
|
||||
replicationEnabled?: boolean;
|
||||
replicateAfter: string[];
|
||||
/** follower 侧信息(isLeader=false 时展示) */
|
||||
follower?: Record<string, unknown>;
|
||||
}
|
||||
|
||||
export function parseReplicationDetails(body: unknown): SolrReplicationDetails | null {
|
||||
const details = (body as Record<string, unknown> | null)?.details as Record<string, unknown> | undefined;
|
||||
if (!details) return null;
|
||||
const leader = (details.leader ?? {}) as Record<string, unknown>;
|
||||
const follower = details.follower as Record<string, unknown> | undefined;
|
||||
const num = (v: unknown) => (typeof v === "number" ? v : v != null ? Number(v) : undefined);
|
||||
return {
|
||||
isLeader: details.isLeader === true || details.isLeader === "true",
|
||||
isFollower: details.isFollower === true || details.isFollower === "true",
|
||||
indexSize: details.indexSize as string | undefined,
|
||||
indexPath: details.indexPath as string | undefined,
|
||||
indexVersion: details.indexVersion != null ? String(details.indexVersion) : undefined,
|
||||
generation: num(details.generation),
|
||||
replicableVersion: num(leader.replicableVersion),
|
||||
replicableGeneration: num(leader.replicableGeneration),
|
||||
replicationEnabled: leader.replicationEnabled === true || leader.replicationEnabled === "true",
|
||||
replicateAfter: Array.isArray(leader.replicateAfter) ? leader.replicateAfter.map(String) : [],
|
||||
follower,
|
||||
};
|
||||
}
|
||||
|
||||
/** leader 侧启停复制:/{core}/replication?command=enablereplication|disablereplication */
|
||||
export function solrReplicationCommand(connectionId: string, core: string, command: "enablereplication" | "disablereplication"): Promise<SolrAdminResponse> {
|
||||
return solrAdminRequest(connectionId, "GET", `/${encodeURIComponent(core)}/replication?command=${command}`);
|
||||
}
|
||||
|
||||
/** /admin/info/properties 响应 → JVM 工作目录(官方 Instance 框的 CWD)。 */
|
||||
export function parseServerCwd(body: unknown): string | undefined {
|
||||
const props = (body as Record<string, unknown> | null)?.["system.properties"] as Record<string, unknown> | undefined;
|
||||
return typeof props?.["user.dir"] === "string" ? props["user.dir"] : undefined;
|
||||
}
|
||||
|
||||
/* ---------- Dashboard(官方布局:Instance / Versions / JVM + System 进度条) ---------- */
|
||||
|
||||
export interface SolrSystemInfo {
|
||||
mode?: string;
|
||||
solrHome?: string;
|
||||
coreRoot?: string;
|
||||
/** jvm.jmx.startTime(ISO) */
|
||||
startTime?: string;
|
||||
uptimeMs?: number;
|
||||
solrSpec?: string;
|
||||
solrImpl?: string;
|
||||
luceneSpec?: string;
|
||||
luceneImpl?: string;
|
||||
/** name + version 拼接,如 "Eclipse Adoptium OpenJDK 64-Bit Server VM 17.0.15 17.0.15+6" */
|
||||
jvmRuntime?: string;
|
||||
processors?: number;
|
||||
args: string[];
|
||||
jvmMemUsedPct?: number;
|
||||
jvmMemUsed?: string;
|
||||
jvmMemTotal?: string;
|
||||
/** 物理内存:bytes */
|
||||
physMemUsedPct?: number;
|
||||
physMemUsed?: number;
|
||||
physMemTotal?: number;
|
||||
swapUsedPct?: number;
|
||||
swapUsed?: number;
|
||||
swapTotal?: number;
|
||||
fdUsed?: number;
|
||||
fdMax?: number;
|
||||
}
|
||||
|
||||
export function parseSolrSystemInfo(body: unknown): SolrSystemInfo {
|
||||
const root = (body ?? {}) as Record<string, unknown>;
|
||||
const jvm = (root.jvm ?? {}) as Record<string, unknown>;
|
||||
const jmx = (jvm.jmx ?? {}) as Record<string, unknown>;
|
||||
const lucene = (root.lucene ?? {}) as Record<string, unknown>;
|
||||
const system = (root.system ?? {}) as Record<string, unknown>;
|
||||
const memory = (jvm.memory ?? {}) as Record<string, unknown>;
|
||||
const raw = (memory.raw ?? {}) as Record<string, unknown>;
|
||||
|
||||
const num = (v: unknown): number | undefined => (typeof v === "number" && Number.isFinite(v) ? v : undefined);
|
||||
const str = (v: unknown): string | undefined => (typeof v === "string" && v !== "" ? v : undefined);
|
||||
const pct = (used: number | undefined, total: number | undefined) => (used != null && total != null && total > 0 ? (used / total) * 100 : undefined);
|
||||
|
||||
const physTotal = num(system.totalPhysicalMemorySize);
|
||||
const physFree = num(system.freePhysicalMemorySize);
|
||||
const physUsed = physTotal != null && physFree != null ? physTotal - physFree : undefined;
|
||||
const swapTotal = num(system.totalSwapSpaceSize);
|
||||
const swapFree = num(system.freeSwapSpaceSize);
|
||||
const swapUsed = swapTotal != null && swapFree != null ? swapTotal - swapFree : undefined;
|
||||
|
||||
const jvmName = str(jvm.name);
|
||||
const jvmVersion = str(jvm.version);
|
||||
|
||||
return {
|
||||
mode: str(root.mode),
|
||||
solrHome: str(root.solr_home),
|
||||
coreRoot: str(root.core_root),
|
||||
startTime: str(jmx.startTime),
|
||||
uptimeMs: num(jmx.upTimeMS),
|
||||
solrSpec: str(lucene["solr-spec-version"]),
|
||||
solrImpl: str(lucene["solr-impl-version"]),
|
||||
luceneSpec: str(lucene["lucene-spec-version"]),
|
||||
luceneImpl: str(lucene["lucene-impl-version"]),
|
||||
jvmRuntime: [jvmName, jvmVersion].filter(Boolean).join(" ") || undefined,
|
||||
processors: num(jvm.processors),
|
||||
args: Array.isArray(jmx.commandLineArgs) ? jmx.commandLineArgs.map(String) : [],
|
||||
jvmMemUsedPct: num(raw["used%"]),
|
||||
jvmMemUsed: str(memory.used),
|
||||
jvmMemTotal: str(memory.total),
|
||||
physMemUsedPct: pct(physUsed, physTotal),
|
||||
physMemUsed: physUsed,
|
||||
physMemTotal: physTotal,
|
||||
swapUsedPct: pct(swapUsed, swapTotal),
|
||||
swapUsed,
|
||||
swapTotal,
|
||||
fdUsed: num(system.openFileDescriptorCount),
|
||||
fdMax: num(system.maxFileDescriptorCount),
|
||||
};
|
||||
}
|
||||
|
||||
/** solr-impl-version 里带构建日期("9.8.1 dab835... - houston - 2025-03-06 13:59:17"),>1 年提示升级。 */
|
||||
export function solrReleaseAgeDays(implVersion?: string): number | null {
|
||||
if (!implVersion) return null;
|
||||
const match = implVersion.match(/(\d{4})-(\d{2})-(\d{2})/);
|
||||
if (!match) return null;
|
||||
const ts = Date.parse(`${match[1]}-${match[2]}-${match[3]}T00:00:00Z`);
|
||||
if (!Number.isFinite(ts)) return null;
|
||||
return Math.floor((Date.now() - ts) / 86400000);
|
||||
}
|
||||
@@ -0,0 +1,173 @@
|
||||
/**
|
||||
* Read/write classification for Apache Solr REST requests.
|
||||
*
|
||||
* Mirrors `classify_solr_query_risk` in `crates/dbx-sql/src/query_execution_sql.rs`
|
||||
* so the desktop guards (read-only unlock, production safety) agree with the
|
||||
* backend read-only gate instead of treating every request as unrecognized.
|
||||
*
|
||||
* Solr write traffic funnels through `/{core}/update*` (plus `commit`) — for
|
||||
* every HTTP method, since Solr update handlers also answer GET commits.
|
||||
* CoreAdmin/Collections actions and ReplicationHandler commands ride on GET
|
||||
* too, so `action=`/`command=` values outside the read whitelists are
|
||||
* dangerous. Read-only POST handlers are the query
|
||||
* endpoints (select/query/get/export/...). Any other mutating method/path —
|
||||
* `/admin/*`, `/schema`, `/config`, core management — is classified dangerous.
|
||||
*/
|
||||
|
||||
export type SolrRequestRisk = "read" | "write" | "dangerous";
|
||||
|
||||
const REQUEST_LINE = /^(GET|POST|PUT|PATCH|DELETE|HEAD|OPTIONS)\s+(\S+)/i;
|
||||
const READ_ONLY_POST_ENDPOINTS = new Set(["select", "query", "get", "export", "terms", "suggest", "spell", "mlt", "sql", "graph", "clustering", "tvrh", "luke", "elevate", "browse", "debug"]);
|
||||
const READ_ONLY_REPLICATION_COMMANDS = new Set(["details", "restorestatus", "filelist", "filecontent", "filedownload", "filemtime", "indexversion", "showversion"]);
|
||||
const RISK_ORDER: Record<SolrRequestRisk, number> = { read: 0, write: 1, dangerous: 2 };
|
||||
|
||||
function parseRequestLine(line: string): { method: string; rawPath: string; endpoint: string; isUpdatePath: boolean; segments: string[] } | null {
|
||||
const match = line.trim().match(REQUEST_LINE);
|
||||
if (!match) return null;
|
||||
const rawPath = match[2];
|
||||
const path = (rawPath.split("?", 1)[0] ?? "").replace(/\/+$/, "");
|
||||
const segments = path.split("/").filter(Boolean);
|
||||
// Users may paste absolute Solr paths ("/solr/{core}/select") or relative
|
||||
// ones ("{core}/select"); drop the fixed /solr context segment if present.
|
||||
if (segments[0]?.toLowerCase() === "solr") segments.shift();
|
||||
// Update handler variants (/update/json, /update/json/docs, /update/csv)
|
||||
// nest below the update segment, so the last segment alone cannot spot them.
|
||||
const isUpdatePath = segments.some((segment) => segment.startsWith("update") || segment === "commit");
|
||||
return { method: match[1].toUpperCase(), rawPath, endpoint: segments[segments.length - 1]?.toLowerCase() ?? "", isUpdatePath, segments };
|
||||
}
|
||||
|
||||
/**
|
||||
* CoreAdmin/Collections endpoints accept GET-triggered mutations
|
||||
* (`GET /admin/cores?action=CREATE&name=x` really creates a core). Only the
|
||||
* explicitly read-only actions stay "read"; any other action is dangerous.
|
||||
*/
|
||||
function solrAdminRequestIsMutation(rawPath: string, segments: string[]): boolean {
|
||||
const isAdminTarget = segments.some((segment, index) => segment.toLowerCase() === "admin" && ["cores", "collections"].includes(segments[index + 1]?.toLowerCase() ?? ""));
|
||||
if (!isAdminTarget) return false;
|
||||
const query = rawPath.split("?")[1];
|
||||
if (!query) return false;
|
||||
const action = query
|
||||
.split("&")
|
||||
.map((param) => param.split("=", 2))
|
||||
.find(([key]) => key.toLowerCase() === "action")?.[1];
|
||||
if (action === undefined) return false;
|
||||
return !["STATUS", "REQUESTSTATUS", "LIST"].includes(action.toUpperCase());
|
||||
}
|
||||
|
||||
/**
|
||||
* The replication handler also takes GET-triggered mutations
|
||||
* (`GET /{core}/replication?command=disablereplication` really stops
|
||||
* replication). Only the explicitly read-only commands stay "read"; a missing
|
||||
* command falls back to the handler's default details response.
|
||||
*/
|
||||
function solrReplicationRequestIsMutation(rawPath: string, segments: string[]): boolean {
|
||||
if (segments[segments.length - 1]?.toLowerCase() !== "replication") return false;
|
||||
const query = rawPath.split("?")[1];
|
||||
if (!query) return false;
|
||||
const command = query
|
||||
.split("&")
|
||||
.map((param) => param.split("=", 2))
|
||||
.find(([key]) => key.toLowerCase() === "command")?.[1];
|
||||
if (command === undefined) return false;
|
||||
return !READ_ONLY_REPLICATION_COMMANDS.has(command.toLowerCase());
|
||||
}
|
||||
|
||||
function classifyParsedRequest({ method, rawPath, endpoint, isUpdatePath, segments }: { method: string; rawPath: string; endpoint: string; isUpdatePath: boolean; segments: string[] }): SolrRequestRisk {
|
||||
// Solr update handlers also answer GET (commit/optimize/stream.body all
|
||||
// mutate), so update paths count as writes for every method, not just POST.
|
||||
if (isUpdatePath) return "write";
|
||||
if (method === "GET" || method === "HEAD" || method === "OPTIONS") {
|
||||
return solrAdminRequestIsMutation(rawPath, segments) || solrReplicationRequestIsMutation(rawPath, segments) ? "dangerous" : "read";
|
||||
}
|
||||
if (method === "POST" || method === "PUT" || method === "PATCH" || method === "DELETE") {
|
||||
return method === "POST" && READ_ONLY_POST_ENDPOINTS.has(endpoint) ? "read" : "dangerous";
|
||||
}
|
||||
return "dangerous";
|
||||
}
|
||||
|
||||
/**
|
||||
* Classifies a single request: the request line is the first non-comment line,
|
||||
* everything after it is the JSON body. Returns null when the text is not a
|
||||
* REST request.
|
||||
*/
|
||||
export function classifySolrRequestRisk(request: string): SolrRequestRisk | null {
|
||||
const parsed = parseRequestLine(uncommentedLines(request)[0] ?? "");
|
||||
return parsed ? classifyParsedRequest(parsed) : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Classifies every request in the editor text and returns the highest risk, so
|
||||
* a read request followed by a write is still guarded. Like the backend, the
|
||||
* text only counts as REST when its first non-comment line is a request line.
|
||||
*/
|
||||
export function classifySolrSourceRisk(source: string): SolrRequestRisk | null {
|
||||
const lines = uncommentedLines(source);
|
||||
if (!parseRequestLine(lines[0] ?? "")) return null;
|
||||
|
||||
let highest: SolrRequestRisk = "read";
|
||||
for (const line of lines) {
|
||||
const parsed = parseRequestLine(line);
|
||||
if (!parsed) continue;
|
||||
const risk = classifyParsedRequest(parsed);
|
||||
if (RISK_ORDER[risk] > RISK_ORDER[highest]) highest = risk;
|
||||
}
|
||||
return highest;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a parsed request line targets a mutating path that is not a document
|
||||
* update — used by the dangerous-execution confirmation gate.
|
||||
*/
|
||||
export function isDangerousSolrRequest(method: string, path: string): boolean {
|
||||
const upperMethod = method.toUpperCase();
|
||||
const pathname = path.split("?", 1)[0].replace(/\/+$/, "");
|
||||
const segments = pathname.split("/").filter(Boolean);
|
||||
if (segments[0]?.toLowerCase() === "solr") segments.shift();
|
||||
const endpoint = segments[segments.length - 1]?.toLowerCase() ?? "";
|
||||
const isUpdatePath = segments.some((segment) => segment.startsWith("update") || segment === "commit");
|
||||
// Document writes are guarded by the write confirmation, not the dangerous
|
||||
// gate — for every method, including GET-driven commits.
|
||||
if (isUpdatePath) return false;
|
||||
if (upperMethod === "GET" || upperMethod === "HEAD" || upperMethod === "OPTIONS") {
|
||||
return solrAdminRequestIsMutation(path, segments) || solrReplicationRequestIsMutation(path, segments);
|
||||
}
|
||||
if (upperMethod === "POST" || upperMethod === "PUT" || upperMethod === "PATCH" || upperMethod === "DELETE") {
|
||||
return !(upperMethod === "POST" && READ_ONLY_POST_ENDPOINTS.has(endpoint));
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns each line with its leading comments removed, dropping lines that hold
|
||||
* nothing else. Block comments spanning several lines are skipped as a whole so
|
||||
* a commented-out request line is never classified.
|
||||
*/
|
||||
function uncommentedLines(source: string): string[] {
|
||||
const lines: string[] = [];
|
||||
let inBlockComment = false;
|
||||
|
||||
for (const rawLine of source.split("\n")) {
|
||||
let offset = 0;
|
||||
while (offset < rawLine.length) {
|
||||
if (inBlockComment) {
|
||||
const close = rawLine.indexOf("*/", offset);
|
||||
if (close < 0) break;
|
||||
inBlockComment = false;
|
||||
offset = close + 2;
|
||||
continue;
|
||||
}
|
||||
while (offset < rawLine.length && /\s/.test(rawLine[offset] ?? "")) offset += 1;
|
||||
if (offset >= rawLine.length) break;
|
||||
if (rawLine.startsWith("/*", offset)) {
|
||||
inBlockComment = true;
|
||||
offset += 2;
|
||||
continue;
|
||||
}
|
||||
if (rawLine[offset] === "#" || rawLine.startsWith("//", offset)) break;
|
||||
lines.push(rawLine.slice(offset));
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return lines;
|
||||
}
|
||||
@@ -461,6 +461,7 @@ export function shouldRunSqlSemanticDiagnostics(sql: string, cursor: number, opt
|
||||
options.databaseType === "elasticsearch" ||
|
||||
options.databaseType === "easysearch" ||
|
||||
options.databaseType === "meilisearch" ||
|
||||
options.databaseType === "solr" ||
|
||||
options.databaseType === "qdrant" ||
|
||||
options.databaseType === "milvus" ||
|
||||
options.databaseType === "weaviate" ||
|
||||
@@ -481,6 +482,7 @@ export function isSqlSemanticDiagnosticInputContext(sql: string, cursor: number,
|
||||
options.databaseType === "elasticsearch" ||
|
||||
options.databaseType === "easysearch" ||
|
||||
options.databaseType === "meilisearch" ||
|
||||
options.databaseType === "solr" ||
|
||||
options.databaseType === "qdrant" ||
|
||||
options.databaseType === "milvus" ||
|
||||
options.databaseType === "weaviate" ||
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { classifyElasticsearchRequestRisk, classifyElasticsearchSourceRisk, type ElasticsearchRequestRisk } from "@/lib/elasticsearch/elasticsearchRequestRisk";
|
||||
import { classifySolrRequestRisk, classifySolrSourceRisk } from "@/lib/solr/solrRequestRisk";
|
||||
import { mongoAggregateWriteStage, splitMongoCommandRanges, type MongoCommand } from "@/lib/mongo/mongoShellCommand";
|
||||
import { isElasticsearchCompatibleDatabaseType, type DatabaseType } from "@/types/database";
|
||||
import { isElasticsearchCompatibleDatabaseType, isSolrDatabaseType, type DatabaseType } from "@/types/database";
|
||||
|
||||
export type SqlRiskLevel = "read" | "write" | "ddl" | "transaction" | "unknown";
|
||||
|
||||
@@ -54,7 +55,7 @@ export function classifySqlRisk(sql: string, options: SqlRiskOptions = {}): SqlR
|
||||
|
||||
// REST requests carry a JSON body that must not be split on semicolons, and
|
||||
// every request in the text is classified so the highest risk wins.
|
||||
const searchEngineRisk = searchEngineAssessment(sql, options.dialect, classifyElasticsearchSourceRisk);
|
||||
const searchEngineRisk = searchEngineAssessment(sql, options.dialect, { elasticsearch: classifyElasticsearchSourceRisk, solr: classifySolrSourceRisk });
|
||||
if (searchEngineRisk) return { ...searchEngineRisk, statements: [searchEngineRisk] };
|
||||
|
||||
const statements = splitSqlStatementsForSafety(sql).map((statement) => classifySqlStatementRisk(statement, options));
|
||||
@@ -69,7 +70,7 @@ export function classifySqlStatementRisk(sql: string, options: SqlRiskOptions =
|
||||
|
||||
const dynamodbRisk = classifyDynamoDbStatementRisk(sql, options.dialect);
|
||||
if (dynamodbRisk) return dynamodbRisk;
|
||||
const searchEngineRisk = searchEngineAssessment(sql, options.dialect, classifyElasticsearchRequestRisk);
|
||||
const searchEngineRisk = searchEngineAssessment(sql, options.dialect, { elasticsearch: classifyElasticsearchRequestRisk, solr: classifySolrRequestRisk });
|
||||
if (searchEngineRisk) return searchEngineRisk;
|
||||
return classifyTokens(tokenizeSqlForRisk(sql));
|
||||
}
|
||||
@@ -85,9 +86,11 @@ export function classifySqlStatementRisk(sql: string, options: SqlRiskOptions =
|
||||
* is a schema change, ...), which a request path does not carry. Reporting
|
||||
* `rest` keeps REST mutations as opaque as they were before this branch existed.
|
||||
*/
|
||||
function searchEngineAssessment(sql: string, dialect: DatabaseType | string | undefined, classify: (value: string) => ElasticsearchRequestRisk | null): SqlRiskStatementAssessment | null {
|
||||
if (!isElasticsearchCompatibleDatabaseType(dialect as DatabaseType | undefined)) return null;
|
||||
const risk = classify(sql);
|
||||
function searchEngineAssessment(sql: string, dialect: DatabaseType | string | undefined, classify: { elasticsearch: (value: string) => ElasticsearchRequestRisk | null; solr: (value: string) => ElasticsearchRequestRisk | null }): SqlRiskStatementAssessment | null {
|
||||
const databaseType = dialect as DatabaseType | undefined;
|
||||
const classifier = isSolrDatabaseType(databaseType) ? classify.solr : isElasticsearchCompatibleDatabaseType(databaseType) ? classify.elasticsearch : null;
|
||||
if (!classifier) return null;
|
||||
const risk = classifier(sql);
|
||||
if (!risk) return null;
|
||||
return { risk: risk === "read" ? "read" : risk === "write" ? "write" : "ddl", firstKeyword: "rest" };
|
||||
}
|
||||
|
||||
@@ -3,7 +3,7 @@ import { cursorBelongsToTrailingStatementDelimiter } from "@/lib/sql/statementDe
|
||||
import { splitMongoCommandRanges } from "@/lib/mongo/mongoShellCommand";
|
||||
import { isRedisCommentLine } from "@/lib/redis/redisCommandTokenizer";
|
||||
import { readSqlBracedParameterAt, type SqlParameterOptions } from "@/lib/sql/sqlParameters";
|
||||
import { isElasticsearchCompatibleDatabaseType, isMeilisearchDatabaseType, type DatabaseType } from "@/types/database";
|
||||
import { isElasticsearchCompatibleDatabaseType, isMeilisearchDatabaseType, isSolrDatabaseType, type DatabaseType } from "@/types/database";
|
||||
|
||||
/**
|
||||
* A contiguous range of SQL text expressed as document offsets plus the
|
||||
@@ -18,7 +18,7 @@ export interface SqlTextRange {
|
||||
const ELASTICSEARCH_REST_REQUEST = /^(?:GET|POST|PUT|PATCH|DELETE|HEAD)\s+\S+/i;
|
||||
|
||||
function isHttpJsonRestDatabaseType(databaseType?: DatabaseType): boolean {
|
||||
return isElasticsearchCompatibleDatabaseType(databaseType) || isMeilisearchDatabaseType(databaseType);
|
||||
return isElasticsearchCompatibleDatabaseType(databaseType) || isMeilisearchDatabaseType(databaseType) || isSolrDatabaseType(databaseType);
|
||||
}
|
||||
|
||||
export function elasticsearchRestRequestRanges(sql: string, databaseType?: DatabaseType): SqlTextRange[] {
|
||||
@@ -27,7 +27,7 @@ export function elasticsearchRestRequestRanges(sql: string, databaseType?: Datab
|
||||
return requests.length > 0 && requests.every((request) => ELASTICSEARCH_REST_REQUEST.test(request.sql)) ? requests : [];
|
||||
}
|
||||
|
||||
const NON_SQL_EXECUTION_TARGET_TYPES: ReadonlySet<DatabaseType> = new Set(["mongodb", "elasticsearch", "easysearch", "meilisearch", "qdrant", "milvus", "weaviate", "chromadb", "etcd", "zookeeper", "consul", "mq", "neo4j", "victoriametrics"]);
|
||||
const NON_SQL_EXECUTION_TARGET_TYPES: ReadonlySet<DatabaseType> = new Set(["mongodb", "elasticsearch", "easysearch", "meilisearch", "solr", "qdrant", "milvus", "weaviate", "chromadb", "etcd", "zookeeper", "consul", "mq", "neo4j", "victoriametrics"]);
|
||||
|
||||
export function supportsExecutionTargetPicker(databaseType?: DatabaseType): boolean {
|
||||
return !!databaseType && (databaseType === "redis" || isHttpJsonRestDatabaseType(databaseType) || !NON_SQL_EXECUTION_TARGET_TYPES.has(databaseType));
|
||||
@@ -270,6 +270,7 @@ const DATABASE_SOFT_STATEMENT_KEYWORDS: Partial<Record<DatabaseType, readonly st
|
||||
mongodb: [],
|
||||
elasticsearch: [],
|
||||
easysearch: [],
|
||||
solr: [],
|
||||
qdrant: [],
|
||||
milvus: [],
|
||||
weaviate: [],
|
||||
|
||||
@@ -84,6 +84,12 @@ const capabilityByType: Partial<Record<DatabaseType, Partial<TableMetadataCapabi
|
||||
triggers: false,
|
||||
ddl: false,
|
||||
},
|
||||
solr: {
|
||||
indexes: false,
|
||||
foreignKeys: false,
|
||||
triggers: false,
|
||||
ddl: false,
|
||||
},
|
||||
hbase: {
|
||||
indexes: false,
|
||||
foreignKeys: false,
|
||||
|
||||
Reference in new issue
Block a user