Skip to content

armgit / dbx

Public Imported from GitHub
0

25 MB lightweight cross-platform database client for 100+ databases, including MySQL, PostgreSQL, SQLite, Redis, MongoDB, DuckDB, SQL Server, and Dameng. Built-in AI, MCP Server, CLI, desktop and Docker. | 轻量级跨平台数据库管理工具,支持 MySQL、PostgreSQL、SQLite、Redis、MongoDB、达梦等 100+ 数据库,提供桌面端、Docker、CLI、内置 AI 助手和 MCP。

feat(solr): add Apache Solr connection support

Terry Yao3687a9cbfb30
diff --git a/apps/desktop/public/icons/database/solr.svg b/apps/desktop/public/icons/database/solr.svg
new file mode 100644
index 0000000000..b4c1bb7f12
--- /dev/null
+++ b/apps/desktop/public/icons/database/solr.svg
@@ -0,0 +1 @@
+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 48 48"><defs><clipPath id="a" clipPathUnits="userSpaceOnUse"><path d="M0 102.654h203.005V0H0Z"/></clipPath></defs><g clip-path="url(#a)" transform="matrix(1.33333 0 0 -1.33333 0 136.872)"><path d="m0 0-33-35.677L8.473-16.543A33.5 33.5 0 0 1 0 0" style="fill:#da3522;fill-opacity:1;fill-rule:nonzero;stroke:none" transform="translate(31.112 96.955)scale(.53706)"/><path d="M0 0c-4.572 0-8.928-.917-12.9-2.572l-4.428-37.314L4.799-.347A34 34 0 0 1 0 0" style="fill:#da3522;fill-opacity:1;fill-rule:nonzero;stroke:none" transform="translate(17.962 102.654)scale(.53706)"/><path d="m0 0-39.298-21.992 36.87 4.375A33.46 33.46 0 0 1 0 0" style="fill:#da3522;fill-opacity:1;fill-rule:nonzero;stroke:none" transform="translate(35.839 86.966)scale(.53706)"/><path d="M0 0a33.75 33.75 0 0 1 10.612 11.619l-34.559-6.863Z" style="fill:#da3522;fill-opacity:1;fill-rule:nonzero;stroke:none" transform="translate(28.058 69.675)scale(.53706)"/><path d="m0 0-19.237-41.695L16.448-8.689C11.973-4.384 6.313-1.303 0 0" style="fill:#da3522;fill-opacity:1;fill-rule:nonzero;stroke:none" transform="translate(21.626 102.28)scale(.53706)"/><path d="M0 0a33.4 33.4 0 0 1 10.54 2.638L-8.818 4.935Z" style="fill:#da3522;fill-opacity:1;fill-rule:nonzero;stroke:none" transform="translate(19.47 66.654)scale(.53706)"/><path d="M0 0a33.4 33.4 0 0 1-2.829-10.792l5.215-9.32z" style="fill:#da3522;fill-opacity:1;fill-rule:nonzero;stroke:none" transform="translate(1.524 92.034)scale(.53706)"/><path d="M0 0a33.74 33.74 0 0 1-11.832-10.567l4.867-24.504z" style="fill:#da3522;fill-opacity:1;fill-rule:nonzero;stroke:none" transform="translate(9.471 100.531)scale(.53706)"/></g></svg>
\ No newline at end of file
diff --git a/apps/desktop/src/App.vue b/apps/desktop/src/App.vue
index 0dbc6329bc..6c18902f71 100644
--- a/apps/desktop/src/App.vue
+++ b/apps/desktop/src/App.vue
@@ -3207,7 +3207,7 @@ async function handleQuickOpenSelect(item: any) {
await connectionStore.loadConsulRoot(item.connectionId);
} else if (config?.db_type === "mongodb") {
await connectionStore.loadMongoDatabases(item.connectionId);
- } else if (config?.db_type === "elasticsearch" || config?.db_type === "easysearch" || config?.db_type === "meilisearch") {
+ } else if (config?.db_type === "elasticsearch" || config?.db_type === "easysearch" || config?.db_type === "meilisearch" || config?.db_type === "solr") {
await connectionStore.openElasticsearchConnectionTree(item.connectionId);
} else if (config?.db_type === "qdrant" || config?.db_type === "milvus" || config?.db_type === "weaviate" || config?.db_type === "chromadb") {
await connectionStore.loadVectorCollections(item.connectionId);
@@ -3234,7 +3234,7 @@ async function handleQuickOpenSelect(item: any) {
await connectionStore.loadConsulRoot(item.connectionId);
} else if (config?.db_type === "mongodb") {
await connectionStore.loadMongoDatabases(item.connectionId);
- } else if (config?.db_type === "elasticsearch" || config?.db_type === "easysearch" || config?.db_type === "meilisearch") {
+ } else if (config?.db_type === "elasticsearch" || config?.db_type === "easysearch" || config?.db_type === "meilisearch" || config?.db_type === "solr") {
await connectionStore.openElasticsearchConnectionTree(item.connectionId);
} else if (config?.db_type === "qdrant" || config?.db_type === "milvus" || config?.db_type === "weaviate" || config?.db_type === "chromadb") {
await connectionStore.loadVectorCollections(item.connectionId);
diff --git a/apps/desktop/src/components/connection/ConnectionDialog.vue b/apps/desktop/src/components/connection/ConnectionDialog.vue
index a22e80dc84..9eef79123a 100644
--- a/apps/desktop/src/components/connection/ConnectionDialog.vue
+++ b/apps/desktop/src/components/connection/ConnectionDialog.vue
@@ -3241,6 +3241,7 @@ const tlsCapableDatabaseTypes = new Set<DatabaseType>([
"elasticsearch",
"easysearch",
"meilisearch",
+ "solr",
"hbase",
"qdrant",
"milvus",
@@ -4569,12 +4570,12 @@ function connectionConfigForSubmit(id: string, generatedName = "", validatePlugi
if ((config.client_cert_path && !config.client_key_path) || (!config.client_cert_path && config.client_key_path)) {
throw new Error(t("connection.etcdClientCertPairRequired"));
}
- } else if (form.value.db_type !== "consul" && config.db_type !== "elasticsearch" && config.db_type !== "easysearch") {
+ } else if (form.value.db_type !== "consul" && config.db_type !== "elasticsearch" && config.db_type !== "easysearch" && config.db_type !== "solr") {
config.etcd_endpoints = undefined;
config.client_cert_path = undefined;
config.client_key_path = undefined;
}
- if (config.db_type === "elasticsearch" || config.db_type === "easysearch") {
+ if (config.db_type === "elasticsearch" || config.db_type === "easysearch" || config.db_type === "solr") {
config.client_cert_path = config.client_cert_path?.trim() || "";
config.client_key_path = config.client_key_path?.trim() || "";
if ((config.client_cert_path && !config.client_key_path) || (!config.client_cert_path && config.client_key_path)) {
@@ -4591,7 +4592,8 @@ function connectionConfigForSubmit(id: string, generatedName = "", validatePlugi
config.db_type !== "victoriametrics" &&
config.db_type !== "zookeeper" &&
config.db_type !== "elasticsearch" &&
- config.db_type !== "easysearch"
+ config.db_type !== "easysearch" &&
+ config.db_type !== "solr"
) {
config.ca_cert_path = undefined;
} else {
@@ -8115,7 +8117,7 @@ function openExternalUrl(url: string) {
</div>
</div>
- <div v-if="form.db_type !== 'hbase' && form.db_type !== 'meilisearch' && form.db_type !== 'spanner'" class="grid grid-cols-4 items-center gap-4">
+ <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">
<Label :class="connectionLabelClass">{{ databaseLabel }}</Label>
<Input v-model="form.database" class="col-span-3" :placeholder="databasePlaceholder" />
</div>
diff --git a/apps/desktop/src/components/diff/DataCompareDialog.vue b/apps/desktop/src/components/diff/DataCompareDialog.vue
index fbc4b3c472..2bd43027e3 100644
--- a/apps/desktop/src/components/diff/DataCompareDialog.vue
+++ b/apps/desktop/src/components/diff/DataCompareDialog.vue
@@ -114,7 +114,7 @@ let initializingPrefillGeneration = 0;
let componentUnmounted = false;
let shownSessionError = "";
-const sqlConnections = computed(() => store.connections.filter((connection) => !["redis", "mongodb", "elasticsearch", "easysearch", "meilisearch", "qdrant", "milvus", "weaviate", "chromadb", "etcd", "zookeeper", "consul", "mq", "nacos"].includes(connection.db_type)));
+const sqlConnections = computed(() => store.connections.filter((connection) => !["redis", "mongodb", "elasticsearch", "easysearch", "meilisearch", "solr", "qdrant", "milvus", "weaviate", "chromadb", "etcd", "zookeeper", "consul", "mq", "nacos"].includes(connection.db_type)));
const selectedSourceTableNames = computed(() => sourceTables.value.filter((table) => selectedSourceTables.value.has(table)));
const isBatchCompare = computed(() => selectedSourceTableNames.value.length > 1);
// Bridge the shared TableMultiSelect `string[]` v-model with the Set-based selection store.
diff --git a/apps/desktop/src/components/diff/SchemaDiffConfigStep.vue b/apps/desktop/src/components/diff/SchemaDiffConfigStep.vue
index 67853c6f02..f7590813f5 100644
--- a/apps/desktop/src/components/diff/SchemaDiffConfigStep.vue
+++ b/apps/desktop/src/components/diff/SchemaDiffConfigStep.vue
@@ -84,7 +84,7 @@ const targetSchemas = ref<string[]>([]);
const sourceDbVersion = ref<string | null>(null);
const targetDbVersion = ref<string | null>(null);
-const sqlConnections = computed(() => store.connections.filter((c: any) => !["mongodb", "redis", "elasticsearch", "easysearch", "meilisearch", "etcd", "zookeeper", "consul", "mq", "nacos"].includes(c.db_type)));
+const sqlConnections = computed(() => store.connections.filter((c: any) => !["mongodb", "redis", "elasticsearch", "easysearch", "meilisearch", "solr", "etcd", "zookeeper", "consul", "mq", "nacos"].includes(c.db_type)));
const sourceConfig = computed(() => store.getConfig(props.sourceConnectionId));
const targetConfig = computed(() => store.getConfig(props.targetConnectionId));
diff --git a/apps/desktop/src/components/document/DocumentBrowser.vue b/apps/desktop/src/components/document/DocumentBrowser.vue
index 9ebcffa22e..574cb647ec 100644
--- a/apps/desktop/src/components/document/DocumentBrowser.vue
+++ b/apps/desktop/src/components/document/DocumentBrowser.vue
@@ -71,7 +71,7 @@ import {
stringifyDocumentStoreValue,
documentStoreValueForGrid,
} from "@/lib/app/documentJsonValues";
-import { applyDocumentStoreIdentityPlan, formatMeilisearchDocumentOperationPreview, insertDocumentStoreDocument as insertDocumentStoreDocumentCore } from "@/lib/app/documentStoreSave";
+import { applyDocumentStoreIdentityPlan, formatMeilisearchDocumentOperationPreview, formatSolrDocumentOperationPreview, insertDocumentStoreDocument as insertDocumentStoreDocumentCore } from "@/lib/app/documentStoreSave";
import { restoreDocumentBrowserState, saveDocumentBrowserState, type DocumentBrowserDataSnapshot } from "@/lib/tabs/documentBrowserStateCache";
import RedisJsonEditor from "@/components/redis/RedisJsonEditor.vue";
import { isLosslessJsonNumber, parseJsonPreservingLargeNumbers } from "@/lib/common/safeJsonFormat";
@@ -145,7 +145,7 @@ const DYNAMODB_DEFAULT_EXPORT_ROW_LIMIT = 10_000;
// stores (DynamoDB/Elasticsearch) cannot resume a page without their cursor
// stacks, and infinite scroll always restarts from the first segment.
const restoredDocumentBrowserState = props.stateKey ? restoreDocumentBrowserState(props.stateKey) : undefined;
-const skipBasedDocumentStore = documentStoreProviderFor(props.databaseType).kind === "mongodb" || documentStoreProviderFor(props.databaseType).kind === "meilisearch";
+const skipBasedDocumentStore = ["mongodb", "meilisearch", "solr"].includes(documentStoreProviderFor(props.databaseType).kind);
const restoresSkipBasedPage = !!restoredDocumentBrowserState && !settingsStore.editorSettings.infiniteScroll && skipBasedDocumentStore;
const documents = ref<JsonRecord[]>([]);
@@ -466,6 +466,12 @@ function elasticsearchGridColumnTypesFor(columns: readonly string[]): string[] {
});
}
const elasticsearchGridColumnTypes = computed(() => elasticsearchGridColumnTypesFor(lastGridColumns.value));
+const solrSchemaFields = ref<ColumnInfo[]>([]);
+const solrFieldTypes = computed(() => new Map(solrSchemaFields.value.map((field) => [field.name, field.data_type])));
+function solrGridColumnTypesFor(columns: readonly string[]): string[] {
+ return columns.map((column) => (column === "_id" ? "string" : (solrFieldTypes.value.get(column) ?? "")));
+}
+const solrGridColumnTypes = computed(() => solrGridColumnTypesFor(lastGridColumns.value));
const dynamodbTableDescription = ref<DynamoDbTableDescription | null>(null);
const dynamodbIndexName = ref("__table__");
const dynamodbPageCursors = ref<Array<string | undefined>>([undefined]);
@@ -536,6 +542,9 @@ const deleteDetails = computed(() => {
});
}
const displayId = mongoDocumentIdForGrid(id);
+ if (props.databaseType === "solr") {
+ return `Solr core: ${props.collection}\nDocument _id: ${String(displayId)}`;
+ }
if (props.databaseType === "elasticsearch" || props.databaseType === "easysearch" || props.databaseType === "meilisearch") {
const product = props.databaseType === "easysearch" ? "Easysearch" : props.databaseType === "meilisearch" ? "Meilisearch" : "Elasticsearch";
return `${product} index: ${props.collection}\nDocument _id: ${String(displayId)}`;
@@ -608,7 +617,7 @@ function commitLoadedDocuments(nextDocuments: JsonRecord[], nextCopyDocuments: J
const gridResult = computed<QueryResult>(() => {
const docs = documents.value;
- const columnTypes = documentStoreProvider.value.kind === "elasticsearch" ? elasticsearchGridColumnTypes.value : lastGridColumnTypes.value;
+ const columnTypes = documentStoreProvider.value.kind === "elasticsearch" ? elasticsearchGridColumnTypes.value : documentStoreProvider.value.kind === "solr" ? solrGridColumnTypes.value : lastGridColumnTypes.value;
if (!docs.length) {
return {
columns: lastGridColumns.value,
@@ -637,7 +646,7 @@ const gridResult = computed<QueryResult>(() => {
async function exportAllDocumentStoreDocuments(onProgress?: (info: { rowsExported: number; totalRows: number | null }) => void): Promise<QueryResult | undefined> {
const kind = documentStoreProvider.value.kind;
- if (kind !== "mongodb" && kind !== "dynamodb" && kind !== "elasticsearch") return undefined;
+ if (kind !== "mongodb" && kind !== "dynamodb" && kind !== "elasticsearch" && kind !== "solr") return undefined;
const connectionId = props.connectionId;
const database = props.database;
@@ -673,7 +682,7 @@ async function exportAllDocumentStoreDocuments(onProgress?: (info: { rowsExporte
}
}
- if ((kind === "mongodb" || kind === "elasticsearch") && result.total_is_exact !== false) totalRows = Math.min(result.total, rowLimit);
+ if ((kind === "mongodb" || kind === "elasticsearch" || kind === "solr") && result.total_is_exact !== false) totalRows = Math.min(result.total, rowLimit);
onProgress?.({ rowsExported: exportedDocuments.length, totalRows });
if (kind === "dynamodb" || kind === "elasticsearch") {
@@ -705,7 +714,7 @@ async function exportAllDocumentStoreDocuments(onProgress?: (info: { rowsExporte
const result = mongoDocumentsToQueryResult(exportedDocuments, performance.now() - exportStartedAt, totalRows ?? exportedDocuments.length, exportedCopyDocuments, totalRows !== null);
if (result.columns.length === 0) result.columns = gridResult.value.columns;
- result.column_types = kind === "mongodb" ? mongoDocumentGridColumnTypes(exportedDocuments, result.columns) : kind === "elasticsearch" ? elasticsearchGridColumnTypesFor(result.columns) : undefined;
+ result.column_types = kind === "mongodb" ? mongoDocumentGridColumnTypes(exportedDocuments, result.columns) : kind === "elasticsearch" ? elasticsearchGridColumnTypesFor(result.columns) : kind === "solr" ? solrGridColumnTypesFor(result.columns) : undefined;
result.affected_rows = exportedDocuments.length;
result.truncated = (kind === "dynamodb" || kind === "elasticsearch") && !!cursor && exportedDocuments.length >= rowLimit;
result.has_more = result.truncated;
@@ -717,10 +726,19 @@ const elasticsearchFilterFieldNames = computed(() => {
const names = [...elasticsearchMappingFields.value.map((field) => field.name), ...gridResult.value.columns, "_id", "_routing"];
return [...new Set(names.filter(Boolean))];
});
+const solrFilterFieldNames = computed(() => {
+ const names = [...solrSchemaFields.value.map((field) => field.name), ...gridResult.value.columns, "_id"];
+ return [...new Set(names.filter(Boolean))];
+});
const documentFilterFieldTree = computed<DocumentFieldPathNode[]>(() => {
if (documentStoreProvider.value.kind === "elasticsearch") {
return elasticsearchFieldPathTreeFromFieldNames(elasticsearchFilterFieldNames.value, elasticsearchFieldTypes.value);
}
+ if (documentStoreProvider.value.kind === "solr") {
+ // Schema fields give the filter builder a complete field list even before
+ // any document page has loaded; unknown Solr types stay leaf-selectable.
+ return elasticsearchFieldPathTreeFromFieldNames(solrFilterFieldNames.value, solrFieldTypes.value);
+ }
const tree = documentFieldPathTreeFromDocuments(documents.value);
if (tree.length > 0) return tree;
return gridResult.value.columns.map((column) => ({
@@ -1395,12 +1413,16 @@ async function applyDocumentStructuredFilters() {
applyFilter();
}
-async function loadElasticsearchMappingFields() {
- if (documentStoreProvider.value.kind !== "elasticsearch") return;
+async function loadDocumentStoreSchemaFields() {
+ const kind = documentStoreProvider.value.kind;
+ if (kind !== "elasticsearch" && kind !== "solr") return;
try {
- elasticsearchMappingFields.value = (await api.getColumns(props.connectionId, props.database, "", props.collection)) ?? [];
+ const fields = (await api.getColumns(props.connectionId, props.database, "", props.collection)) ?? [];
+ if (kind === "elasticsearch") elasticsearchMappingFields.value = fields;
+ else solrSchemaFields.value = fields;
} catch {
- elasticsearchMappingFields.value = [];
+ if (kind === "elasticsearch") elasticsearchMappingFields.value = [];
+ else solrSchemaFields.value = [];
}
}
@@ -1687,9 +1709,9 @@ async function previewDocumentChanges(changes: DocumentGridChanges): Promise<str
const sourceDocument = documents.value[rowIdx];
if (!sourceDocument) continue;
const documentId = sourceDocument._id ?? id;
- const updated = buildPathIdentityUpdatedDocument(sourceDocument, dirtyCols, columns, "meilisearch");
- const writeDocument = prepareDocumentStoreWriteDocument(updated, { kind: "meilisearch", mode: "update" });
- stmts.push(formatMeilisearchDocumentOperationPreview({ action: "update", index: coll, id: documentId, document: writeDocument }));
+ const updated = buildPathIdentityUpdatedDocument(sourceDocument, dirtyCols, columns, kind === "solr" ? "solr" : "meilisearch");
+ const writeDocument = prepareDocumentStoreWriteDocument(updated, { kind: kind === "solr" ? "solr" : "meilisearch", mode: "update" });
+ stmts.push(kind === "solr" ? formatSolrDocumentOperationPreview({ action: "update", core: coll, id: documentId, document: writeDocument }) : formatMeilisearchDocumentOperationPreview({ action: "update", index: coll, id: documentId, document: writeDocument }));
}
} else {
const updateDoc = buildMongoUpdateDocument(dirtyCols, columns, documents.value[rowIdx]);
@@ -1707,7 +1729,7 @@ async function previewDocumentChanges(changes: DocumentGridChanges): Promise<str
continue;
}
if (!isEs) {
- stmts.push(formatMeilisearchDocumentOperationPreview({ action: "delete", index: coll, id: documents.value[rowIdx]?._id ?? id }));
+ stmts.push(kind === "solr" ? formatSolrDocumentOperationPreview({ action: "delete", core: coll, id: documents.value[rowIdx]?._id ?? id }) : formatMeilisearchDocumentOperationPreview({ action: "delete", index: coll, id: documents.value[rowIdx]?._id ?? id }));
continue;
}
const routing = documentRoutingFromGridRow(row, columns);
@@ -1730,8 +1752,8 @@ async function previewDocumentChanges(changes: DocumentGridChanges): Promise<str
}
if (!isEs) {
const idValue = idColIdx >= 0 ? newRow[idColIdx] : null;
- const id = idValue === null || idValue === undefined || idValue === "" ? undefined : parseDocumentStoreInputValue(idValue, "meilisearch");
- stmts.push(formatMeilisearchDocumentOperationPreview({ action: id === undefined ? "insert" : "upsert", index: coll, id, document: doc }));
+ const id = idValue === null || idValue === undefined || idValue === "" ? undefined : parseDocumentStoreInputValue(idValue, kind === "solr" ? "solr" : "meilisearch");
+ stmts.push(kind === "solr" ? formatSolrDocumentOperationPreview({ action: id === undefined ? "insert" : "upsert", core: coll, id, document: doc }) : formatMeilisearchDocumentOperationPreview({ action: id === undefined ? "insert" : "upsert", index: coll, id, document: doc }));
continue;
}
const id = idColIdx >= 0 ? documentIdFromGridValue(newRow[idColIdx]) : null;
@@ -1917,7 +1939,7 @@ async function load(options: { page?: number; append?: boolean; offset?: number;
if (documentLoadExecutionId.value !== executionId) return;
if (connectionId !== props.connectionId || database !== props.database || collection !== props.collection || storeKind !== documentStoreProvider.value.kind) return;
const nextDocuments =
- storeKind === "elasticsearch" && result.raw_documents?.length === result.documents.length
+ (storeKind === "elasticsearch" || storeKind === "solr") && result.raw_documents?.length === result.documents.length
? result.raw_documents.map((raw, index) => {
try {
return asRecord(parseJsonPreservingLargeNumbers(raw));
@@ -1997,7 +2019,7 @@ async function countExactDocumentTotal(): Promise<number | undefined> {
paginationTotal.value = totals.paginationTotal;
return exactCount;
}
- const exactCount = request.storeKind === "dynamodb" ? await api.documentCountDocuments(request.connectionId, request.collection, request.filter) : await api.mongoCountDocuments(request.connectionId, request.database, request.collection, request.filter, "accurate");
+ const exactCount = request.storeKind === "dynamodb" || request.storeKind === "solr" ? await api.documentCountDocuments(request.connectionId, request.collection, request.filter) : await api.mongoCountDocuments(request.connectionId, request.database, request.collection, request.filter, "accurate");
if (!isCurrentDocumentQueryTotalCountRequest(request)) return undefined;
if (!Number.isFinite(exactCount) || exactCount < 0) {
throw new Error("invalid count");
@@ -2633,9 +2655,9 @@ onMounted(async () => {
console.warn("[DBX] ensureConnected failed for", props.connectionId, e);
}
await loadDynamoDbTableDescription();
- // Mapping metadata enriches the filter builder, but it must not delay the
- // first page of documents when the mapping endpoint is slow.
- void loadElasticsearchMappingFields();
+ // Schema metadata enriches the filter builder, but it must not delay the
+ // first page of documents when the schema endpoint is slow.
+ void loadDocumentStoreSchemaFields();
// A restored snapshot already holds the rows the last load produced, so a tab
// switch must not re-issue the collection query (#8679). Refresh and every
// mutation path still force a real load.
diff --git a/apps/desktop/src/components/editor/QueryEditor.vue b/apps/desktop/src/components/editor/QueryEditor.vue
index 69f2829257..a62050d26a 100644
--- a/apps/desktop/src/components/editor/QueryEditor.vue
+++ b/apps/desktop/src/components/editor/QueryEditor.vue
@@ -270,7 +270,7 @@ function sqlBehaviorDialect(): "mysql" | "postgres" | "sqlserver" | undefined {
function queryEditorSelectionLanguage(): "sql" | "text" {
const databaseType = props.databaseType;
- return databaseType === "redis" || databaseType === "mongodb" || databaseType === "elasticsearch" || databaseType === "easysearch" || databaseType === "meilisearch" || databaseType === "victoriametrics" ? "text" : "sql";
+ return databaseType === "redis" || databaseType === "mongodb" || databaseType === "elasticsearch" || databaseType === "easysearch" || databaseType === "meilisearch" || databaseType === "solr" || databaseType === "victoriametrics" ? "text" : "sql";
}
const COMPLETION_REMOTE_LATENCY_BUDGET_MS = 120;
@@ -3902,7 +3902,7 @@ async function refreshSemanticDiagnostics(options: { preserveOutsideRanges?: boo
setSemanticDiagnostics([]);
return;
}
- if (props.databaseType === "elasticsearch" || props.databaseType === "easysearch" || props.databaseType === "meilisearch" || props.databaseType === "victoriametrics") {
+ if (props.databaseType === "elasticsearch" || props.databaseType === "easysearch" || props.databaseType === "meilisearch" || props.databaseType === "solr" || props.databaseType === "victoriametrics") {
setSemanticDiagnostics([]);
return;
}
@@ -4955,7 +4955,7 @@ function localCompletionSchemasForDatabaseDisambiguation(completionContext: Retu
}
function shouldInsertSqlCompletionSpace(): boolean {
- return props.databaseType !== "mongodb" && props.databaseType !== "redis" && props.databaseType !== "elasticsearch" && props.databaseType !== "easysearch" && props.databaseType !== "meilisearch" && props.databaseType !== "victoriametrics";
+ return props.databaseType !== "mongodb" && props.databaseType !== "redis" && props.databaseType !== "elasticsearch" && props.databaseType !== "easysearch" && props.databaseType !== "meilisearch" && props.databaseType !== "solr" && props.databaseType !== "victoriametrics";
}
// Snippet expansion normally follows from the item type; a provider can also
@@ -5196,7 +5196,7 @@ async function provideSqlCompletions(context: CompletionContext) {
if (props.databaseType === "mongodb") {
return provideMongoCompletions(currentState, position, explicit);
}
- if (props.databaseType === "meilisearch") return null;
+ if (props.databaseType === "meilisearch" || props.databaseType === "solr") return null;
if (props.databaseType === "elasticsearch" || props.databaseType === "easysearch") {
if (!isSqlLikeCompletionStatement(fullDoc, position, sqlCompletionDialectOptions())) {
return provideElasticsearchCompletions(currentState, position, explicit);
@@ -5571,7 +5571,7 @@ function shouldStartSqlCompletionAfterInput(insertedText: string, removedText: s
if (props.databaseType === "mongodb") {
return !!(insertedText || removedText) && shouldAutoOpenMongoCompletion(fullDoc, position);
}
- if (props.databaseType === "victoriametrics" || props.databaseType === "meilisearch") return false;
+ if (props.databaseType === "victoriametrics" || props.databaseType === "meilisearch" || props.databaseType === "solr") return false;
if (props.databaseType === "redis" || props.databaseType === "elasticsearch" || props.databaseType === "easysearch") {
// Preserve old character-based checks for non-SQL providers.
if (!insertedText && removedText) {
diff --git a/apps/desktop/src/components/export/DatabaseExportDialog.vue b/apps/desktop/src/components/export/DatabaseExportDialog.vue
index bfce98ebb6..51d32e5efa 100644
--- a/apps/desktop/src/components/export/DatabaseExportDialog.vue
+++ b/apps/desktop/src/components/export/DatabaseExportDialog.vue
@@ -115,7 +115,7 @@ const exportElapsedText = computed(() => {
return formatDataTransferDuration((exportFinishedAt.value ?? currentTime.value) - exportStartedAt.value);
});
-const sqlConnections = computed(() => store.connections.filter((c) => !["redis", "mongodb", "elasticsearch", "easysearch", "meilisearch", "qdrant", "milvus", "weaviate", "chromadb", "etcd", "zookeeper", "consul", "mq", "nacos"].includes(c.db_type)));
+const sqlConnections = computed(() => store.connections.filter((c) => !["redis", "mongodb", "elasticsearch", "easysearch", "meilisearch", "solr", "qdrant", "milvus", "weaviate", "chromadb", "etcd", "zookeeper", "consul", "mq", "nacos"].includes(c.db_type)));
const canExport = computed(() => {
const hasContent = includeStructure.value || includeData.value || includeObjects.value;
diff --git a/apps/desktop/src/components/icons/DatabaseIcon.vue b/apps/desktop/src/components/icons/DatabaseIcon.vue
index fe60885964..741f1ed90f 100644
--- a/apps/desktop/src/components/icons/DatabaseIcon.vue
+++ b/apps/desktop/src/components/icons/DatabaseIcon.vue
@@ -31,6 +31,7 @@ const assetIcons: Record<string, string> = {
elasticsearch: "elasticsearch",
easysearch: "easysearch",
meilisearch: "meilisearch",
+ solr: "solr",
oracle: "oracle",
"oracle-10g": "oracle",
"oracle-legacy": "oracle",
@@ -135,7 +136,7 @@ const assetSrc = computed(() => {
</script>
<template>
- <img v-if="assetName" :src="assetSrc" alt="" class="database-logo object-contain" :class="{ 'database-logo-light': useLightIconInDarkMode, 'database-logo-impala': normalizedType === 'impala' }" aria-hidden="true" />
+ <img v-if="assetName" :src="assetSrc" alt="" class="database-logo object-contain" :class="{ 'database-logo-light': useLightIconInDarkMode, 'database-logo-impala': normalizedType === 'impala', 'database-logo-solr': normalizedType === 'solr' }" aria-hidden="true" />
<Database v-else class="text-blue-400" />
</template>
@@ -152,4 +153,10 @@ const assetSrc = computed(() => {
.database-logo-impala {
transform: scale(1.55);
}
+
+/* solr.svg 的图形撑满整个 viewBox(无内边距),其他 logo 留白约 20-25%,
+ 统一 scale(1.35) 下视觉偏大,单独收敛到与多数 logo 一致的占幅。 */
+.database-logo-solr {
+ transform: scale(1.02);
+}
</style>
diff --git a/apps/desktop/src/components/layout/ContentArea.vue b/apps/desktop/src/components/layout/ContentArea.vue
index 8ea28b0762..c66e81129e 100644
--- a/apps/desktop/src/components/layout/ContentArea.vue
+++ b/apps/desktop/src/components/layout/ContentArea.vue
@@ -129,6 +129,7 @@ const DamengJobAdmin = defineAsyncComponent(() => import("@/components/admin/Dam
const DamengUserAdmin = defineAsyncComponent(() => import("@/components/admin/DamengUserAdmin.vue"));
const DamengRoleAdmin = defineAsyncComponent(() => import("@/components/admin/DamengRoleAdmin.vue"));
+const SolrAdmin = defineAsyncComponent(() => import("@/components/solr/SolrAdmin.vue"));
const PluginFilesystemTab = defineAsyncComponent(() => import("@/components/plugins/PluginFilesystemTab.vue"));
const ExplainPlanViewer = defineAsyncComponent(() => import("@/components/explain/ExplainPlanViewer.vue"));
const QueryChart = defineAsyncComponent(() => import("@/components/chart/QueryChart.vue"));
@@ -505,7 +506,7 @@ const activeStatementExecutionMarkers = computed(() =>
const activeElasticsearchJsonResponse = computed(() => elasticsearchJsonResponseForResult(activeEffectiveDatabaseType.value, activeResultSql.value, props.activeTab.result));
/** Whether the active result is an Elasticsearch _source table that also has a raw JSON toggle. */
const activeElasticsearchRawBody = computed(() => {
- if (activeEffectiveDatabaseType.value !== "elasticsearch" && activeEffectiveDatabaseType.value !== "easysearch") return undefined;
+ if (activeEffectiveDatabaseType.value !== "elasticsearch" && activeEffectiveDatabaseType.value !== "easysearch" && activeEffectiveDatabaseType.value !== "solr") return undefined;
return props.activeTab.result?.elasticsearch_raw_body;
});
/** ES `_search?profile=true` body extracted from the active result, when present. */
@@ -2863,6 +2864,12 @@ defineExpose({
</div>
</template>
+ <template v-else-if="activeTab.mode === 'solr-admin'">
+ <div class="min-h-0 flex-1">
+ <SolrAdmin :key="activeTab.id" :connection-id="activeTab.connectionId" />
+ </div>
+ </template>
+
<template v-else-if="activeTab.mode === 'dolt-version-control'">
<div class="min-h-0 flex-1">
<DoltVersionControl :key="activeTab.id" :connection-id="activeTab.connectionId" :database="activeTab.database" :initial-branch="activeTab.workspaceBranch" />
diff --git a/apps/desktop/src/components/layout/EditorToolbar.vue b/apps/desktop/src/components/layout/EditorToolbar.vue
index 6b90c748ad..27bf9d920f 100644
--- a/apps/desktop/src/components/layout/EditorToolbar.vue
+++ b/apps/desktop/src/components/layout/EditorToolbar.vue
@@ -209,6 +209,7 @@ const supportsExplain = computed(() => {
dbType !== "elasticsearch" &&
dbType !== "easysearch" &&
dbType !== "meilisearch" &&
+ dbType !== "solr" &&
dbType !== "qdrant" &&
dbType !== "milvus" &&
dbType !== "weaviate" &&
@@ -758,6 +759,7 @@ async function changeCatalog(selectedCatalog: string) {
activeConnection?.db_type !== 'elasticsearch' &&
activeConnection?.db_type !== 'easysearch' &&
activeConnection?.db_type !== 'meilisearch' &&
+ activeConnection?.db_type !== 'solr' &&
activeConnection?.db_type !== 'qdrant' &&
activeConnection?.db_type !== 'milvus' &&
activeConnection?.db_type !== 'weaviate' &&
diff --git a/apps/desktop/src/components/sidebar/ConnectionTree.vue b/apps/desktop/src/components/sidebar/ConnectionTree.vue
index 89cc5995ac..0720c6dbe8 100644
--- a/apps/desktop/src/components/sidebar/ConnectionTree.vue
+++ b/apps/desktop/src/components/sidebar/ConnectionTree.vue
@@ -1747,7 +1747,7 @@ async function ensureTreeLoadedForTarget(target: ActiveTabSidebarTarget, opts?:
await store.loadMongoDatabases(connId);
} else if (config.db_type === "dynamodb") {
await store.loadDynamoDbTables(connId);
- } else if (config.db_type === "elasticsearch" || config.db_type === "easysearch" || config.db_type === "meilisearch") {
+ } else if (config.db_type === "elasticsearch" || config.db_type === "easysearch" || config.db_type === "meilisearch" || config.db_type === "solr") {
await store.loadElasticsearchIndices(connId);
} else if (config.db_type === "qdrant" || config.db_type === "milvus" || config.db_type === "weaviate" || config.db_type === "chromadb") {
await store.loadVectorCollections(connId);
diff --git a/apps/desktop/src/components/sidebar/SidebarTreeRuntimeHost.vue b/apps/desktop/src/components/sidebar/SidebarTreeRuntimeHost.vue
index acd50ed9d0..89eb0999d7 100644
--- a/apps/desktop/src/components/sidebar/SidebarTreeRuntimeHost.vue
+++ b/apps/desktop/src/components/sidebar/SidebarTreeRuntimeHost.vue
@@ -967,8 +967,8 @@ async function toggle(requestId = beginNavigationRequest()) {
await connectionStore.loadMongoDatabases(node.connectionId);
} else if (config?.db_type === "dynamodb") {
await connectionStore.loadDynamoDbTables(node.connectionId);
- } else if (config?.db_type === "elasticsearch" || config?.db_type === "easysearch" || config?.db_type === "meilisearch") {
- // Expand: list indices (like other db types list databases).
+ } else if (config?.db_type === "elasticsearch" || config?.db_type === "easysearch" || config?.db_type === "meilisearch" || config?.db_type === "solr") {
+ // Expand: list indices/cores (like other db types list databases).
await connectionStore.loadElasticsearchIndices(node.connectionId);
} else if (config?.db_type === "milvus") {
await connectionStore.loadMilvusDatabases(node.connectionId);
@@ -1826,6 +1826,8 @@ async function openServerDashboard() {
connectionStore.activeConnectionId = node.connectionId;
if (currentDatabaseType() === "nacos") {
queryStore.openNacosDashboard(node.connectionId);
+ } else if (currentDatabaseType() === "solr") {
+ queryStore.openSolrAdmin(node.connectionId);
} else if (connectionSupportsXuguServerDashboard(connectionStore.getConfig(node.connectionId))) {
queryStore.openXuguDashboard(node.connectionId);
} else if (connectionSupportsPgServerDashboard(connectionStore.getConfig(node.connectionId))) {
@@ -4686,7 +4688,7 @@ const canOpenSqlFileExecution = computed(() => {
const canExportAllDatabases = computed(() => {
if (activeNode.value.type !== "connection" || !activeNode.value.connectionId) return false;
const dbType = connectionStore.getConfig(activeNode.value.connectionId)?.db_type;
- return !["redis", "mongodb", "dynamodb", "elasticsearch", "easysearch", "meilisearch", "qdrant", "milvus", "weaviate", "chromadb", "etcd", "zookeeper", "consul", "mq", "nacos", "plugin"].includes(dbType || "");
+ return !["redis", "mongodb", "dynamodb", "elasticsearch", "easysearch", "solr", "meilisearch", "qdrant", "milvus", "weaviate", "chromadb", "etcd", "zookeeper", "consul", "mq", "nacos", "plugin"].includes(dbType || "");
});
const canOpenScheduledBackups = computed(() => {
@@ -5597,7 +5599,11 @@ function buildConnectionSidebarMenu(context: SidebarMenuFactoryContext): boolean
}
if (
node.connectionId &&
- (currentDatabaseType() === "nacos" || connectionSupportsXuguServerDashboard(connectionStore.getConfig(node.connectionId)) || connectionSupportsServerDashboard(connectionStore.getConfig(node.connectionId)) || connectionSupportsPgServerDashboard(connectionStore.getConfig(node.connectionId)))
+ (currentDatabaseType() === "nacos" ||
+ currentDatabaseType() === "solr" ||
+ connectionSupportsXuguServerDashboard(connectionStore.getConfig(node.connectionId)) ||
+ connectionSupportsServerDashboard(connectionStore.getConfig(node.connectionId)) ||
+ connectionSupportsPgServerDashboard(connectionStore.getConfig(node.connectionId)))
) {
items.push({ label: t("contextMenu.serverDashboard"), action: openServerDashboard, icon: Gauge });
}
diff --git a/apps/desktop/src/components/solr/SolrAdmin.vue b/apps/desktop/src/components/solr/SolrAdmin.vue
new file mode 100644
index 0000000000..63b0bb9188
--- /dev/null
+++ b/apps/desktop/src/components/solr/SolrAdmin.vue
@@ -0,0 +1,1394 @@
+<script setup lang="ts">
+import { computed, onMounted, ref } from "vue";
+import { useI18n } from "vue-i18n";
+import { Activity, AlertTriangle, Boxes, Database, FileText, Gauge, Layers, Loader2, Network, Play, Plus, RefreshCcw, ScrollText, Search, Settings2, Shuffle, Trash2 } from "@lucide/vue";
+import { Button } from "@/components/ui/button";
+import { Badge } from "@/components/ui/badge";
+import { Input } from "@/components/ui/input";
+import { Label } from "@/components/ui/label";
+import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
+import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog";
+import JsonTree from "@/components/common/JsonTree.vue";
+import { useToast } from "@/composables/useToast";
+import { useConnectionStore } from "@/stores/connectionStore";
+import { useQueryStore } from "@/stores/queryStore";
+import { executeQuery } from "@/lib/backend/api";
+import type { QueryResult } from "@/types/database";
+import {
+ buildSolrQuery,
+ defaultSolrQueryForm,
+ parseAnalysisResponse,
+ parseCoreStatus,
+ parseIndexStats,
+ parseParamsetNames,
+ parseReplicationDetails,
+ parseServerCwd,
+ parseSolrNumFound,
+ parseSolrSchema,
+ parseSolrSystemInfo,
+ solrReleaseAgeDays,
+ solrAdminErrorMessage,
+ solrAdminGet,
+ solrAdminPath,
+ solrAdminViewById,
+ solrAnalysisPath,
+ solrCoreAdminRequest,
+ solrReplicationCommand,
+ SOLR_ADMIN_CORE_VIEWS,
+ SOLR_ADMIN_SERVER_VIEWS,
+ type SolrAdminResponse,
+ type SolrAdminViewDef,
+ type SolrAdminViewId,
+ type SolrAnalysisResult,
+ type SolrCoreStatus,
+ type SolrIndexStats,
+ type SolrQueryParam,
+ type SolrReplicationDetails,
+} from "@/lib/solr/solrAdmin";
+
+const props = defineProps<{
+ connectionId: string;
+}>();
+
+const { t } = useI18n();
+const { toast } = useToast();
+const connectionStore = useConnectionStore();
+const queryStore = useQueryStore();
+
+const VIEW_ICONS: Record<SolrAdminViewId, typeof Gauge> = {
+ dashboard: Gauge,
+ logging: ScrollText,
+ javaProps: Settings2,
+ threads: Activity,
+ coreAdmin: Boxes,
+ metrics: Gauge,
+ overview: Layers,
+ analysis: Search,
+ documents: FileText,
+ paramsets: Settings2,
+ files: FileText,
+ ping: Activity,
+ plugins: Boxes,
+ query: Play,
+ replication: Network,
+ schema: Database,
+ segments: Layers,
+};
+
+const activeViewId = ref<SolrAdminViewId>("dashboard");
+const activeView = computed<SolrAdminViewDef>(() => solrAdminViewById(activeViewId.value) ?? SOLR_ADMIN_SERVER_VIEWS[0]);
+
+const cores = ref<SolrCoreStatus[]>([]);
+const selectedCore = ref("");
+const loading = ref(false);
+const error = ref("");
+const response = ref<SolrAdminResponse | null>(null);
+
+const connectionName = computed(() => connectionStore.getConfig(props.connectionId)?.name ?? "");
+const coreNames = computed(() => cores.value.map((core) => core.name));
+
+const responseBody = computed(() => response.value?.body ?? null);
+const systemInfo = computed(() => parseSolrSystemInfo(responseBody.value));
+const solrReleaseOld = computed(() => {
+ const days = solrReleaseAgeDays(systemInfo.value.solrImpl);
+ return days != null && days > 365;
+});
+
+function barPct(pct?: number): string {
+ return `${Math.min(100, Math.max(0, pct ?? 0)).toFixed(1)}%`;
+}
+
+const propertyEntries = computed(() => {
+ const body = responseBody.value;
+ const props_ = (body as Record<string, unknown> | null)?.["system.properties"];
+ if (!props_ || typeof props_ !== "object" || Array.isArray(props_)) return [];
+ return Object.entries(props_ as Record<string, unknown>)
+ .map(([key, value]) => ({ key, value: String(value) }))
+ .sort((a, b) => a.key.localeCompare(b.key));
+});
+
+const loggingLevels = computed(() => {
+ const body = responseBody.value;
+ const levels = (body as Record<string, unknown> | null)?.loggers;
+ if (!Array.isArray(levels)) return [];
+ return levels
+ .filter((entry): entry is Record<string, unknown> => !!entry && typeof entry === "object" && !Array.isArray(entry))
+ .map((entry) => ({ name: String(entry.name ?? ""), level: String(entry.level ?? ""), set: entry.set === true }))
+ .sort((a, b) => a.name.localeCompare(b.name));
+});
+
+/* ---------- Overview(官方 UI 组合视图:luke index + STATUS + replication + ping + user.dir) ---------- */
+
+const overviewStats = ref<SolrIndexStats | null>(null);
+const overviewReplication = ref<SolrReplicationDetails | null>(null);
+const overviewPingStatus = ref("");
+const overviewCwd = ref("");
+
+async function loadOverview() {
+ const core = selectedCore.value;
+ if (!core) return;
+ loading.value = true;
+ error.value = "";
+ overviewStats.value = null;
+ overviewReplication.value = null;
+ overviewPingStatus.value = "";
+ overviewCwd.value = "";
+ const enc = encodeURIComponent(core);
+ const [lukeRes, replRes, pingRes, propsRes] = await Promise.allSettled([
+ solrAdminGet(props.connectionId, `/${enc}/admin/luke?show=index`),
+ solrAdminGet(props.connectionId, `/${enc}/replication?command=details`),
+ solrAdminGet(props.connectionId, `/${enc}/admin/ping`),
+ solrAdminGet(props.connectionId, "/admin/info/properties"),
+ ]);
+ loading.value = false;
+ // luke 是 Statistics/Impl 的主数据源,失败则整页报错;其余块允许局部降级
+ if (lukeRes.status === "rejected") {
+ error.value = String(lukeRes.reason?.message ?? lukeRes.reason);
+ return;
+ }
+ response.value = lukeRes.value;
+ overviewStats.value = parseIndexStats(lukeRes.value.body);
+ overviewReplication.value = replRes.status === "fulfilled" ? parseReplicationDetails(replRes.value.body) : null;
+ if (pingRes.status === "fulfilled") {
+ const status = (pingRes.value.body as Record<string, unknown> | null)?.status;
+ overviewPingStatus.value = typeof status === "string" ? status : "";
+ }
+ overviewCwd.value = propsRes.status === "fulfilled" ? (parseServerCwd(propsRes.value.body) ?? "") : "";
+}
+
+const overviewInstanceRows = computed(() => {
+ const core = cores.value.find((c) => c.name === selectedCore.value);
+ const rows = [
+ { key: "cwd", value: overviewCwd.value },
+ { key: "instanceDir", value: core?.instanceDir },
+ { key: "data", value: core?.dataDir },
+ { key: "index", value: overviewReplication.value?.indexPath },
+ { key: "impl", value: overviewStats.value?.directoryImpl },
+ ];
+ return rows.filter((row) => row.value);
+});
+
+function replicationRows(r: SolrReplicationDetails | null) {
+ if (!r?.isLeader) return [];
+ return [
+ { label: t("solrAdmin.overview.leaderSearching"), version: r.indexVersion ?? "-", gen: r.generation ?? "-", size: r.indexSize ?? "-" },
+ { label: t("solrAdmin.overview.leaderReplicable"), version: r.replicableVersion ?? "-", gen: r.replicableGeneration ?? "-", size: "-" },
+ ];
+}
+
+const overviewReplicationRows = computed(() => replicationRows(overviewReplication.value));
+
+/* ---------- Replication 视图(官方布局:操作按钮 + Index 表 + Settings) ---------- */
+
+const replicationDetails = ref<SolrReplicationDetails | null>(null);
+const replicationRowsComputed = computed(() => replicationRows(replicationDetails.value));
+
+async function loadReplication() {
+ const core = selectedCore.value;
+ if (!core) return;
+ loading.value = true;
+ error.value = "";
+ try {
+ const res = await solrAdminGet(props.connectionId, `/${encodeURIComponent(core)}/replication?command=details`);
+ response.value = res;
+ replicationDetails.value = parseReplicationDetails(res.body);
+ } catch (e: any) {
+ error.value = String(e?.message ?? e);
+ response.value = null;
+ } finally {
+ loading.value = false;
+ }
+}
+
+function relativeTime(iso?: string): string {
+ if (!iso) return "-";
+ const t0 = Date.parse(iso);
+ if (!Number.isFinite(t0)) return iso;
+ const sec = Math.max(0, Math.floor((Date.now() - t0) / 1000));
+ if (sec < 60) return t("solrAdmin.overview.justNow");
+ const min = Math.floor(sec / 60);
+ if (min < 60) return t("solrAdmin.overview.minutesAgo", { n: min });
+ const hours = Math.floor(min / 60);
+ if (hours < 48) return t("solrAdmin.overview.hoursAgo", { n: hours });
+ return t("solrAdmin.overview.daysAgo", { n: Math.floor(hours / 24) });
+}
+
+const schemaInfo = computed(() => parseSolrSchema(responseBody.value));
+const segmentEntries = computed(() => {
+ const body = responseBody.value;
+ const segments = (body as Record<string, unknown> | null)?.segments;
+ if (!segments || typeof segments !== "object" || Array.isArray(segments)) return [];
+ return Object.entries(segments as Record<string, Record<string, unknown>>)
+ .map(([name, info]) => ({
+ name,
+ numDocs: info?.numDocs,
+ delDocs: info?.delDocs ?? info?.deletedDocs,
+ sizeInBytes: info?.sizeInBytes ?? info?.size,
+ age: info?.age,
+ source: info?.source,
+ }))
+ .sort((a, b) => b.name.localeCompare(a.name));
+});
+
+const pingResult = computed(() => {
+ const body = responseBody.value;
+ if (!body || typeof body !== "object" || Array.isArray(body)) return null;
+ const root = body as Record<string, unknown>;
+ const header = (root.responseHeader ?? {}) as Record<string, unknown>;
+ return { status: String(root.status ?? ""), qtime: typeof header.QTime === "number" ? header.QTime : undefined };
+});
+
+async function loadCores() {
+ try {
+ const res = await solrAdminGet(props.connectionId, "/admin/cores?action=STATUS");
+ cores.value = parseCoreStatus(res.body);
+ if (!selectedCore.value && cores.value.length) selectedCore.value = cores.value[0].name;
+ } catch {
+ // core 列表失败不阻塞 server 视图;selector 为空时 core 视图提示选择
+ }
+}
+
+async function load() {
+ const view = activeView.value;
+ if (view.view === "action") return;
+ if (view.view === "overview") {
+ await loadOverview();
+ return;
+ }
+ if (view.view === "replication") {
+ await loadReplication();
+ return;
+ }
+ if (view.view === "queryForm") {
+ // core 切换后 paramset 列表过期,结果属于旧 core,一并清掉
+ queryResult.value = null;
+ await loadParamsets();
+ return;
+ }
+ if (view.scope === "core" && !selectedCore.value) {
+ response.value = null;
+ return;
+ }
+ loading.value = true;
+ error.value = "";
+ try {
+ response.value = await solrAdminGet(props.connectionId, solrAdminPath(view, selectedCore.value));
+ } catch (e: any) {
+ error.value = String(e?.message ?? e);
+ response.value = null;
+ } finally {
+ loading.value = false;
+ }
+}
+
+function selectView(id: SolrAdminViewId) {
+ if (id === "documents") {
+ openDocuments();
+ return;
+ }
+ activeViewId.value = id;
+ if (id === "query") {
+ loadParamsets();
+ return;
+ }
+ load();
+}
+
+function openDocuments() {
+ if (!selectedCore.value) return;
+ const tab = queryStore.createTab(props.connectionId, "default", selectedCore.value, "mongo");
+ queryStore.updateSql(tab, selectedCore.value);
+}
+
+/* ---------- Query Builder(对标官方 Admin UI Query 表单) ---------- */
+
+const queryForm = ref(defaultSolrQueryForm());
+const paramsetNames = ref<string[]>([]);
+const queryRunning = ref(false);
+const queryError = ref("");
+const queryResult = ref<QueryResult | null>(null);
+const queryShowRaw = ref(false);
+
+const builtQuery = computed(() => buildSolrQuery(selectedCore.value, queryForm.value));
+const queryNumFound = computed(() => parseSolrNumFound(queryResult.value?.elasticsearch_raw_body ?? ""));
+const queryRawBody = computed(() => queryResult.value?.elasticsearch_raw_body ?? "");
+const queryRawParsed = computed(() => {
+ if (!queryRawBody.value) return null;
+ try {
+ return JSON.parse(queryRawBody.value);
+ } catch {
+ return queryRawBody.value;
+ }
+});
+
+async function loadParamsets() {
+ if (!selectedCore.value) {
+ paramsetNames.value = [];
+ return;
+ }
+ try {
+ const res = await solrAdminGet(props.connectionId, `/${encodeURIComponent(selectedCore.value)}/config/params`);
+ paramsetNames.value = parseParamsetNames(res.body);
+ } catch {
+ paramsetNames.value = [];
+ }
+}
+
+function toggleParamset(name: string) {
+ const list = queryForm.value.useParams;
+ const i = list.indexOf(name);
+ if (i >= 0) list.splice(i, 1);
+ else list.push(name);
+}
+
+function addQueryRow(list: string[] | SolrQueryParam[], empty: string | SolrQueryParam) {
+ (list as Array<string | SolrQueryParam>).push(empty);
+}
+
+function removeQueryRow(list: unknown[], index: number) {
+ list.splice(index, 1);
+}
+
+async function runQueryForm() {
+ if (!selectedCore.value) return;
+ // JSON 模式先本地校验,非法 JSON 直接提示不发请求
+ if (builtQuery.value.jsonMode) {
+ try {
+ JSON.parse(queryForm.value.jsonQuery);
+ } catch (e) {
+ queryError.value = `Invalid JSON: ${String((e as Error)?.message ?? e)}`;
+ return;
+ }
+ }
+ queryRunning.value = true;
+ queryError.value = "";
+ try {
+ queryResult.value = await executeQuery(props.connectionId, "", builtQuery.value.text);
+ queryShowRaw.value = false;
+ } catch (e: any) {
+ queryError.value = String(e?.message ?? e);
+ queryResult.value = null;
+ } finally {
+ queryRunning.value = false;
+ }
+}
+
+function openQueryInConsole() {
+ const core = selectedCore.value;
+ queryStore.createTab(props.connectionId, "default", core ? `${core} - query` : "solr query", "query", undefined, builtQuery.value.text);
+}
+
+function queryCellText(value: unknown): string {
+ if (value == null) return "null";
+ if (typeof value === "object") return JSON.stringify(value);
+ return String(value);
+}
+
+/* ---------- Analysis ---------- */
+
+const analysisField = ref("");
+const analysisText = ref("");
+const analysisQuery = ref("");
+const analysisLoading = ref(false);
+const analysisError = ref("");
+const analysisResult = ref<SolrAnalysisResult | null>(null);
+
+async function runAnalysis() {
+ if (!selectedCore.value || !analysisField.value.trim() || !analysisText.value) return;
+ analysisLoading.value = true;
+ analysisError.value = "";
+ try {
+ const res = await solrAdminGet(props.connectionId, solrAnalysisPath(selectedCore.value, analysisField.value.trim(), analysisText.value, analysisQuery.value || undefined));
+ analysisResult.value = parseAnalysisResponse(res.body, analysisField.value.trim());
+ } catch (e: any) {
+ analysisError.value = String(e?.message ?? e);
+ analysisResult.value = null;
+ } finally {
+ analysisLoading.value = false;
+ }
+}
+
+/* ---------- Core Admin actions ---------- */
+
+const actionPending = ref(false);
+type CoreActionId = "RELOAD" | "UNLOAD" | "RENAME" | "SWAP" | "DISABLE_REPLICATION" | "ENABLE_REPLICATION";
+const confirmAction = ref<{ action: CoreActionId; core: string; label: string } | null>(null);
+const renameTarget = ref("");
+const swapTarget = ref("");
+const createOpen = ref(false);
+const createName = ref("");
+const createConfigSet = ref("_default");
+const createInstanceDir = ref("");
+
+function askCoreAction(action: CoreActionId, core: string) {
+ renameTarget.value = "";
+ swapTarget.value = "";
+ confirmAction.value = { action, core, label: t(`solrAdmin.actions.${action.toLowerCase()}`) };
+}
+
+function askReplicationToggle() {
+ if (!selectedCore.value || !replicationDetails.value) return;
+ const disabling = replicationDetails.value.replicationEnabled !== false;
+ confirmAction.value = {
+ action: disabling ? "DISABLE_REPLICATION" : "ENABLE_REPLICATION",
+ core: selectedCore.value,
+ label: t(disabling ? "solrAdmin.replication.disable" : "solrAdmin.replication.enable"),
+ };
+}
+
+async function runCoreAction() {
+ const pending = confirmAction.value;
+ if (!pending) return;
+ actionPending.value = true;
+ try {
+ if (pending.action === "DISABLE_REPLICATION" || pending.action === "ENABLE_REPLICATION") {
+ const command = pending.action === "DISABLE_REPLICATION" ? "disablereplication" : "enablereplication";
+ const res = await solrReplicationCommand(props.connectionId, pending.core, command);
+ const failed = solrAdminErrorMessage(res);
+ if (failed) throw new Error(failed);
+ toast(t("solrAdmin.actions.success", { action: pending.label, core: pending.core }), 3000);
+ confirmAction.value = null;
+ await loadReplication();
+ return;
+ }
+ const params: Record<string, string> = { action: pending.action };
+ if (pending.action === "SWAP") {
+ params.core = pending.core;
+ params.other = swapTarget.value;
+ } else if (pending.action === "RENAME") {
+ params.core = pending.core;
+ params.other = renameTarget.value;
+ } else {
+ params.core = pending.core;
+ }
+ const res = await solrCoreAdminRequest(props.connectionId, params);
+ const failed = solrAdminErrorMessage(res);
+ if (failed) throw new Error(failed);
+ toast(t("solrAdmin.actions.success", { action: pending.label, core: pending.core }), 3000);
+ confirmAction.value = null;
+ await loadCores();
+ if (activeViewId.value === "coreAdmin") await load();
+ } catch (e: any) {
+ toast(t("solrAdmin.actions.failed", { message: String(e?.message ?? e) }), 5000);
+ } finally {
+ actionPending.value = false;
+ }
+}
+
+async function runCreateCore() {
+ const name = createName.value.trim();
+ if (!name) return;
+ actionPending.value = true;
+ try {
+ const params: Record<string, string> = { action: "CREATE", name, configSet: createConfigSet.value.trim() || "_default" };
+ if (createInstanceDir.value.trim()) params.instanceDir = createInstanceDir.value.trim();
+ const res = await solrCoreAdminRequest(props.connectionId, params);
+ const failed = solrAdminErrorMessage(res);
+ if (failed) throw new Error(failed);
+ toast(t("solrAdmin.actions.success", { action: t("solrAdmin.actions.create"), core: name }), 3000);
+ createOpen.value = false;
+ createName.value = "";
+ createInstanceDir.value = "";
+ await loadCores();
+ if (activeViewId.value === "coreAdmin") await load();
+ } catch (e: any) {
+ toast(t("solrAdmin.actions.failed", { message: String(e?.message ?? e) }), 5000);
+ } finally {
+ actionPending.value = false;
+ }
+}
+
+function formatBytes(value: unknown): string {
+ const bytes = typeof value === "number" ? value : Number(value);
+ if (!Number.isFinite(bytes) || bytes < 0) return "-";
+ const units = ["B", "KB", "MB", "GB", "TB"];
+ let size = bytes;
+ let unit = 0;
+ while (size >= 1024 && unit < units.length - 1) {
+ size /= 1024;
+ unit += 1;
+ }
+ return `${size.toFixed(unit === 0 ? 0 : 1)} ${units[unit]}`;
+}
+
+function formatUptime(ms: unknown): string {
+ const total = typeof ms === "number" ? ms : Number(ms);
+ if (!Number.isFinite(total) || total < 0) return "-";
+ const seconds = Math.floor(total / 1000);
+ const days = Math.floor(seconds / 86400);
+ const hours = Math.floor((seconds % 86400) / 3600);
+ const minutes = Math.floor((seconds % 3600) / 60);
+ if (days) return `${days}d ${hours}h`;
+ if (hours) return `${hours}h ${minutes}m`;
+ if (minutes) return `${minutes}m ${seconds % 60}s`;
+ return `${seconds}s`;
+}
+
+onMounted(async () => {
+ await loadCores();
+ await load();
+});
+</script>
+
+<template>
+ <div class="flex h-full min-h-0 flex-col bg-background">
+ <div class="flex items-center gap-3 border-b px-4 py-2">
+ <Gauge class="h-4 w-4 text-muted-foreground" />
+ <span class="text-sm font-medium">Solr Admin</span>
+ <span v-if="connectionName" class="text-xs text-muted-foreground">{{ connectionName }}</span>
+ <div class="ml-auto flex items-center gap-2">
+ <Badge v-if="response" variant="outline" class="font-mono text-xs">HTTP {{ response.status }}</Badge>
+ <span v-if="response" class="text-xs text-muted-foreground">{{ response.elapsedMs }} ms</span>
+ <Button size="sm" variant="outline" :disabled="loading" @click="load">
+ <RefreshCcw class="mr-1.5 h-3.5 w-3.5" :class="{ 'animate-spin': loading }" />
+ {{ t("solrAdmin.refresh") }}
+ </Button>
+ </div>
+ </div>
+
+ <div class="flex min-h-0 flex-1">
+ <div class="w-44 shrink-0 overflow-y-auto border-r py-2">
+ <div class="px-3 pb-1 text-xs font-medium uppercase text-muted-foreground">{{ t("solrAdmin.sections.server") }}</div>
+ <button v-for="view in SOLR_ADMIN_SERVER_VIEWS" :key="view.id" class="flex w-full items-center gap-2 px-3 py-1.5 text-left text-sm hover:bg-accent" :class="{ 'bg-accent font-medium': activeViewId === view.id }" @click="selectView(view.id)">
+ <component :is="VIEW_ICONS[view.id]" class="h-3.5 w-3.5 text-muted-foreground" />
+ {{ t(`solrAdmin.views.${view.id}`) }}
+ </button>
+
+ <div class="mt-3 px-3 pb-1 text-xs font-medium uppercase text-muted-foreground">{{ t("solrAdmin.sections.core") }}</div>
+ <div class="px-3 pb-2">
+ <Select v-model="selectedCore" @update:model-value="activeView.scope === 'core' && load()">
+ <SelectTrigger class="h-7 w-full text-xs">
+ <SelectValue :placeholder="t('solrAdmin.selectCore')" />
+ </SelectTrigger>
+ <SelectContent>
+ <SelectItem v-for="name in coreNames" :key="name" :value="name">{{ name }}</SelectItem>
+ </SelectContent>
+ </Select>
+ </div>
+ <button v-for="view in SOLR_ADMIN_CORE_VIEWS" :key="view.id" class="flex w-full items-center gap-2 px-3 py-1.5 text-left text-sm hover:bg-accent disabled:opacity-50" :class="{ 'bg-accent font-medium': activeViewId === view.id }" :disabled="!selectedCore" @click="selectView(view.id)">
+ <component :is="VIEW_ICONS[view.id]" class="h-3.5 w-3.5 text-muted-foreground" />
+ {{ t(`solrAdmin.views.${view.id}`) }}
+ </button>
+ </div>
+
+ <div class="flex min-w-0 flex-1 flex-col">
+ <div class="border-b px-4 py-2 text-sm font-medium">{{ t(`solrAdmin.views.${activeView.id}`) }}</div>
+
+ <div v-if="activeView.scope === 'core' && !selectedCore" class="p-6 text-sm text-muted-foreground">
+ {{ t("solrAdmin.noCore") }}
+ </div>
+ <div v-else-if="error" class="flex items-start gap-2 p-4 text-sm text-destructive">
+ <AlertTriangle class="mt-0.5 h-4 w-4 shrink-0" />
+ <pre class="whitespace-pre-wrap font-mono text-xs">{{ error }}</pre>
+ </div>
+ <div v-else-if="loading && !response" class="flex flex-1 items-center justify-center">
+ <Loader2 class="h-5 w-5 animate-spin text-muted-foreground" />
+ </div>
+
+ <div v-else class="min-h-0 flex-1 overflow-y-auto p-4">
+ <!-- Dashboard(官方双栏:Instance / Versions / JVM + System/JVM-Memory 进度条) -->
+ <template v-if="activeView.view === 'dashboard'">
+ <div class="grid grid-cols-1 gap-3 xl:grid-cols-2">
+ <div class="space-y-3">
+ <!-- Instance -->
+ <div class="rounded border">
+ <div class="border-b bg-muted/30 px-3 py-1.5 text-xs font-medium text-muted-foreground">{{ t("solrAdmin.dashboard.instance") }}</div>
+ <table class="w-full text-sm">
+ <tbody>
+ <tr class="border-b last:border-0">
+ <td class="w-32 px-3 py-1.5 text-xs text-muted-foreground">{{ t("solrAdmin.dashboard.start") }}</td>
+ <td class="px-3 py-1.5 text-xs">
+ {{ relativeTime(systemInfo.startTime) }}<span v-if="systemInfo.uptimeMs" class="ml-2 text-muted-foreground">({{ formatUptime(systemInfo.uptimeMs) }})</span>
+ </td>
+ </tr>
+ <tr v-if="systemInfo.mode" class="border-b last:border-0">
+ <td class="w-32 px-3 py-1.5 text-xs text-muted-foreground">{{ t("solrAdmin.dashboard.mode") }}</td>
+ <td class="px-3 py-1.5 font-mono text-xs">{{ systemInfo.mode }}</td>
+ </tr>
+ <tr v-if="systemInfo.solrHome" class="border-b last:border-0">
+ <td class="w-32 px-3 py-1.5 text-xs text-muted-foreground">{{ t("solrAdmin.dashboard.solr_home") }}</td>
+ <td class="break-all px-3 py-1.5 font-mono text-xs">{{ systemInfo.solrHome }}</td>
+ </tr>
+ <tr v-if="systemInfo.coreRoot" class="border-b last:border-0">
+ <td class="w-32 px-3 py-1.5 text-xs text-muted-foreground">{{ t("solrAdmin.dashboard.core_root") }}</td>
+ <td class="break-all px-3 py-1.5 font-mono text-xs">{{ systemInfo.coreRoot }}</td>
+ </tr>
+ </tbody>
+ </table>
+ </div>
+
+ <!-- Versions -->
+ <div class="rounded border">
+ <div class="border-b bg-muted/30 px-3 py-1.5 text-xs font-medium text-muted-foreground">{{ t("solrAdmin.dashboard.versions") }}</div>
+ <table class="w-full text-sm">
+ <tbody>
+ <tr class="border-b last:border-0">
+ <td class="w-32 px-3 py-1.5 text-xs text-muted-foreground">solr-spec</td>
+ <td class="px-3 py-1.5 font-mono text-xs">{{ systemInfo.solrSpec ?? "-" }}</td>
+ </tr>
+ <tr class="border-b last:border-0">
+ <td class="w-32 px-3 py-1.5 text-xs text-muted-foreground">solr-impl</td>
+ <td class="break-all px-3 py-1.5 font-mono text-xs">{{ systemInfo.solrImpl ?? "-" }}</td>
+ </tr>
+ <tr class="border-b last:border-0">
+ <td class="w-32 px-3 py-1.5 text-xs text-muted-foreground">lucene-spec</td>
+ <td class="px-3 py-1.5 font-mono text-xs">{{ systemInfo.luceneSpec ?? "-" }}</td>
+ </tr>
+ <tr class="border-b last:border-0">
+ <td class="w-32 px-3 py-1.5 text-xs text-muted-foreground">lucene-impl</td>
+ <td class="break-all px-3 py-1.5 font-mono text-xs">{{ systemInfo.luceneImpl ?? "-" }}</td>
+ </tr>
+ </tbody>
+ </table>
+ <div v-if="solrReleaseOld" class="flex items-center gap-2 border-t px-3 py-2 text-xs text-amber-600">
+ <AlertTriangle class="h-3.5 w-3.5 shrink-0" />
+ {{ t("solrAdmin.dashboard.outdatedWarning") }}
+ </div>
+ </div>
+
+ <!-- JVM -->
+ <div class="rounded border">
+ <div class="border-b bg-muted/30 px-3 py-1.5 text-xs font-medium text-muted-foreground">{{ t("solrAdmin.dashboard.jvmTitle") }}</div>
+ <table class="w-full text-sm">
+ <tbody>
+ <tr class="border-b last:border-0">
+ <td class="w-32 px-3 py-1.5 text-xs text-muted-foreground">{{ t("solrAdmin.dashboard.runtime") }}</td>
+ <td class="break-all px-3 py-1.5 font-mono text-xs">{{ systemInfo.jvmRuntime ?? "-" }}</td>
+ </tr>
+ <tr class="border-b last:border-0">
+ <td class="w-32 px-3 py-1.5 text-xs text-muted-foreground">{{ t("solrAdmin.dashboard.processors") }}</td>
+ <td class="px-3 py-1.5 font-mono text-xs">{{ systemInfo.processors ?? "-" }}</td>
+ </tr>
+ <tr v-if="systemInfo.args.length" class="border-b last:border-0">
+ <td class="w-32 px-3 py-1.5 align-top text-xs text-muted-foreground">{{ t("solrAdmin.dashboard.args") }}</td>
+ <td class="break-all px-3 py-1.5 font-mono text-[11px] leading-relaxed">{{ systemInfo.args.join(" ") }}</td>
+ </tr>
+ </tbody>
+ </table>
+ </div>
+ </div>
+
+ <div class="space-y-3">
+ <!-- System -->
+ <div class="rounded border p-3">
+ <div class="mb-2 text-xs font-medium text-muted-foreground">{{ t("solrAdmin.dashboard.system") }}</div>
+ <div v-if="systemInfo.physMemUsedPct != null" class="mb-3">
+ <div class="mb-1 flex justify-between text-xs">
+ <span>{{ t("solrAdmin.dashboard.physMem") }}</span
+ ><span>{{ barPct(systemInfo.physMemUsedPct) }}</span>
+ </div>
+ <div class="h-2 overflow-hidden rounded bg-muted"><div class="h-full rounded bg-primary" :style="{ width: barPct(systemInfo.physMemUsedPct) }" /></div>
+ <div class="mt-0.5 text-right font-mono text-[10px] text-muted-foreground">{{ formatBytes(systemInfo.physMemUsed) }} / {{ formatBytes(systemInfo.physMemTotal) }}</div>
+ </div>
+ <div v-if="systemInfo.swapUsedPct != null" class="mb-3">
+ <div class="mb-1 flex justify-between text-xs">
+ <span>{{ t("solrAdmin.dashboard.swap") }}</span
+ ><span>{{ barPct(systemInfo.swapUsedPct) }}</span>
+ </div>
+ <div class="h-2 overflow-hidden rounded bg-muted"><div class="h-full rounded bg-primary" :style="{ width: barPct(systemInfo.swapUsedPct) }" /></div>
+ <div class="mt-0.5 text-right font-mono text-[10px] text-muted-foreground">{{ formatBytes(systemInfo.swapUsed) }} / {{ formatBytes(systemInfo.swapTotal) }}</div>
+ </div>
+ <div v-if="systemInfo.fdMax">
+ <div class="mb-1 flex justify-between text-xs">
+ <span>{{ t("solrAdmin.dashboard.fd") }}</span
+ ><span>{{ barPct((systemInfo.fdUsed! / systemInfo.fdMax) * 100) }}</span>
+ </div>
+ <div class="h-2 overflow-hidden rounded bg-muted"><div class="h-full rounded bg-primary" :style="{ width: barPct((systemInfo.fdUsed! / systemInfo.fdMax) * 100) }" /></div>
+ <div class="mt-0.5 text-right font-mono text-[10px] text-muted-foreground">{{ systemInfo.fdUsed ?? "-" }} / {{ systemInfo.fdMax }}</div>
+ </div>
+ </div>
+
+ <!-- JVM-Memory -->
+ <div class="rounded border p-3">
+ <div class="mb-1 flex justify-between text-xs">
+ <span class="font-medium text-muted-foreground">{{ t("solrAdmin.dashboard.jvmMemory") }}</span
+ ><span>{{ barPct(systemInfo.jvmMemUsedPct) }}</span>
+ </div>
+ <div class="h-2 overflow-hidden rounded bg-muted"><div class="h-full rounded bg-primary" :style="{ width: barPct(systemInfo.jvmMemUsedPct) }" /></div>
+ <div class="mt-0.5 text-right font-mono text-[10px] text-muted-foreground">{{ systemInfo.jvmMemUsed ?? "-" }} / {{ systemInfo.jvmMemTotal ?? "-" }}</div>
+ </div>
+ </div>
+ </div>
+ <div class="mt-4">
+ <JsonTree v-if="responseBody" :value="responseBody" :initial-expanded-depth="1" virtualized />
+ </div>
+ </template>
+
+ <!-- Java Properties -->
+ <table v-else-if="activeView.view === 'properties'" class="w-full text-sm">
+ <tbody>
+ <tr v-for="entry in propertyEntries" :key="entry.key" class="border-b last:border-0">
+ <td class="w-1/3 py-1 pr-4 font-mono text-xs">{{ entry.key }}</td>
+ <td class="break-all py-1 font-mono text-xs text-muted-foreground">{{ entry.value }}</td>
+ </tr>
+ </tbody>
+ </table>
+
+ <!-- Logging -->
+ <table v-else-if="activeView.view === 'logging'" class="w-full text-sm">
+ <thead>
+ <tr class="border-b text-left text-xs text-muted-foreground">
+ <th class="py-1 pr-4 font-medium">{{ t("solrAdmin.logging.name") }}</th>
+ <th class="w-24 py-1 pr-4 font-medium">{{ t("solrAdmin.logging.level") }}</th>
+ <th class="w-24 py-1 font-medium">{{ t("solrAdmin.logging.set") }}</th>
+ </tr>
+ </thead>
+ <tbody>
+ <tr v-for="entry in loggingLevels" :key="entry.name" class="border-b last:border-0">
+ <td class="py-1 pr-4 font-mono text-xs">{{ entry.name }}</td>
+ <td class="py-1 pr-4">
+ <Badge variant="outline" class="text-xs">{{ entry.level || "-" }}</Badge>
+ </td>
+ <td class="py-1 text-xs text-muted-foreground">{{ entry.set ? "✓" : "" }}</td>
+ </tr>
+ </tbody>
+ </table>
+
+ <!-- Core Admin -->
+ <template v-else-if="activeView.view === 'coreAdmin'">
+ <div class="mb-3 flex justify-end">
+ <Button size="sm" @click="createOpen = true">
+ <Plus class="mr-1.5 h-3.5 w-3.5" />
+ {{ t("solrAdmin.actions.create") }}
+ </Button>
+ </div>
+ <table class="w-full text-sm">
+ <thead>
+ <tr class="border-b text-left text-xs text-muted-foreground">
+ <th class="py-1 pr-3 font-medium">{{ t("solrAdmin.core.name") }}</th>
+ <th class="py-1 pr-3 font-medium">{{ t("solrAdmin.core.docs") }}</th>
+ <th class="py-1 pr-3 font-medium">{{ t("solrAdmin.core.size") }}</th>
+ <th class="py-1 pr-3 font-medium">{{ t("solrAdmin.core.segments") }}</th>
+ <th class="py-1 pr-3 font-medium">{{ t("solrAdmin.core.uptime") }}</th>
+ <th class="py-1 font-medium">{{ t("solrAdmin.core.ops") }}</th>
+ </tr>
+ </thead>
+ <tbody>
+ <tr v-for="core in cores" :key="core.name" class="border-b last:border-0">
+ <td class="py-1.5 pr-3 font-mono text-xs font-medium">{{ core.name }}</td>
+ <td class="py-1.5 pr-3 font-mono text-xs">
+ {{ core.numDocs ?? "-" }}<span v-if="core.deletedDocs" class="text-muted-foreground"> (-{{ core.deletedDocs }})</span>
+ </td>
+ <td class="py-1.5 pr-3 font-mono text-xs">{{ formatBytes(core.sizeInBytes) }}</td>
+ <td class="py-1.5 pr-3 font-mono text-xs">{{ core.segmentCount ?? "-" }}</td>
+ <td class="py-1.5 pr-3 font-mono text-xs">{{ formatUptime(core.uptime) }}</td>
+ <td class="py-1.5">
+ <div class="flex gap-1">
+ <Button size="sm" variant="outline" class="h-6 px-2 text-xs" @click="askCoreAction('RELOAD', core.name)">
+ <RefreshCcw class="h-3 w-3" />
+ </Button>
+ <Button size="sm" variant="outline" class="h-6 px-2 text-xs" @click="askCoreAction('RENAME', core.name)">
+ <FileText class="h-3 w-3" />
+ </Button>
+ <Button size="sm" variant="outline" class="h-6 px-2 text-xs" @click="askCoreAction('SWAP', core.name)">
+ <Shuffle class="h-3 w-3" />
+ </Button>
+ <Button size="sm" variant="outline" class="h-6 px-2 text-xs text-destructive" @click="askCoreAction('UNLOAD', core.name)">
+ <Trash2 class="h-3 w-3" />
+ </Button>
+ </div>
+ </td>
+ </tr>
+ </tbody>
+ </table>
+ <div class="mt-4">
+ <JsonTree v-if="responseBody" :value="responseBody" :initial-expanded-depth="1" virtualized />
+ </div>
+ </template>
+
+ <!-- Core Overview(官方布局:Statistics + Instance + Replication + Healthcheck) -->
+ <template v-else-if="activeView.view === 'overview'">
+ <div class="grid grid-cols-1 gap-3 xl:grid-cols-2">
+ <!-- Statistics -->
+ <div class="rounded border">
+ <div class="border-b bg-muted/30 px-3 py-1.5 text-xs font-medium text-muted-foreground">{{ t("solrAdmin.overview.statistics") }}</div>
+ <table class="w-full text-sm">
+ <tbody>
+ <tr v-if="overviewStats" class="border-b last:border-0">
+ <td class="w-40 px-3 py-1 text-xs text-muted-foreground">{{ t("solrAdmin.overview.lastModified") }}</td>
+ <td class="px-3 py-1 font-mono text-xs">{{ relativeTime(overviewStats.lastModified) }}</td>
+ </tr>
+ <tr v-if="overviewStats" class="border-b last:border-0">
+ <td class="w-40 px-3 py-1 text-xs text-muted-foreground">{{ t("solrAdmin.overview.numDocs") }}</td>
+ <td class="px-3 py-1 font-mono text-xs">{{ overviewStats.numDocs ?? "-" }}</td>
+ </tr>
+ <tr v-if="overviewStats" class="border-b last:border-0">
+ <td class="w-40 px-3 py-1 text-xs text-muted-foreground">{{ t("solrAdmin.overview.maxDoc") }}</td>
+ <td class="px-3 py-1 font-mono text-xs">{{ overviewStats.maxDoc ?? "-" }}</td>
+ </tr>
+ <tr v-if="overviewStats" class="border-b last:border-0">
+ <td class="w-40 px-3 py-1 text-xs text-muted-foreground">{{ t("solrAdmin.overview.deletedDocs") }}</td>
+ <td class="px-3 py-1 font-mono text-xs">{{ overviewStats.deletedDocs ?? "-" }}</td>
+ </tr>
+ <tr v-if="overviewStats" class="border-b last:border-0">
+ <td class="w-40 px-3 py-1 text-xs text-muted-foreground">{{ t("solrAdmin.overview.version") }}</td>
+ <td class="px-3 py-1 font-mono text-xs">{{ overviewStats.version ?? "-" }}</td>
+ </tr>
+ <tr v-if="overviewStats" class="border-b last:border-0">
+ <td class="w-40 px-3 py-1 text-xs text-muted-foreground">{{ t("solrAdmin.overview.segmentCount") }}</td>
+ <td class="px-3 py-1 font-mono text-xs">{{ overviewStats.segmentCount ?? "-" }}</td>
+ </tr>
+ <tr v-if="overviewStats" class="border-b last:border-0">
+ <td class="w-40 px-3 py-1 text-xs text-muted-foreground">{{ t("solrAdmin.overview.current") }}</td>
+ <td class="px-3 py-1 text-xs">{{ overviewStats.current ? "✓" : "✗" }}</td>
+ </tr>
+ </tbody>
+ </table>
+ </div>
+
+ <!-- Instance -->
+ <div class="rounded border">
+ <div class="border-b bg-muted/30 px-3 py-1.5 text-xs font-medium text-muted-foreground">{{ t("solrAdmin.overview.instance") }}</div>
+ <table class="w-full text-sm">
+ <tbody>
+ <tr v-for="row in overviewInstanceRows" :key="row.key" class="border-b last:border-0">
+ <td class="w-40 px-3 py-1 text-xs text-muted-foreground">{{ t(`solrAdmin.overview.${row.key}`) }}</td>
+ <td class="break-all px-3 py-1 font-mono text-xs">{{ row.value }}</td>
+ </tr>
+ </tbody>
+ </table>
+ </div>
+
+ <!-- Replication (Leader) -->
+ <div class="rounded border">
+ <div class="border-b bg-muted/30 px-3 py-1.5 text-xs font-medium text-muted-foreground">{{ t("solrAdmin.overview.replication") }}</div>
+ <table v-if="overviewReplicationRows.length" class="w-full text-sm">
+ <thead>
+ <tr class="border-b text-left text-xs text-muted-foreground">
+ <th class="px-3 py-1 font-medium"></th>
+ <th class="px-3 py-1 font-medium">{{ t("solrAdmin.overview.colVersion") }}</th>
+ <th class="px-3 py-1 font-medium">{{ t("solrAdmin.overview.colGen") }}</th>
+ <th class="px-3 py-1 font-medium">{{ t("solrAdmin.overview.colSize") }}</th>
+ </tr>
+ </thead>
+ <tbody>
+ <tr v-for="row in overviewReplicationRows" :key="row.label" class="border-b last:border-0">
+ <td class="px-3 py-1 text-xs">{{ row.label }}</td>
+ <td class="px-3 py-1 font-mono text-xs">{{ row.version }}</td>
+ <td class="px-3 py-1 font-mono text-xs">{{ row.gen }}</td>
+ <td class="px-3 py-1 font-mono text-xs">{{ row.size }}</td>
+ </tr>
+ </tbody>
+ </table>
+ <div v-else class="px-3 py-2 text-xs text-muted-foreground">{{ t("solrAdmin.overview.noReplication") }}</div>
+ </div>
+
+ <!-- Healthcheck -->
+ <div class="rounded border">
+ <div class="border-b bg-muted/30 px-3 py-1.5 text-xs font-medium text-muted-foreground">{{ t("solrAdmin.overview.healthcheck") }}</div>
+ <div class="px-3 py-2 text-sm">
+ <Badge v-if="overviewPingStatus === 'OK'" variant="default" class="text-xs">OK</Badge>
+ <span v-else class="text-xs text-muted-foreground">{{ overviewPingStatus || t("solrAdmin.overview.noHealthcheck") }}</span>
+ </div>
+ </div>
+ </div>
+ </template>
+
+ <!-- Ping -->
+ <template v-else-if="activeView.view === 'ping'">
+ <div class="flex items-center gap-3">
+ <Badge :variant="pingResult?.status === 'OK' ? 'default' : 'destructive'" class="text-sm">{{ pingResult?.status || "-" }}</Badge>
+ <span v-if="pingResult?.qtime != null" class="text-sm text-muted-foreground">{{ pingResult.qtime }} ms</span>
+ </div>
+ <div class="mt-4">
+ <JsonTree v-if="responseBody" :value="responseBody" :initial-expanded-depth="2" />
+ </div>
+ </template>
+
+ <!-- Schema -->
+ <template v-else-if="activeView.view === 'schema'">
+ <div class="mb-3 flex flex-wrap items-center gap-2 text-xs text-muted-foreground">
+ <Badge v-if="schemaInfo.uniqueKey" variant="outline">uniqueKey: {{ schemaInfo.uniqueKey }}</Badge>
+ <Badge variant="outline">{{ schemaInfo.fields.length }} {{ t("solrAdmin.schema.fields") }}</Badge>
+ <Badge variant="outline">{{ schemaInfo.dynamicFields.length }} {{ t("solrAdmin.schema.dynamicFields") }}</Badge>
+ <Badge variant="outline">{{ schemaInfo.fieldTypeCount }} {{ t("solrAdmin.schema.fieldTypes") }}</Badge>
+ </div>
+ <table class="w-full text-sm">
+ <thead>
+ <tr class="border-b text-left text-xs text-muted-foreground">
+ <th class="py-1 pr-3 font-medium">{{ t("solrAdmin.schema.name") }}</th>
+ <th class="w-32 py-1 pr-3 font-medium">{{ t("solrAdmin.schema.type") }}</th>
+ <th class="w-20 py-1 font-medium">{{ t("solrAdmin.schema.flags") }}</th>
+ </tr>
+ </thead>
+ <tbody>
+ <tr v-for="field in schemaInfo.fields" :key="field.name" class="border-b last:border-0">
+ <td class="py-1 pr-3 font-mono text-xs">
+ {{ field.name }}
+ <Badge v-if="field.name === schemaInfo.uniqueKey" variant="default" class="ml-1 px-1 text-[10px]">PK</Badge>
+ </td>
+ <td class="py-1 pr-3 font-mono text-xs">{{ field.type }}</td>
+ <td class="py-1 font-mono text-[10px] text-muted-foreground">
+ {{ [field.indexed ? "I" : "", field.stored ? "S" : "", field.required ? "R" : "", field.multiValued ? "M" : "", field.docValues ? "D" : ""].filter(Boolean).join(" ") }}
+ </td>
+ </tr>
+ </tbody>
+ </table>
+ <div v-if="schemaInfo.copyFields.length" class="mt-4">
+ <div class="mb-1 text-xs font-medium text-muted-foreground">copyFields</div>
+ <div v-for="cf in schemaInfo.copyFields" :key="`${cf.source}->${cf.dest}`" class="font-mono text-xs">{{ cf.source }} → {{ cf.dest }}</div>
+ </div>
+ <div class="mt-4">
+ <JsonTree v-if="responseBody" :value="responseBody" :initial-expanded-depth="1" virtualized />
+ </div>
+ </template>
+
+ <!-- Analysis -->
+ <template v-else-if="activeView.view === 'analysis'">
+ <div class="mb-3 grid grid-cols-[140px_1fr_1fr_auto] items-end gap-2">
+ <div>
+ <Label class="text-xs">{{ t("solrAdmin.analysis.field") }}</Label>
+ <Input v-model="analysisField" class="h-8 font-mono text-xs" placeholder="code" @keyup.enter="runAnalysis" />
+ </div>
+ <div>
+ <Label class="text-xs">{{ t("solrAdmin.analysis.indexValue") }}</Label>
+ <Input v-model="analysisText" class="h-8 font-mono text-xs" :placeholder="t('solrAdmin.analysis.indexPlaceholder')" @keyup.enter="runAnalysis" />
+ </div>
+ <div>
+ <Label class="text-xs">{{ t("solrAdmin.analysis.queryValue") }}</Label>
+ <Input v-model="analysisQuery" class="h-8 font-mono text-xs" :placeholder="t('solrAdmin.analysis.queryPlaceholder')" @keyup.enter="runAnalysis" />
+ </div>
+ <Button size="sm" class="h-8" :disabled="analysisLoading || !analysisField.trim() || !analysisText" @click="runAnalysis">
+ <Loader2 v-if="analysisLoading" class="mr-1.5 h-3.5 w-3.5 animate-spin" />
+ {{ t("solrAdmin.analysis.run") }}
+ </Button>
+ </div>
+ <div v-if="analysisError" class="mb-3 text-sm text-destructive">{{ analysisError }}</div>
+ <template v-if="analysisResult">
+ <div v-for="section in ['index', 'query'] as const" :key="section">
+ <div v-if="analysisResult[section].length" class="mb-3">
+ <div class="mb-1 text-xs font-medium uppercase text-muted-foreground">{{ t(`solrAdmin.analysis.${section}`) }}</div>
+ <div class="space-y-1">
+ <div v-for="(stage, i) in analysisResult[section]" :key="i" class="flex items-start gap-3 rounded border p-2">
+ <div class="w-64 shrink-0 break-all font-mono text-[10px] text-muted-foreground" :title="stage.name">{{ stage.name.split(".").pop() }}</div>
+ <div class="flex flex-wrap gap-1">
+ <Badge v-for="(token, j) in stage.tokens" :key="j" variant="secondary" class="font-mono text-xs">{{ token }}</Badge>
+ </div>
+ </div>
+ </div>
+ </div>
+ </div>
+ <div v-if="!analysisResult.index.length && !analysisResult.query.length" class="text-sm text-muted-foreground">{{ t("solrAdmin.analysis.empty") }}</div>
+ </template>
+ </template>
+
+ <!-- Query Builder(对标官方 Admin UI Query 表单) -->
+ <template v-else-if="activeView.view === 'queryForm'">
+ <div class="space-y-3 text-sm">
+ <div class="grid grid-cols-2 gap-2">
+ <div>
+ <Label class="text-xs">Request-Handler (qt)</Label>
+ <Input v-model="queryForm.handler" class="h-8 font-mono text-xs" placeholder="/select" />
+ </div>
+ <div>
+ <Label class="text-xs">defType</Label>
+ <Select v-model="queryForm.defType">
+ <SelectTrigger class="h-8 w-full text-xs"><SelectValue :placeholder="t('solrAdmin.queryForm.defaultParser')" /></SelectTrigger>
+ <SelectContent>
+ <SelectItem value="lucene">lucene</SelectItem>
+ <SelectItem value="dismax">dismax</SelectItem>
+ <SelectItem value="edismax">edismax</SelectItem>
+ </SelectContent>
+ </Select>
+ </div>
+ </div>
+
+ <div>
+ <Label class="text-xs">q</Label>
+ <Input v-model="queryForm.q" class="h-8 font-mono text-xs" placeholder="*:*" />
+ </div>
+
+ <div class="grid grid-cols-2 gap-2">
+ <div>
+ <Label class="text-xs">q.op</Label>
+ <Select v-model="queryForm.qop">
+ <SelectTrigger class="h-8 w-full text-xs"><SelectValue placeholder="OR / AND" /></SelectTrigger>
+ <SelectContent>
+ <SelectItem value="OR">OR</SelectItem>
+ <SelectItem value="AND">AND</SelectItem>
+ </SelectContent>
+ </Select>
+ </div>
+ <div>
+ <Label class="text-xs">sort</Label>
+ <Input v-model="queryForm.sort" class="h-8 font-mono text-xs" placeholder="field asc/desc" />
+ </div>
+ </div>
+
+ <div>
+ <Label class="text-xs">fq</Label>
+ <div v-for="(_, i) in queryForm.fq" :key="i" class="mb-1 flex items-center gap-1">
+ <Input v-model="queryForm.fq[i]" class="h-8 font-mono text-xs" />
+ <Button size="sm" variant="outline" class="h-8 w-8 shrink-0 px-0" @click="removeQueryRow(queryForm.fq, i)">−</Button>
+ </div>
+ <Button size="sm" variant="ghost" class="h-7 px-2 text-xs" @click="addQueryRow(queryForm.fq, '')">+ fq</Button>
+ </div>
+
+ <div class="grid grid-cols-4 gap-2">
+ <div>
+ <Label class="text-xs">start</Label>
+ <Input v-model="queryForm.start" class="h-8 font-mono text-xs" placeholder="0" />
+ </div>
+ <div>
+ <Label class="text-xs">rows</Label>
+ <Input v-model="queryForm.rows" class="h-8 font-mono text-xs" placeholder="10" />
+ </div>
+ <div>
+ <Label class="text-xs">fl</Label>
+ <Input v-model="queryForm.fl" class="h-8 font-mono text-xs" />
+ </div>
+ <div>
+ <Label class="text-xs">df</Label>
+ <Input v-model="queryForm.df" class="h-8 font-mono text-xs" />
+ </div>
+ </div>
+
+ <div class="grid grid-cols-2 gap-2">
+ <div v-if="paramsetNames.length">
+ <Label class="text-xs">{{ t("solrAdmin.queryForm.paramsets") }}</Label>
+ <div class="flex flex-wrap gap-1 pt-1">
+ <Badge v-for="name in paramsetNames" :key="name" :variant="queryForm.useParams.includes(name) ? 'default' : 'outline'" class="cursor-pointer text-xs" @click="toggleParamset(name)">
+ {{ name }}
+ </Badge>
+ </div>
+ </div>
+ <div>
+ <Label class="text-xs">wt</Label>
+ <Select v-model="queryForm.wt">
+ <SelectTrigger class="h-8 w-full text-xs"><SelectValue placeholder="json" /></SelectTrigger>
+ <SelectContent>
+ <SelectItem value="json">json</SelectItem>
+ <SelectItem value="xml">xml</SelectItem>
+ <SelectItem value="csv">csv</SelectItem>
+ <SelectItem value="python">python</SelectItem>
+ <SelectItem value="ruby">ruby</SelectItem>
+ <SelectItem value="php">php</SelectItem>
+ <SelectItem value="raw">raw</SelectItem>
+ </SelectContent>
+ </Select>
+ <label class="mt-1.5 flex items-center gap-1.5 text-xs text-muted-foreground"><input v-model="queryForm.indent" type="checkbox" /> indent on</label>
+ <label class="mt-1 flex items-center gap-1.5 text-xs text-muted-foreground"><input v-model="queryForm.debugQuery" type="checkbox" /> debugQuery</label>
+ </div>
+ </div>
+
+ <!-- hl -->
+ <div class="rounded border p-2">
+ <label class="flex items-center gap-1.5 text-xs font-medium"><input v-model="queryForm.hl.enabled" type="checkbox" /> hl</label>
+ <div v-if="queryForm.hl.enabled" class="mt-2 grid grid-cols-3 gap-2">
+ <div><Label class="text-xs">hl.fl</Label><Input v-model="queryForm.hl.fl" class="h-8 font-mono text-xs" /></div>
+ <div><Label class="text-xs">hl.snippets</Label><Input v-model="queryForm.hl.snippets" class="h-8 font-mono text-xs" /></div>
+ <div><Label class="text-xs">hl.fragsize</Label><Input v-model="queryForm.hl.fragsize" class="h-8 font-mono text-xs" /></div>
+ <div><Label class="text-xs">hl.simple.pre</Label><Input v-model="queryForm.hl.simplePre" class="h-8 font-mono text-xs" placeholder="&lt;em&gt;" /></div>
+ <div><Label class="text-xs">hl.simple.post</Label><Input v-model="queryForm.hl.simplePost" class="h-8 font-mono text-xs" placeholder="&lt;/em&gt;" /></div>
+ <div class="flex items-end gap-3 pb-1.5">
+ <label class="flex items-center gap-1.5 text-xs text-muted-foreground"><input v-model="queryForm.hl.requireFieldMatch" type="checkbox" /> hl.requireFieldMatch</label>
+ <label class="flex items-center gap-1.5 text-xs text-muted-foreground"><input v-model="queryForm.hl.mergeContiguous" type="checkbox" /> hl.mergeContiguous</label>
+ </div>
+ </div>
+ </div>
+
+ <!-- facet -->
+ <div class="rounded border p-2">
+ <label class="flex items-center gap-1.5 text-xs font-medium"><input v-model="queryForm.facet.enabled" type="checkbox" /> facet</label>
+ <div v-if="queryForm.facet.enabled" class="mt-2 space-y-2">
+ <div class="grid grid-cols-2 gap-2">
+ <div>
+ <Label class="text-xs">facet.field</Label>
+ <div v-for="(_, i) in queryForm.facet.fields" :key="i" class="mb-1 flex items-center gap-1">
+ <Input v-model="queryForm.facet.fields[i]" class="h-8 font-mono text-xs" />
+ <Button size="sm" variant="outline" class="h-8 w-8 shrink-0 px-0" @click="removeQueryRow(queryForm.facet.fields, i)">−</Button>
+ </div>
+ <Button size="sm" variant="ghost" class="h-7 px-2 text-xs" @click="addQueryRow(queryForm.facet.fields, '')">+ facet.field</Button>
+ </div>
+ <div>
+ <Label class="text-xs">facet.query</Label>
+ <div v-for="(_, i) in queryForm.facet.queries" :key="i" class="mb-1 flex items-center gap-1">
+ <Input v-model="queryForm.facet.queries[i]" class="h-8 font-mono text-xs" />
+ <Button size="sm" variant="outline" class="h-8 w-8 shrink-0 px-0" @click="removeQueryRow(queryForm.facet.queries, i)">−</Button>
+ </div>
+ <Button size="sm" variant="ghost" class="h-7 px-2 text-xs" @click="addQueryRow(queryForm.facet.queries, '')">+ facet.query</Button>
+ </div>
+ </div>
+ <div class="grid grid-cols-4 gap-2">
+ <div><Label class="text-xs">facet.prefix</Label><Input v-model="queryForm.facet.prefix" class="h-8 font-mono text-xs" /></div>
+ <div><Label class="text-xs">facet.sort</Label><Input v-model="queryForm.facet.sort" class="h-8 font-mono text-xs" placeholder="count/index" /></div>
+ <div><Label class="text-xs">facet.limit</Label><Input v-model="queryForm.facet.limit" class="h-8 font-mono text-xs" /></div>
+ <div><Label class="text-xs">facet.offset</Label><Input v-model="queryForm.facet.offset" class="h-8 font-mono text-xs" /></div>
+ <div><Label class="text-xs">facet.mincount</Label><Input v-model="queryForm.facet.mincount" class="h-8 font-mono text-xs" /></div>
+ <div class="flex items-end pb-1.5">
+ <label class="flex items-center gap-1.5 text-xs text-muted-foreground"><input v-model="queryForm.facet.missing" type="checkbox" /> facet.missing</label>
+ </div>
+ </div>
+ </div>
+ </div>
+
+ <!-- spatial -->
+ <div class="rounded border p-2">
+ <label class="flex items-center gap-1.5 text-xs font-medium"><input v-model="queryForm.spatial.enabled" type="checkbox" /> spatial</label>
+ <div v-if="queryForm.spatial.enabled" class="mt-2 grid grid-cols-4 gap-2">
+ <div><Label class="text-xs">pt</Label><Input v-model="queryForm.spatial.pt" class="h-8 font-mono text-xs" placeholder="lat,lng" /></div>
+ <div><Label class="text-xs">sfield</Label><Input v-model="queryForm.spatial.sfield" class="h-8 font-mono text-xs" /></div>
+ <div><Label class="text-xs">d</Label><Input v-model="queryForm.spatial.d" class="h-8 font-mono text-xs" placeholder="km" /></div>
+ <div class="flex items-end gap-3 pb-1.5">
+ <label class="flex items-center gap-1.5 text-xs text-muted-foreground"><input v-model="queryForm.spatial.geofilt" type="checkbox" /> geofilt</label>
+ <label class="flex items-center gap-1.5 text-xs text-muted-foreground"><input v-model="queryForm.spatial.bbox" type="checkbox" /> bbox</label>
+ </div>
+ </div>
+ </div>
+
+ <!-- spellcheck -->
+ <div class="rounded border p-2">
+ <label class="flex items-center gap-1.5 text-xs font-medium"><input v-model="queryForm.spellcheck.enabled" type="checkbox" /> spellcheck</label>
+ <div v-if="queryForm.spellcheck.enabled" class="mt-2 grid grid-cols-4 gap-2">
+ <div><Label class="text-xs">spellcheck.q</Label><Input v-model="queryForm.spellcheck.q" class="h-8 font-mono text-xs" /></div>
+ <div><Label class="text-xs">spellcheck.count</Label><Input v-model="queryForm.spellcheck.count" class="h-8 font-mono text-xs" /></div>
+ <div><Label class="text-xs">spellcheck.dictionary</Label><Input v-model="queryForm.spellcheck.dictionary" class="h-8 font-mono text-xs" /></div>
+ <div class="flex items-end gap-3 pb-1.5">
+ <label class="flex items-center gap-1.5 text-xs text-muted-foreground"><input v-model="queryForm.spellcheck.build" type="checkbox" /> build</label>
+ <label class="flex items-center gap-1.5 text-xs text-muted-foreground"><input v-model="queryForm.spellcheck.collate" type="checkbox" /> collate</label>
+ <label class="flex items-center gap-1.5 text-xs text-muted-foreground"><input v-model="queryForm.spellcheck.onlyMorePopular" type="checkbox" /> onlyMorePopular</label>
+ </div>
+ </div>
+ </div>
+
+ <!-- Raw Query Parameters -->
+ <div>
+ <Label class="text-xs">Raw Query Parameters</Label>
+ <div v-for="(rp, i) in queryForm.rawParams" :key="i" class="mb-1 flex items-center gap-1">
+ <Input v-model="rp.key" class="h-8 w-48 font-mono text-xs" placeholder="key" />
+ <Input v-model="rp.value" class="h-8 font-mono text-xs" placeholder="value" />
+ <Button size="sm" variant="outline" class="h-8 w-8 shrink-0 px-0" @click="removeQueryRow(queryForm.rawParams, i)">−</Button>
+ </div>
+ <Button size="sm" variant="ghost" class="h-7 px-2 text-xs" @click="addQueryRow(queryForm.rawParams, { key: '', value: '' })">+ param</Button>
+ </div>
+
+ <!-- JSON Query -->
+ <div>
+ <Label class="text-xs"
+ >JSON Query <span class="text-muted-foreground">({{ t("solrAdmin.queryForm.jsonHint") }})</span></Label
+ >
+ <textarea v-model="queryForm.jsonQuery" rows="4" class="w-full rounded border bg-background p-2 font-mono text-xs focus:outline-none focus:ring-1 focus:ring-ring" placeholder='{"query":"code:BLOMUS*","limit":20}'></textarea>
+ </div>
+
+ <!-- 预览 + 执行 -->
+ <div class="rounded border bg-muted/40 p-2 font-mono text-[11px] break-all">{{ builtQuery.text }}</div>
+ <div class="flex items-center gap-2">
+ <Button size="sm" class="h-8" :disabled="queryRunning || !selectedCore" @click="runQueryForm">
+ <Loader2 v-if="queryRunning" class="mr-1.5 h-3.5 w-3.5 animate-spin" />
+ {{ t("solrAdmin.queryForm.execute") }}
+ </Button>
+ <Button size="sm" variant="outline" class="h-8" @click="openQueryInConsole">{{ t("solrAdmin.queryForm.openInConsole") }}</Button>
+ </div>
+ <div v-if="queryError" class="flex items-start gap-2 text-sm text-destructive">
+ <AlertTriangle class="mt-0.5 h-4 w-4 shrink-0" />
+ <pre class="whitespace-pre-wrap font-mono text-xs">{{ queryError }}</pre>
+ </div>
+
+ <!-- 结果 -->
+ <div v-if="queryResult" class="space-y-2 border-t pt-2">
+ <div class="flex flex-wrap items-center gap-2 text-xs">
+ <Badge v-if="queryNumFound != null" variant="secondary">numFound: {{ queryNumFound }}</Badge>
+ <Badge variant="outline">{{ queryResult.rows?.length ?? 0 }} {{ t("solrAdmin.queryForm.rowsReturned") }}</Badge>
+ <span class="text-muted-foreground">{{ queryResult.execution_time_ms }} ms</span>
+ <Button v-if="queryRawBody" size="sm" variant="ghost" class="h-6 px-2 text-xs" @click="queryShowRaw = !queryShowRaw">
+ {{ queryShowRaw ? t("solrAdmin.queryForm.tableView") : t("solrAdmin.queryForm.rawJson") }}
+ </Button>
+ </div>
+ <div v-if="queryResult.execution_error" class="text-sm text-destructive">{{ queryResult.error?.messageKey }}</div>
+ <JsonTree v-else-if="queryShowRaw && queryRawParsed" :value="queryRawParsed" :initial-expanded-depth="2" virtualized />
+ <div v-else-if="queryResult.columns?.length" class="overflow-x-auto rounded border">
+ <table class="w-full text-sm">
+ <thead>
+ <tr class="border-b bg-muted/40 text-left text-xs text-muted-foreground">
+ <th v-for="col in queryResult.columns" :key="col" class="whitespace-nowrap px-2 py-1 font-medium">{{ col }}</th>
+ </tr>
+ </thead>
+ <tbody>
+ <tr v-for="(row, ri) in queryResult.rows" :key="ri" class="border-b last:border-0">
+ <td v-for="(cell, ci) in row" :key="ci" class="max-w-80 truncate px-2 py-1 font-mono text-xs" :title="queryCellText(cell)">{{ queryCellText(cell) }}</td>
+ </tr>
+ </tbody>
+ </table>
+ </div>
+ <JsonTree v-else-if="queryRawParsed" :value="queryRawParsed" :initial-expanded-depth="2" virtualized />
+ <div v-else class="text-sm text-muted-foreground">{{ t("solrAdmin.emptyBody") }}</div>
+ </div>
+ </div>
+ </template>
+
+ <!-- Segments -->
+ <table v-else-if="activeView.view === 'segments' && segmentEntries.length" class="w-full text-sm">
+ <thead>
+ <tr class="border-b text-left text-xs text-muted-foreground">
+ <th class="py-1 pr-3 font-medium">{{ t("solrAdmin.segments.name") }}</th>
+ <th class="py-1 pr-3 font-medium">{{ t("solrAdmin.core.docs") }}</th>
+ <th class="py-1 pr-3 font-medium">{{ t("solrAdmin.segments.deleted") }}</th>
+ <th class="py-1 pr-3 font-medium">{{ t("solrAdmin.core.size") }}</th>
+ <th class="py-1 pr-3 font-medium">{{ t("solrAdmin.segments.age") }}</th>
+ <th class="py-1 font-medium">{{ t("solrAdmin.segments.source") }}</th>
+ </tr>
+ </thead>
+ <tbody>
+ <tr v-for="seg in segmentEntries" :key="seg.name" class="border-b last:border-0">
+ <td class="py-1 pr-3 font-mono text-xs">{{ seg.name }}</td>
+ <td class="py-1 pr-3 font-mono text-xs">{{ seg.numDocs ?? "-" }}</td>
+ <td class="py-1 pr-3 font-mono text-xs">{{ seg.delDocs ?? "-" }}</td>
+ <td class="py-1 pr-3 font-mono text-xs">{{ formatBytes(seg.sizeInBytes) }}</td>
+ <td class="py-1 pr-3 font-mono text-xs">{{ seg.age ?? "-" }}</td>
+ <td class="py-1 font-mono text-xs">{{ seg.source ?? "-" }}</td>
+ </tr>
+ </tbody>
+ </table>
+
+ <!-- Replication(官方布局:操作按钮 + Index 表 + Settings) -->
+ <template v-else-if="activeView.view === 'replication'">
+ <div class="flex flex-wrap gap-2">
+ <Button size="sm" variant="outline" class="h-8" :disabled="loading" @click="loadReplication">
+ <RefreshCcw class="mr-1.5 h-3.5 w-3.5" :class="{ 'animate-spin': loading }" />
+ {{ t("solrAdmin.replication.refresh") }}
+ </Button>
+ <Button v-if="replicationDetails?.isLeader" size="sm" :variant="replicationDetails.replicationEnabled !== false ? 'destructive' : 'default'" class="h-8" @click="askReplicationToggle">
+ {{ replicationDetails.replicationEnabled !== false ? t("solrAdmin.replication.disable") : t("solrAdmin.replication.enable") }}
+ </Button>
+ </div>
+
+ <table v-if="replicationRowsComputed.length" class="mt-4 w-full max-w-2xl text-sm">
+ <thead>
+ <tr class="border-b text-left text-xs text-muted-foreground">
+ <th class="px-2 py-1 font-medium">{{ t("solrAdmin.replication.index") }}</th>
+ <th class="px-2 py-1 font-medium">{{ t("solrAdmin.overview.colVersion") }}</th>
+ <th class="px-2 py-1 font-medium">{{ t("solrAdmin.overview.colGen") }}</th>
+ <th class="px-2 py-1 font-medium">{{ t("solrAdmin.overview.colSize") }}</th>
+ </tr>
+ </thead>
+ <tbody>
+ <tr v-for="row in replicationRowsComputed" :key="row.label" class="border-b last:border-0">
+ <td class="px-2 py-1.5 text-xs">{{ row.label }}</td>
+ <td class="px-2 py-1.5 font-mono text-xs">{{ row.version }}</td>
+ <td class="px-2 py-1.5 font-mono text-xs">{{ row.gen }}</td>
+ <td class="px-2 py-1.5 font-mono text-xs">{{ row.size }}</td>
+ </tr>
+ </tbody>
+ </table>
+
+ <div v-if="replicationDetails" class="mt-4 max-w-2xl rounded border">
+ <div class="border-b bg-muted/30 px-3 py-1.5 text-xs font-medium text-muted-foreground">
+ {{ replicationDetails.isLeader ? t("solrAdmin.replication.settingsLeader") : t("solrAdmin.replication.settingsFollower") }}
+ </div>
+ <table v-if="replicationDetails.isLeader" class="w-full text-sm">
+ <tbody>
+ <tr class="border-b last:border-0">
+ <td class="w-48 px-3 py-1.5 text-xs text-muted-foreground">replication enable:</td>
+ <td class="px-3 py-1.5 text-xs">{{ replicationDetails.replicationEnabled !== false ? "✓" : "✗" }}</td>
+ </tr>
+ <tr class="border-b last:border-0">
+ <td class="w-48 px-3 py-1.5 text-xs text-muted-foreground">replicateAfter:</td>
+ <td class="px-3 py-1.5 font-mono text-xs">{{ replicationDetails.replicateAfter.join(", ") || "-" }}</td>
+ </tr>
+ </tbody>
+ </table>
+ <table v-else-if="replicationDetails.follower" class="w-full text-sm">
+ <tbody>
+ <tr v-for="(value, key) in replicationDetails.follower" :key="key" class="border-b last:border-0">
+ <td class="w-48 px-3 py-1.5 font-mono text-xs text-muted-foreground">{{ key }}</td>
+ <td class="break-all px-3 py-1.5 font-mono text-xs">{{ queryCellText(value) }}</td>
+ </tr>
+ </tbody>
+ </table>
+ </div>
+ <div v-else-if="!loading" class="mt-4 text-sm text-muted-foreground">{{ t("solrAdmin.replication.noDetails") }}</div>
+
+ <JsonTree v-if="responseBody" :value="responseBody" :initial-expanded-depth="1" virtualized class="mt-4" />
+ </template>
+
+ <!-- 通用 JSON 视图(threads / metrics / paramsets / files / plugins 及兜底) -->
+ <JsonTree v-else-if="responseBody" :value="responseBody" :initial-expanded-depth="2" virtualized />
+ <div v-else-if="response" class="text-sm text-muted-foreground">{{ t("solrAdmin.emptyBody") }}</div>
+ </div>
+ </div>
+ </div>
+
+ <!-- 危险/写操作确认 -->
+ <Dialog
+ :open="confirmAction !== null"
+ @update:open="
+ (open) => {
+ if (!open && !actionPending) confirmAction = null;
+ }
+ "
+ >
+ <DialogContent class="max-w-sm" :show-close-button="!actionPending">
+ <DialogHeader>
+ <DialogTitle class="flex items-center gap-2">
+ <AlertTriangle class="h-4 w-4 text-destructive" />
+ {{ confirmAction?.label }}
+ </DialogTitle>
+ </DialogHeader>
+ <p class="text-sm text-muted-foreground">
+ {{ t("solrAdmin.actions.confirm", { action: confirmAction?.label, core: confirmAction?.core }) }}
+ </p>
+ <div v-if="confirmAction?.action === 'RENAME'" class="mt-2">
+ <Label class="text-xs">{{ t("solrAdmin.actions.newName") }}</Label>
+ <Input v-model="renameTarget" class="mt-1 h-8 font-mono text-xs" :placeholder="confirmAction.core" />
+ </div>
+ <div v-else-if="confirmAction?.action === 'SWAP'" class="mt-2">
+ <Label class="text-xs">{{ t("solrAdmin.actions.swapWith") }}</Label>
+ <Select v-model="swapTarget">
+ <SelectTrigger class="mt-1 h-8 w-full text-xs"><SelectValue :placeholder="t('solrAdmin.selectCore')" /></SelectTrigger>
+ <SelectContent>
+ <SelectItem v-for="name in coreNames.filter((n) => n !== confirmAction?.core)" :key="name" :value="name">{{ name }}</SelectItem>
+ </SelectContent>
+ </Select>
+ </div>
+ <DialogFooter>
+ <Button variant="outline" :disabled="actionPending" @click="confirmAction = null">{{ t("dangerDialog.cancel") }}</Button>
+ <Button
+ :variant="confirmAction?.action === 'UNLOAD' || confirmAction?.action === 'DISABLE_REPLICATION' ? 'destructive' : 'default'"
+ :disabled="actionPending || (confirmAction?.action === 'RENAME' && !renameTarget.trim()) || (confirmAction?.action === 'SWAP' && !swapTarget)"
+ @click="runCoreAction"
+ >
+ <Loader2 v-if="actionPending" class="mr-1.5 h-3.5 w-3.5 animate-spin" />
+ {{ confirmAction?.label }}
+ </Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+
+ <!-- CREATE core -->
+ <Dialog
+ :open="createOpen"
+ @update:open="
+ (open) => {
+ if (!open && !actionPending) createOpen = false;
+ }
+ "
+ >
+ <DialogContent class="max-w-sm" :show-close-button="!actionPending">
+ <DialogHeader>
+ <DialogTitle>{{ t("solrAdmin.actions.create") }}</DialogTitle>
+ </DialogHeader>
+ <div class="space-y-3">
+ <div>
+ <Label class="text-xs">{{ t("solrAdmin.core.name") }}</Label>
+ <Input v-model="createName" class="mt-1 h-8 font-mono text-xs" placeholder="new_core" />
+ </div>
+ <div>
+ <Label class="text-xs">configSet</Label>
+ <Input v-model="createConfigSet" class="mt-1 h-8 font-mono text-xs" placeholder="_default" />
+ </div>
+ <div>
+ <Label class="text-xs">instanceDir ({{ t("solrAdmin.optional") }})</Label>
+ <Input v-model="createInstanceDir" class="mt-1 h-8 font-mono text-xs" />
+ </div>
+ </div>
+ <DialogFooter>
+ <Button variant="outline" :disabled="actionPending" @click="createOpen = false">{{ t("dangerDialog.cancel") }}</Button>
+ <Button :disabled="actionPending || !createName.trim()" @click="runCreateCore">
+ <Loader2 v-if="actionPending" class="mr-1.5 h-3.5 w-3.5 animate-spin" />
+ {{ t("solrAdmin.actions.create") }}
+ </Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+ </div>
+</template>
diff --git a/apps/desktop/src/components/sql-file/SqlFileExecutionDialog.vue b/apps/desktop/src/components/sql-file/SqlFileExecutionDialog.vue
index 6ac933ad6b..30a1f28bef 100644
--- a/apps/desktop/src/components/sql-file/SqlFileExecutionDialog.vue
+++ b/apps/desktop/src/components/sql-file/SqlFileExecutionDialog.vue
@@ -167,7 +167,7 @@ function resetPerFileState() {
currentFileName.value = "";
}
-const sqlConnections = computed(() => store.connections.filter((c) => !["redis", "mongodb", "elasticsearch", "easysearch", "meilisearch", "qdrant", "milvus", "weaviate", "chromadb", "etcd", "zookeeper", "consul", "mq", "nacos"].includes(c.db_type)));
+const sqlConnections = computed(() => store.connections.filter((c) => !["redis", "mongodb", "elasticsearch", "easysearch", "meilisearch", "solr", "qdrant", "milvus", "weaviate", "chromadb", "etcd", "zookeeper", "consul", "mq", "nacos"].includes(c.db_type)));
// Mirrors the core executor gate (`relational_constraint_bypass_kind` in
// sql_file_import.rs): MySQL-family types use the session-scoped
// FOREIGN_KEY_CHECKS toggle, PostgreSQL-family types use DISABLE/ENABLE
diff --git a/apps/desktop/src/composables/useQuickOpen.ts b/apps/desktop/src/composables/useQuickOpen.ts
index b327bec1cb..864dd940f4 100644
--- a/apps/desktop/src/composables/useQuickOpen.ts
+++ b/apps/desktop/src/composables/useQuickOpen.ts
@@ -25,7 +25,7 @@ const INITIAL_SQL_FILE_LIMIT = 20;
const CONTENT_SEARCH_DEBOUNCE_MS = 200;
const CONTENT_SEARCH_MAX_RESULTS = 500;
-const REMOTE_SEARCH_UNSUPPORTED_TYPES = new Set<ConnectionConfig["db_type"]>(["redis", "mongodb", "elasticsearch", "easysearch", "meilisearch", "qdrant", "milvus", "weaviate", "chromadb", "neo4j", "influxdb", "victoriametrics", "etcd", "zookeeper", "mq", "nacos", "consul"]);
+const REMOTE_SEARCH_UNSUPPORTED_TYPES = new Set<ConnectionConfig["db_type"]>(["redis", "mongodb", "elasticsearch", "easysearch", "meilisearch", "solr", "qdrant", "milvus", "weaviate", "chromadb", "neo4j", "influxdb", "victoriametrics", "etcd", "zookeeper", "mq", "nacos", "consul"]);
export interface QuickOpenItem {
id: string;
diff --git a/apps/desktop/src/composables/useSqlExecution.ts b/apps/desktop/src/composables/useSqlExecution.ts
index 49842f64aa..ffe5ff7d58 100644
--- a/apps/desktop/src/composables/useSqlExecution.ts
+++ b/apps/desktop/src/composables/useSqlExecution.ts
@@ -18,6 +18,7 @@ import { defaultViewForResult } from "@/lib/query/queryResultDefaultView";
import { isQueryExecutionErrorResult } from "@/lib/query/queryResultError";
import { classifyRedisCommandSafety } from "@/lib/redis/redisCommandSafety";
import { isRedisCommentLine } from "@/lib/redis/redisCommandTokenizer";
+import { isDangerousSolrRequest } from "@/lib/solr/solrRequestRisk";
import { isSqlExecutionSnapshot, resolveExecutableSql, type SqlExecutionOverride, type SqlExecutionSnapshot } from "@/lib/sql/sqlExecutionTarget";
import { isElasticsearchRestRequestText, parseElasticsearchRestRequestTarget, splitSqlStatementRanges, sqlStatementParameterOptionsForCompatibility } from "@/lib/sql/sqlStatementRanges";
import { extractSqlParameterDescriptors, type SqlParameterDescriptor, type SqlParameterSyntax } from "@/lib/sql/sqlParameters";
@@ -96,12 +97,12 @@ function isDangerousMeilisearchRequest(method: "GET" | "POST" | "PUT" | "PATCH"
}
export function isDangerousSql(sql: string, databaseType?: DatabaseType): boolean {
- if (databaseType === "elasticsearch" || databaseType === "easysearch" || databaseType === "meilisearch") {
+ if (databaseType === "elasticsearch" || databaseType === "easysearch" || databaseType === "meilisearch" || databaseType === "solr") {
const requests = splitSqlStatementRanges(sql, databaseType)
.map((statement) => parseElasticsearchRestRequestTarget(statement.sql))
.filter((request): request is NonNullable<typeof request> => request !== null);
if (requests.length > 0) {
- return requests.some((request) => (databaseType === "meilisearch" ? isDangerousMeilisearchRequest(request.method, request.path) : isDangerousElasticsearchRequest(request.method, request.path)));
+ return requests.some((request) => (databaseType === "meilisearch" ? isDangerousMeilisearchRequest(request.method, request.path) : databaseType === "solr" ? isDangerousSolrRequest(request.method, request.path) : isDangerousElasticsearchRequest(request.method, request.path)));
}
}
const cleaned = stripSqlComments(sql);
@@ -921,7 +922,7 @@ export function useSqlExecution(deps: {
export function supportsSqlTemplateParameters(connection: Pick<ConnectionConfig, "db_type"> | undefined, sql = ""): boolean {
if (!connection) return false;
- if (connection.db_type === "meilisearch") return false;
+ if (connection.db_type === "meilisearch" || connection.db_type === "solr") return false;
if (connection.db_type === "elasticsearch" || connection.db_type === "easysearch") return !isElasticsearchRestRequestText(sql);
return connection.db_type !== "redis" && connection.db_type !== "mongodb" && connection.db_type !== "victoriametrics";
}
diff --git a/apps/desktop/src/i18n/locales/en.ts b/apps/desktop/src/i18n/locales/en.ts
index f227c7d79e..2ddfc9f260 100644
--- a/apps/desktop/src/i18n/locales/en.ts
+++ b/apps/desktop/src/i18n/locales/en.ts
@@ -4209,6 +4209,154 @@ export default {
unknown: "Unknown",
},
},
+ solrAdmin: {
+ title: "Solr Admin",
+ refresh: "Refresh",
+ selectCore: "Select core",
+ noCore: "No core selected. Pick a core to view core-level admin pages.",
+ emptyBody: "Empty response body.",
+ optional: "optional",
+ sections: {
+ server: "Server",
+ core: "Core",
+ },
+ views: {
+ dashboard: "Dashboard",
+ logging: "Logging",
+ javaProps: "Java Properties",
+ threads: "Thread Dump",
+ coreAdmin: "Core Admin",
+ metrics: "Metrics",
+ overview: "Overview",
+ analysis: "Analysis",
+ documents: "Documents",
+ paramsets: "Paramsets",
+ files: "Files",
+ ping: "Ping",
+ plugins: "Plugins / Stats",
+ query: "Query",
+ replication: "Replication",
+ schema: "Schema",
+ segments: "Segments info",
+ },
+ dashboard: {
+ instance: "Instance",
+ start: "Start",
+ uptime: "Uptime",
+ versions: "Versions",
+ jvmTitle: "JVM",
+ runtime: "Runtime",
+ args: "Args",
+ system: "System",
+ physMem: "Physical Memory",
+ swap: "Swap Space",
+ fd: "File Descriptor Count",
+ jvmMemory: "JVM-Memory",
+ outdatedWarning: "This Solr release is more than a year old. Consider upgrading.",
+ mode: "Mode",
+ solr_home: "Solr Home",
+ core_root: "Core Root",
+ processors: "Processors",
+ },
+ logging: {
+ name: "Logger",
+ level: "Level",
+ set: "Set",
+ },
+ core: {
+ name: "Core",
+ docs: "Docs",
+ size: "Size",
+ segments: "Segs",
+ uptime: "Uptime",
+ ops: "Actions",
+ },
+ schema: {
+ fields: "fields",
+ dynamicFields: "dynamic fields",
+ fieldTypes: "field types",
+ name: "Name",
+ type: "Type",
+ flags: "Flags",
+ },
+ analysis: {
+ field: "Field name",
+ indexValue: "Index value",
+ queryValue: "Query value (optional)",
+ indexPlaceholder: "Text indexed into the field",
+ queryPlaceholder: "Query text analyzed at query time",
+ run: "Analyse",
+ index: "Index chain",
+ query: "Query chain",
+ empty: "No analysis stages returned. Check the field name.",
+ },
+ segments: {
+ name: "Segment",
+ deleted: "Deleted",
+ age: "Age",
+ source: "Source",
+ },
+ actions: {
+ create: "Create Core",
+ reload: "Reload",
+ unload: "Unload",
+ rename: "Rename",
+ swap: "Swap",
+ confirm: 'Run {action} on core "{core}"?',
+ success: '{action} on "{core}" succeeded',
+ failed: "Core admin action failed: {message}",
+ newName: "New core name",
+ swapWith: "Swap with core",
+ },
+ queryForm: {
+ defaultParser: "default parser",
+ paramsets: "paramset(s)",
+ jsonHint: "non-empty switches to POST JSON DSL",
+ execute: "Execute Query",
+ openInConsole: "Open in console",
+ rowsReturned: "rows",
+ tableView: "Table",
+ rawJson: "Raw JSON",
+ },
+ overview: {
+ statistics: "Statistics",
+ instance: "Instance",
+ replication: "Replication",
+ healthcheck: "Healthcheck",
+ lastModified: "Last Modified",
+ numDocs: "Num Docs",
+ maxDoc: "Max Doc",
+ deletedDocs: "Deleted Docs",
+ version: "Version",
+ segmentCount: "Segment Count",
+ current: "Current",
+ cwd: "CWD",
+ instanceDir: "Instance",
+ data: "Data",
+ index: "Index",
+ impl: "Impl",
+ colVersion: "Version",
+ colGen: "Gen",
+ colSize: "Size",
+ leaderSearching: "Leader (Searching)",
+ leaderReplicable: "Leader (Replicable)",
+ noReplication: "No leader replication details for this core.",
+ noHealthcheck: "Ping request handler is not configured with a healthcheck file.",
+ justNow: "just now",
+ minutesAgo: "about {n} minutes ago",
+ hoursAgo: "about {n} hours ago",
+ daysAgo: "about {n} days ago",
+ },
+ replication: {
+ refresh: "Refresh Status",
+ disable: "Disable Replication",
+ enable: "Enable Replication",
+ index: "Index",
+ settingsLeader: "Settings (Leader)",
+ settingsFollower: "Settings (Follower)",
+ noDetails: "No replication details for this core.",
+ },
+ },
userAdmin: {
title: "Users & Privileges",
unsupported: "MySQL-compatible and PostgreSQL-compatible connections are supported. SQL Server, Oracle, and other permission models can be added next.",
diff --git a/apps/desktop/src/i18n/locales/es.ts b/apps/desktop/src/i18n/locales/es.ts
index 1785766fe9..f5da14c118 100644
--- a/apps/desktop/src/i18n/locales/es.ts
+++ b/apps/desktop/src/i18n/locales/es.ts
@@ -10217,4 +10217,152 @@ export default withEnglishFallback({
titleLabel: "Título (opcional)",
titlePlaceholder: "p. ej. Resultado de consulta",
},
+ solrAdmin: {
+ title: "Administración de Solr",
+ refresh: "Actualizar",
+ selectCore: "Seleccionar core",
+ noCore: "No se ha seleccionado ningún core. Seleccione un core antes de ver la página de administración a nivel de core.",
+ emptyBody: "El cuerpo de la respuesta está vacío.",
+ optional: "Opcional",
+ sections: {
+ server: "Servidor",
+ core: "Core",
+ },
+ views: {
+ dashboard: "Panel",
+ logging: "Registro",
+ javaProps: "Propiedades de Java",
+ threads: "Volcado de hilos",
+ coreAdmin: "Administración de Core",
+ metrics: "Métricas",
+ overview: "Resumen",
+ analysis: "Análisis de tokenización",
+ documents: "Documentos",
+ paramsets: "Conjuntos de parámetros",
+ files: "Archivos",
+ ping: "Ping",
+ plugins: "Complementos / Estadísticas",
+ query: "Consulta",
+ replication: "Replicación",
+ schema: "Schema",
+ segments: "Información de segmentos",
+ },
+ dashboard: {
+ instance: "Instancia",
+ start: "Hora de inicio",
+ uptime: "Tiempo de actividad",
+ versions: "Versiones",
+ jvmTitle: "JVM",
+ runtime: "Tiempo de ejecución",
+ args: "Argumentos de inicio",
+ system: "Sistema",
+ physMem: "Memoria física",
+ swap: "Espacio de intercambio",
+ fd: "Número de descriptores de archivos",
+ jvmMemory: "Memoria de JVM",
+ outdatedWarning: "Esta versión de Solr se publicó hace más de un año; se recomienda actualizar.",
+ mode: "Modo de ejecución",
+ solr_home: "Solr Home",
+ core_root: "Directorio raíz de Core",
+ processors: "Número de procesadores",
+ },
+ logging: {
+ name: "Logger",
+ level: "Nivel",
+ set: "Establecido",
+ },
+ core: {
+ name: "Core",
+ docs: "Número de documentos",
+ size: "Tamaño",
+ segments: "Número de segmentos",
+ uptime: "Tiempo de actividad",
+ ops: "Operaciones",
+ },
+ schema: {
+ fields: "campos",
+ dynamicFields: "campos dinámicos",
+ fieldTypes: "tipos de campo",
+ name: "Nombre",
+ type: "Tipo",
+ flags: "Indicadores",
+ },
+ analysis: {
+ field: "Nombre del campo",
+ indexValue: "Texto del lado del índice",
+ queryValue: "Texto del lado de consulta (opcional)",
+ indexPlaceholder: "Texto analizado al escribir en este campo",
+ queryPlaceholder: "Texto analizado en el momento de la consulta",
+ run: "Analizar",
+ index: "Cadena de indexación",
+ query: "Cadena de consulta",
+ empty: "No se devolvieron fases de análisis; compruebe que el nombre del campo sea correcto.",
+ },
+ segments: {
+ name: "Segmento",
+ deleted: "Eliminados",
+ age: "Antigüedad",
+ source: "Origen",
+ },
+ actions: {
+ create: "Crear Core",
+ reload: "Recargar",
+ unload: "Descargar",
+ rename: "Renombrar",
+ swap: "Intercambiar",
+ confirm: '¿Ejecutar {action} en el core "{core}"?',
+ success: '{action} en "{core}" se ejecutó correctamente',
+ failed: "Error en la operación de administración de Core: {message}",
+ newName: "Nombre del nuevo core",
+ swapWith: "Intercambiar con core",
+ },
+ queryForm: {
+ defaultParser: "Parser predeterminado",
+ paramsets: "paramset(s)",
+ jsonHint: "Si no está vacío, enviar con JSON DSL",
+ execute: "Ejecutar consulta",
+ openInConsole: "Abrir en la consola",
+ rowsReturned: "Filas",
+ tableView: "Tabla",
+ rawJson: "JSON sin formato",
+ },
+ overview: {
+ statistics: "Estadísticas",
+ instance: "Instancia",
+ replication: "Replicación",
+ healthcheck: "Comprobación de estado",
+ lastModified: "Última modificación",
+ numDocs: "Número de documentos",
+ maxDoc: "Número máximo de documentos",
+ deletedDocs: "Documentos eliminados",
+ version: "Versión",
+ segmentCount: "Número de segmentos",
+ current: "Actual",
+ cwd: "Directorio de trabajo",
+ instanceDir: "Directorio de instancias",
+ data: "Directorio de datos",
+ index: "Directorio de índices",
+ impl: "Clase de implementación",
+ colVersion: "Versión",
+ colGen: "Gen",
+ colSize: "Tamaño",
+ leaderSearching: "Leader (buscando)",
+ leaderReplicable: "Leader (replicable)",
+ noReplication: "Este core no tiene detalles de replicación de leader.",
+ noHealthcheck: "El controlador de solicitudes Ping no tiene configurado el archivo healthcheck.",
+ justNow: "Hace un momento",
+ minutesAgo: "Hace aproximadamente {n} minutos",
+ hoursAgo: "Hace aproximadamente {n} horas",
+ daysAgo: "Hace aproximadamente {n} días",
+ },
+ replication: {
+ refresh: "Actualizar estado",
+ disable: "Deshabilitar replicación",
+ enable: "Habilitar replicación",
+ index: "Índice",
+ settingsLeader: "Configuración (Leader)",
+ settingsFollower: "Configuración (Follower)",
+ noDetails: "Este core no tiene detalles de replicación.",
+ },
+ },
});
diff --git a/apps/desktop/src/i18n/locales/it.ts b/apps/desktop/src/i18n/locales/it.ts
index a374222779..369d28d0ae 100644
--- a/apps/desktop/src/i18n/locales/it.ts
+++ b/apps/desktop/src/i18n/locales/it.ts
@@ -10217,4 +10217,152 @@ export default withEnglishFallback({
titleLabel: "Titolo (facoltativo)",
titlePlaceholder: "es. Risultato della query",
},
+ solrAdmin: {
+ title: "Amministrazione Solr",
+ refresh: "Aggiorna",
+ selectCore: "Seleziona core",
+ noCore: "Nessun core selezionato. Seleziona prima un core per visualizzare la pagina di amministrazione a livello di core.",
+ emptyBody: "Il corpo della risposta è vuoto.",
+ optional: "Opzionale",
+ sections: {
+ server: "Server",
+ core: "Core",
+ },
+ views: {
+ dashboard: "Dashboard",
+ logging: "Log",
+ javaProps: "Proprietà Java",
+ threads: "Dump dei thread",
+ coreAdmin: "Amministrazione core",
+ metrics: "Metriche",
+ overview: "Panoramica",
+ analysis: "Analisi",
+ documents: "Documenti",
+ paramsets: "Set di parametri",
+ files: "File",
+ ping: "Ping",
+ plugins: "Plugin / Statistiche",
+ query: "Query",
+ replication: "Replicazione",
+ schema: "Schema",
+ segments: "Informazioni sui segmenti",
+ },
+ dashboard: {
+ instance: "Istanza",
+ start: "Ora di avvio",
+ uptime: "Tempo di attività",
+ versions: "Versioni",
+ jvmTitle: "JVM",
+ runtime: "Runtime",
+ args: "Parametri di avvio",
+ system: "Sistema",
+ physMem: "Memoria fisica",
+ swap: "Spazio di swap",
+ fd: "Descrittori di file",
+ jvmMemory: "Memoria JVM",
+ outdatedWarning: "Questa versione di Solr è stata rilasciata da oltre un anno; si consiglia l'aggiornamento.",
+ mode: "Modalità di esecuzione",
+ solr_home: "Solr Home",
+ core_root: "Directory radice dei core",
+ processors: "Numero di processori",
+ },
+ logging: {
+ name: "Logger",
+ level: "Livello",
+ set: "Imposta",
+ },
+ core: {
+ name: "Core",
+ docs: "Numero di documenti",
+ size: "Dimensione",
+ segments: "Numero di segmenti",
+ uptime: "Tempo di attività",
+ ops: "Operazioni",
+ },
+ schema: {
+ fields: "campi",
+ dynamicFields: "campi dinamici",
+ fieldTypes: "tipi di campo",
+ name: "Nome",
+ type: "Tipo",
+ flags: "Flag",
+ },
+ analysis: {
+ field: "Nome del campo",
+ indexValue: "Testo lato indice",
+ queryValue: "Testo lato query (opzionale)",
+ indexPlaceholder: "Testo analizzato durante la scrittura in questo campo",
+ queryPlaceholder: "Testo analizzato durante la query",
+ run: "Analizza",
+ index: "Catena di indicizzazione",
+ query: "Catena di query",
+ empty: "Nessuna fase di analisi restituita. Controlla che il nome del campo sia corretto.",
+ },
+ segments: {
+ name: "Segmento",
+ deleted: "Eliminato",
+ age: "Età",
+ source: "Origine",
+ },
+ actions: {
+ create: "Crea core",
+ reload: "Ricarica",
+ unload: "Scarica",
+ rename: "Rinomina",
+ swap: "Scambia",
+ confirm: 'Eseguire {action} sul core "{core}"?',
+ success: '{action} su "{core}" eseguito correttamente',
+ failed: "Operazione di amministrazione core non riuscita: {message}",
+ newName: "Nuovo nome core",
+ swapWith: "Scambia con il core",
+ },
+ queryForm: {
+ defaultParser: "Parser predefinito",
+ paramsets: "paramset",
+ jsonHint: "Se non vuoto, invia con JSON DSL",
+ execute: "Esegui query",
+ openInConsole: "Apri nella console",
+ rowsReturned: "Righe",
+ tableView: "Tabella",
+ rawJson: "JSON non elaborato",
+ },
+ overview: {
+ statistics: "Statistiche",
+ instance: "Istanza",
+ replication: "Replicazione",
+ healthcheck: "Controllo di integrità",
+ lastModified: "Ultima modifica",
+ numDocs: "Numero di documenti",
+ maxDoc: "Numero massimo di documenti",
+ deletedDocs: "Documenti eliminati",
+ version: "Versione",
+ segmentCount: "Numero di segmenti",
+ current: "Corrente",
+ cwd: "Directory di lavoro",
+ instanceDir: "Directory dell'istanza",
+ data: "Directory dei dati",
+ index: "Directory dell'indice",
+ impl: "Classe di implementazione",
+ colVersion: "Versione",
+ colGen: "Gen",
+ colSize: "Dimensione",
+ leaderSearching: "Leader (ricerca in corso)",
+ leaderReplicable: "Leader (replicabile)",
+ noReplication: "Questo core non dispone di dettagli di replica del leader.",
+ noHealthcheck: "Il gestore di richieste Ping non ha configurato un file healthcheck.",
+ justNow: "Proprio ora",
+ minutesAgo: "Circa {n} minuti fa",
+ hoursAgo: "Circa {n} ore fa",
+ daysAgo: "Circa {n} giorni fa",
+ },
+ replication: {
+ refresh: "Aggiorna stato",
+ disable: "Disabilita replicazione",
+ enable: "Abilita replicazione",
+ index: "Indice",
+ settingsLeader: "Impostazioni (Leader)",
+ settingsFollower: "Impostazioni (Follower)",
+ noDetails: "Questo core non ha dettagli di replicazione.",
+ },
+ },
});
diff --git a/apps/desktop/src/i18n/locales/ja.ts b/apps/desktop/src/i18n/locales/ja.ts
index 3571c18340..a016314fa9 100644
--- a/apps/desktop/src/i18n/locales/ja.ts
+++ b/apps/desktop/src/i18n/locales/ja.ts
@@ -10267,4 +10267,152 @@ export default withEnglishFallback({
titleLabel: "タイトル(任意)",
titlePlaceholder: "例:クエリ結果",
},
+ solrAdmin: {
+ title: "Solr 管理",
+ refresh: "更新",
+ selectCore: "コアを選択",
+ noCore: "コアが選択されていません。コアレベルの管理ページを表示するには、まずコアを選択してください。",
+ emptyBody: "レスポンスボディが空です。",
+ optional: "任意",
+ sections: {
+ server: "サーバー",
+ core: "コア",
+ },
+ views: {
+ dashboard: "ダッシュボード",
+ logging: "ログ",
+ javaProps: "Java プロパティ",
+ threads: "スレッドダンプ",
+ coreAdmin: "コア管理",
+ metrics: "メトリクス",
+ overview: "概要",
+ analysis: "アナライズ",
+ documents: "ドキュメント",
+ paramsets: "パラメータセット",
+ files: "ファイル",
+ ping: "Ping",
+ plugins: "プラグイン / 統計",
+ query: "クエリ",
+ replication: "レプリケーション",
+ schema: "スキーマ",
+ segments: "セグメント情報",
+ },
+ dashboard: {
+ instance: "インスタンス",
+ start: "起動時間",
+ uptime: "稼働時間",
+ versions: "バージョン",
+ jvmTitle: "JVM",
+ runtime: "ランタイム",
+ args: "起動引数",
+ system: "システム",
+ physMem: "物理メモリ",
+ swap: "スワップ領域",
+ fd: "ファイル記述子数",
+ jvmMemory: "JVM メモリ",
+ outdatedWarning: "この Solr バージョンはリリースから1年以上経過しています。アップグレードをおすすめします。",
+ mode: "実行モード",
+ solr_home: "Solr Home",
+ core_root: "コアルートディレクトリ",
+ processors: "プロセッサ数",
+ },
+ logging: {
+ name: "ロガー",
+ level: "レベル",
+ set: "設定済み",
+ },
+ core: {
+ name: "コア",
+ docs: "ドキュメント数",
+ size: "サイズ",
+ segments: "セグメント数",
+ uptime: "稼働時間",
+ ops: "操作",
+ },
+ schema: {
+ fields: "フィールド",
+ dynamicFields: "動的フィールド",
+ fieldTypes: "フィールドタイプ",
+ name: "名前",
+ type: "型",
+ flags: "フラグ",
+ },
+ analysis: {
+ field: "フィールド名",
+ indexValue: "インデックス側テキスト",
+ queryValue: "クエリ側テキスト(任意)",
+ indexPlaceholder: "このフィールドに書き込む際に分析されるテキスト",
+ queryPlaceholder: "クエリ時に分析されるテキスト",
+ run: "分析",
+ index: "インデックスチェーン",
+ query: "クエリチェーン",
+ empty: "分析フェーズが返されませんでした。フィールド名が正しいか確認してください。",
+ },
+ segments: {
+ name: "セグメント",
+ deleted: "削除済み",
+ age: "経過時間",
+ source: "ソース",
+ },
+ actions: {
+ create: "コアの新規作成",
+ reload: "再読み込み",
+ unload: "アンロード",
+ rename: "名前の変更",
+ swap: "交換",
+ confirm: 'コア "{core}" に対して {action} を実行しますか?',
+ success: '{action} "{core}" が成功しました',
+ failed: "コア管理操作に失敗しました:{message}",
+ newName: "新しいコア名",
+ swapWith: "コアと交換",
+ },
+ queryForm: {
+ defaultParser: "デフォルトパーサー",
+ paramsets: "paramset(s)",
+ jsonHint: "空でない場合、JSON DSL で送信します",
+ execute: "クエリを実行",
+ openInConsole: "コンソールで開く",
+ rowsReturned: "行",
+ tableView: "テーブル",
+ rawJson: "生の JSON",
+ },
+ overview: {
+ statistics: "統計",
+ instance: "インスタンス",
+ replication: "レプリケーション",
+ healthcheck: "ヘルスチェック",
+ lastModified: "最終更新",
+ numDocs: "ドキュメント数",
+ maxDoc: "最大ドキュメント数",
+ deletedDocs: "削除済みドキュメント",
+ version: "バージョン",
+ segmentCount: "セグメント数",
+ current: "現在",
+ cwd: "作業ディレクトリ",
+ instanceDir: "インスタンスディレクトリ",
+ data: "データディレクトリ",
+ index: "インデックスディレクトリ",
+ impl: "実装クラス",
+ colVersion: "バージョン",
+ colGen: "Gen",
+ colSize: "サイズ",
+ leaderSearching: "リーダー(検索中)",
+ leaderReplicable: "リーダー(複製可能)",
+ noReplication: "このコアにはリーダーの複製詳細がありません。",
+ noHealthcheck: "Ping リクエストハンドラに healthcheck ファイルが設定されていません。",
+ justNow: "たった今",
+ minutesAgo: "約 {n} 分前",
+ hoursAgo: "約 {n} 時間前",
+ daysAgo: "約 {n} 日前",
+ },
+ replication: {
+ refresh: "状態を更新",
+ disable: "レプリケーションを無効化",
+ enable: "レプリケーションを有効化",
+ index: "インデックス",
+ settingsLeader: "設定(リーダー)",
+ settingsFollower: "設定(フォロワー)",
+ noDetails: "このコアにはレプリケーションの詳細がありません。",
+ },
+ },
});
diff --git a/apps/desktop/src/i18n/locales/ko.ts b/apps/desktop/src/i18n/locales/ko.ts
index 1eeacab556..714721e356 100644
--- a/apps/desktop/src/i18n/locales/ko.ts
+++ b/apps/desktop/src/i18n/locales/ko.ts
@@ -9675,4 +9675,152 @@ export default withEnglishFallback({
titleLabel: "제목 (선택)",
titlePlaceholder: "예: 쿼리 결과",
},
+ solrAdmin: {
+ title: "Solr 관리",
+ refresh: "새로 고침",
+ selectCore: "코어 선택",
+ noCore: "코어를 선택하지 않았습니다. 먼저 코어를 선택한 후 코어 수준 관리 페이지를 확인하세요.",
+ emptyBody: "응답 본문이 비어 있습니다.",
+ optional: "선택 사항",
+ sections: {
+ server: "서버",
+ core: "코어",
+ },
+ views: {
+ dashboard: "대시보드",
+ logging: "로깅",
+ javaProps: "Java 속성",
+ threads: "스레드 덤프",
+ coreAdmin: "코어 관리",
+ metrics: "지표",
+ overview: "개요",
+ analysis: "분석",
+ documents: "문서",
+ paramsets: "매개변수 집합",
+ files: "파일",
+ ping: "Ping",
+ plugins: "플러그인 / 통계",
+ query: "쿼리",
+ replication: "복제",
+ schema: "스키마",
+ segments: "세그먼트 정보",
+ },
+ dashboard: {
+ instance: "인스턴스",
+ start: "시작 시간",
+ uptime: "가동 시간",
+ versions: "버전",
+ jvmTitle: "JVM",
+ runtime: "런타임",
+ args: "시작 매개변수",
+ system: "시스템",
+ physMem: "물리 메모리",
+ swap: "스왑 공간",
+ fd: "파일 디스크립터 수",
+ jvmMemory: "JVM 메모리",
+ outdatedWarning: "이 Solr 버전은 출시된 지 1년이 넘었습니다. 업그레이드를 권장합니다.",
+ mode: "실행 모드",
+ solr_home: "Solr Home",
+ core_root: "코어 루트 디렉터리",
+ processors: "프로세서 수",
+ },
+ logging: {
+ name: "로거",
+ level: "레벨",
+ set: "설정됨",
+ },
+ core: {
+ name: "코어",
+ docs: "문서 수",
+ size: "크기",
+ segments: "세그먼트 수",
+ uptime: "가동 시간",
+ ops: "작업",
+ },
+ schema: {
+ fields: "필드",
+ dynamicFields: "동적 필드",
+ fieldTypes: "필드 유형",
+ name: "이름",
+ type: "유형",
+ flags: "플래그",
+ },
+ analysis: {
+ field: "필드 이름",
+ indexValue: "색인 측 텍스트",
+ queryValue: "쿼리 측 텍스트(선택 사항)",
+ indexPlaceholder: "이 필드에 쓸 때 분석되는 텍스트",
+ queryPlaceholder: "쿼리 시 분석되는 텍스트",
+ run: "분석",
+ index: "색인 체인",
+ query: "쿼리 체인",
+ empty: "분석 단계가 반환되지 않았습니다. 필드 이름이 올바른지 확인하세요.",
+ },
+ segments: {
+ name: "세그먼트",
+ deleted: "삭제됨",
+ age: "나이",
+ source: "소스",
+ },
+ actions: {
+ create: "새 코어 생성",
+ reload: "다시 로드",
+ unload: "언로드",
+ rename: "이름 바꾸기",
+ swap: "교환",
+ confirm: '코어 "{core}"에 대해 {action}을(를) 실행하시겠습니까?',
+ success: '{action} "{core}" 실행 성공',
+ failed: "코어 관리 작업 실패: {message}",
+ newName: "새 코어 이름",
+ swapWith: "코어와 교환",
+ },
+ queryForm: {
+ defaultParser: "기본 파서",
+ paramsets: "paramset(s)",
+ jsonHint: "비어 있지 않으면 JSON DSL로 제출합니다",
+ execute: "쿼리 실행",
+ openInConsole: "콘솔에서 열기",
+ rowsReturned: "행",
+ tableView: "표",
+ rawJson: "원시 JSON",
+ },
+ overview: {
+ statistics: "통계",
+ instance: "인스턴스",
+ replication: "복제",
+ healthcheck: "상태 확인",
+ lastModified: "최종 수정",
+ numDocs: "문서 수",
+ maxDoc: "최대 문서 수",
+ deletedDocs: "삭제된 문서",
+ version: "버전",
+ segmentCount: "세그먼트 수",
+ current: "현재",
+ cwd: "작업 디렉터리",
+ instanceDir: "인스턴스 디렉터리",
+ data: "데이터 디렉터리",
+ index: "색인 디렉터리",
+ impl: "구현 클래스",
+ colVersion: "버전",
+ colGen: "Gen",
+ colSize: "크기",
+ leaderSearching: "리더(검색 중)",
+ leaderReplicable: "리더(복제 가능)",
+ noReplication: "이 코어에는 리더 복제 세부 정보가 없습니다.",
+ noHealthcheck: "Ping 요청 핸들러에 healthcheck 파일이 구성되지 않았습니다.",
+ justNow: "방금",
+ minutesAgo: "약 {n}분 전",
+ hoursAgo: "약 {n}시간 전",
+ daysAgo: "약 {n}일 전",
+ },
+ replication: {
+ refresh: "상태 새로 고침",
+ disable: "복제 사용 안 함",
+ enable: "복제 사용",
+ index: "색인",
+ settingsLeader: "설정(리더)",
+ settingsFollower: "설정(팔로워)",
+ noDetails: "이 코어에는 복제 세부 정보가 없습니다.",
+ },
+ },
});
diff --git a/apps/desktop/src/i18n/locales/pt-BR.ts b/apps/desktop/src/i18n/locales/pt-BR.ts
index 068ed169bd..dbc14da35a 100644
--- a/apps/desktop/src/i18n/locales/pt-BR.ts
+++ b/apps/desktop/src/i18n/locales/pt-BR.ts
@@ -10218,4 +10218,152 @@ export default withEnglishFallback({
titleLabel: "Título (opcional)",
titlePlaceholder: "ex.: Resultado da consulta",
},
+ solrAdmin: {
+ title: "Administração do Solr",
+ refresh: "Atualizar",
+ selectCore: "Selecionar core",
+ noCore: "Nenhum core selecionado. Selecione um core primeiro para visualizar a página de administração do core.",
+ emptyBody: "O corpo da resposta está vazio.",
+ optional: "Opcional",
+ sections: {
+ server: "Servidor",
+ core: "Core",
+ },
+ views: {
+ dashboard: "Painel",
+ logging: "Logs",
+ javaProps: "Propriedades Java",
+ threads: "Dump de threads",
+ coreAdmin: "Administração do Core",
+ metrics: "Métricas",
+ overview: "Visão geral",
+ analysis: "Análise",
+ documents: "Documentos",
+ paramsets: "Conjuntos de parâmetros",
+ files: "Arquivos",
+ ping: "Ping",
+ plugins: "Plugins / Estatísticas",
+ query: "Consulta",
+ replication: "Replicação",
+ schema: "Schema",
+ segments: "Informações de segmentos",
+ },
+ dashboard: {
+ instance: "Instância",
+ start: "Hora de início",
+ uptime: "Tempo de atividade",
+ versions: "Versões",
+ jvmTitle: "JVM",
+ runtime: "Tempo de execução",
+ args: "Argumentos de inicialização",
+ system: "Sistema",
+ physMem: "Memória física",
+ swap: "Swap",
+ fd: "Descritores de arquivo",
+ jvmMemory: "Memória da JVM",
+ outdatedWarning: "Esta versão do Solr foi lançada há mais de um ano, recomenda-se atualizar.",
+ mode: "Modo de execução",
+ solr_home: "Solr Home",
+ core_root: "Diretório raiz do Core",
+ processors: "Número de processadores",
+ },
+ logging: {
+ name: "Logger",
+ level: "Nível",
+ set: "Definido",
+ },
+ core: {
+ name: "Core",
+ docs: "Número de documentos",
+ size: "Tamanho",
+ segments: "Número de segmentos",
+ uptime: "Tempo de atividade",
+ ops: "Operações",
+ },
+ schema: {
+ fields: "campos",
+ dynamicFields: "campos dinâmicos",
+ fieldTypes: "tipos de campo",
+ name: "Nome",
+ type: "Tipo",
+ flags: "Sinalizadores",
+ },
+ analysis: {
+ field: "Nome do campo",
+ indexValue: "Texto do lado do índice",
+ queryValue: "Texto do lado da consulta (opcional)",
+ indexPlaceholder: "Texto analisado ao indexar este campo",
+ queryPlaceholder: "Texto analisado durante a consulta",
+ run: "Analisar",
+ index: "Cadeia de indexação",
+ query: "Cadeia de consulta",
+ empty: "Nenhuma fase de análise foi retornada. Verifique se o nome do campo está correto.",
+ },
+ segments: {
+ name: "Segmento",
+ deleted: "Excluído",
+ age: "Idade",
+ source: "Origem",
+ },
+ actions: {
+ create: "Criar Core",
+ reload: "Recarregar",
+ unload: "Descarregar",
+ rename: "Renomear",
+ swap: "Trocar",
+ confirm: 'Executar {action} no core "{core}"?',
+ success: '{action} "{core}" executado com sucesso',
+ failed: "Falha na operação de administração do Core: {message}",
+ newName: "Nome do novo core",
+ swapWith: "Trocar com o core",
+ },
+ queryForm: {
+ defaultParser: "Parser padrão",
+ paramsets: "paramset(s)",
+ jsonHint: "Se não vazio, enviar usando JSON DSL",
+ execute: "Executar consulta",
+ openInConsole: "Abrir no console",
+ rowsReturned: "Linhas",
+ tableView: "Tabela",
+ rawJson: "JSON bruto",
+ },
+ overview: {
+ statistics: "Estatísticas",
+ instance: "Instância",
+ replication: "Replicação",
+ healthcheck: "Verificação de integridade",
+ lastModified: "Última modificação",
+ numDocs: "Número de documentos",
+ maxDoc: "Número máximo de documentos",
+ deletedDocs: "Documentos excluídos",
+ version: "Versão",
+ segmentCount: "Número de segmentos",
+ current: "Atual",
+ cwd: "Diretório de trabalho",
+ instanceDir: "Diretório da instância",
+ data: "Diretório de dados",
+ index: "Diretório do índice",
+ impl: "Classe de implementação",
+ colVersion: "Versão",
+ colGen: "Gen",
+ colSize: "Tamanho",
+ leaderSearching: "Líder (pesquisando)",
+ leaderReplicable: "Líder (replicável)",
+ noReplication: "Este core não possui detalhes de replicação do líder.",
+ noHealthcheck: "O manipulador de requisições Ping não configurou o arquivo healthcheck.",
+ justNow: "Agora mesmo",
+ minutesAgo: "Há cerca de {n} minutos",
+ hoursAgo: "Há cerca de {n} horas",
+ daysAgo: "Há cerca de {n} dias",
+ },
+ replication: {
+ refresh: "Atualizar status",
+ disable: "Desabilitar replicação",
+ enable: "Habilitar replicação",
+ index: "Índice",
+ settingsLeader: "Configurações (Líder)",
+ settingsFollower: "Configurações (Seguidor)",
+ noDetails: "Este core não possui detalhes de replicação.",
+ },
+ },
});
diff --git a/apps/desktop/src/i18n/locales/zh-CN.ts b/apps/desktop/src/i18n/locales/zh-CN.ts
index 1884ba648a..cb4ee58d49 100644
--- a/apps/desktop/src/i18n/locales/zh-CN.ts
+++ b/apps/desktop/src/i18n/locales/zh-CN.ts
@@ -4185,6 +4185,154 @@ export default withEnglishFallback({
unknown: "未知",
},
},
+ solrAdmin: {
+ title: "Solr 管理",
+ refresh: "刷新",
+ selectCore: "选择 core",
+ noCore: "未选择 core。请先选择一个 core 再查看 core 级管理页。",
+ emptyBody: "响应体为空。",
+ optional: "可选",
+ sections: {
+ server: "服务器",
+ core: "Core",
+ },
+ views: {
+ dashboard: "仪表盘",
+ logging: "日志",
+ javaProps: "Java 属性",
+ threads: "线程转储",
+ coreAdmin: "Core 管理",
+ metrics: "指标",
+ overview: "概览",
+ analysis: "分词分析",
+ documents: "文档",
+ paramsets: "参数集",
+ files: "文件",
+ ping: "Ping",
+ plugins: "插件 / 统计",
+ query: "查询",
+ replication: "复制",
+ schema: "Schema",
+ segments: "段信息",
+ },
+ dashboard: {
+ instance: "实例",
+ start: "启动时间",
+ uptime: "运行时长",
+ versions: "版本",
+ jvmTitle: "JVM",
+ runtime: "运行时",
+ args: "启动参数",
+ system: "系统",
+ physMem: "物理内存",
+ swap: "交换空间",
+ fd: "文件描述符数",
+ jvmMemory: "JVM 内存",
+ outdatedWarning: "该 Solr 版本发布已超过一年,建议升级。",
+ mode: "运行模式",
+ solr_home: "Solr Home",
+ core_root: "Core 根目录",
+ processors: "处理器数",
+ },
+ logging: {
+ name: "Logger",
+ level: "级别",
+ set: "已设置",
+ },
+ core: {
+ name: "Core",
+ docs: "文档数",
+ size: "大小",
+ segments: "段数",
+ uptime: "运行时长",
+ ops: "操作",
+ },
+ schema: {
+ fields: "个字段",
+ dynamicFields: "个动态字段",
+ fieldTypes: "个字段类型",
+ name: "名称",
+ type: "类型",
+ flags: "标记",
+ },
+ analysis: {
+ field: "字段名",
+ indexValue: "索引侧文本",
+ queryValue: "查询侧文本(可选)",
+ indexPlaceholder: "写入该字段时分析的文本",
+ queryPlaceholder: "查询时分析的文本",
+ run: "分析",
+ index: "索引链",
+ query: "查询链",
+ empty: "未返回分析阶段,请检查字段名是否正确。",
+ },
+ segments: {
+ name: "段",
+ deleted: "已删除",
+ age: "年龄",
+ source: "来源",
+ },
+ actions: {
+ create: "新建 Core",
+ reload: "重新加载",
+ unload: "卸载",
+ rename: "重命名",
+ swap: "交换",
+ confirm: '对 core "{core}" 执行 {action}?',
+ success: '{action} "{core}" 执行成功',
+ failed: "Core 管理操作失败:{message}",
+ newName: "新 core 名称",
+ swapWith: "与 core 交换",
+ },
+ queryForm: {
+ defaultParser: "默认解析器",
+ paramsets: "paramset(s)",
+ jsonHint: "非空时改用 JSON DSL 提交",
+ execute: "执行查询",
+ openInConsole: "在控制台打开",
+ rowsReturned: "行",
+ tableView: "表格",
+ rawJson: "原始 JSON",
+ },
+ overview: {
+ statistics: "统计",
+ instance: "实例",
+ replication: "复制",
+ healthcheck: "健康检查",
+ lastModified: "最后修改",
+ numDocs: "文档数",
+ maxDoc: "最大文档数",
+ deletedDocs: "已删除文档",
+ version: "版本",
+ segmentCount: "段数",
+ current: "当前",
+ cwd: "工作目录",
+ instanceDir: "实例目录",
+ data: "数据目录",
+ index: "索引目录",
+ impl: "实现类",
+ colVersion: "版本",
+ colGen: "Gen",
+ colSize: "大小",
+ leaderSearching: "Leader(检索中)",
+ leaderReplicable: "Leader(可复制)",
+ noReplication: "该 core 没有 leader 复制详情。",
+ noHealthcheck: "Ping 请求处理器未配置 healthcheck 文件。",
+ justNow: "刚刚",
+ minutesAgo: "约 {n} 分钟前",
+ hoursAgo: "约 {n} 小时前",
+ daysAgo: "约 {n} 天前",
+ },
+ replication: {
+ refresh: "刷新状态",
+ disable: "禁用复制",
+ enable: "启用复制",
+ index: "索引",
+ settingsLeader: "设置(Leader)",
+ settingsFollower: "设置(Follower)",
+ noDetails: "该 core 没有复制详情。",
+ },
+ },
userAdmin: {
title: "用户与权限",
unsupported: "当前支持 MySQL 兼容与 PostgreSQL 兼容连接。SQL Server、Oracle 等会按各自权限模型继续扩展。",
diff --git a/apps/desktop/src/i18n/locales/zh-TW.ts b/apps/desktop/src/i18n/locales/zh-TW.ts
index 9b57ab7685..f26c554b64 100644
--- a/apps/desktop/src/i18n/locales/zh-TW.ts
+++ b/apps/desktop/src/i18n/locales/zh-TW.ts
@@ -10214,4 +10214,152 @@ export default withEnglishFallback({
titleLabel: "標題(可選)",
titlePlaceholder: "例如:查詢結果",
},
+ solrAdmin: {
+ title: "Solr 管理",
+ refresh: "重新整理",
+ selectCore: "選擇 Core",
+ noCore: "未選擇 Core。請先選擇一個 Core 再檢視 Core 層級管理頁。",
+ emptyBody: "回應主體為空。",
+ optional: "選填",
+ sections: {
+ server: "伺服器",
+ core: "Core",
+ },
+ views: {
+ dashboard: "儀表板",
+ logging: "日誌",
+ javaProps: "Java 屬性",
+ threads: "執行緒傾印",
+ coreAdmin: "Core 管理",
+ metrics: "指標",
+ overview: "總覽",
+ analysis: "分詞分析",
+ documents: "文件",
+ paramsets: "參數集",
+ files: "檔案",
+ ping: "Ping",
+ plugins: "外掛 / 統計",
+ query: "查詢",
+ replication: "複製",
+ schema: "Schema",
+ segments: "段資訊",
+ },
+ dashboard: {
+ instance: "執行個體",
+ start: "啟動時間",
+ uptime: "運作時間",
+ versions: "版本",
+ jvmTitle: "JVM",
+ runtime: "執行階段",
+ args: "啟動參數",
+ system: "系統",
+ physMem: "實體記憶體",
+ swap: "交換空間",
+ fd: "檔案描述符數",
+ jvmMemory: "JVM 記憶體",
+ outdatedWarning: "此 Solr 版本發佈已超過一年,建議升級。",
+ mode: "運作模式",
+ solr_home: "Solr Home",
+ core_root: "Core 根目錄",
+ processors: "處理器數",
+ },
+ logging: {
+ name: "Logger",
+ level: "等級",
+ set: "已設定",
+ },
+ core: {
+ name: "Core",
+ docs: "文件數",
+ size: "大小",
+ segments: "段數",
+ uptime: "運作時間",
+ ops: "操作",
+ },
+ schema: {
+ fields: "個欄位",
+ dynamicFields: "個動態欄位",
+ fieldTypes: "個欄位類型",
+ name: "名稱",
+ type: "類型",
+ flags: "標記",
+ },
+ analysis: {
+ field: "欄位名稱",
+ indexValue: "索引端文字",
+ queryValue: "查詢端文字(選填)",
+ indexPlaceholder: "寫入該欄位時分析的文字",
+ queryPlaceholder: "查詢時分析的文字",
+ run: "分析",
+ index: "索引鏈",
+ query: "查詢鏈",
+ empty: "未傳回分析階段,請檢查欄位名稱是否正確。",
+ },
+ segments: {
+ name: "段",
+ deleted: "已刪除",
+ age: "年齡",
+ source: "來源",
+ },
+ actions: {
+ create: "新增 Core",
+ reload: "重新載入",
+ unload: "卸載",
+ rename: "重新命名",
+ swap: "交換",
+ confirm: '對 Core "{core}" 執行 {action}?',
+ success: '{action} "{core}" 執行成功',
+ failed: "Core 管理操作失敗:{message}",
+ newName: "新 Core 名稱",
+ swapWith: "與 Core 交換",
+ },
+ queryForm: {
+ defaultParser: "預設解析器",
+ paramsets: "參數集",
+ jsonHint: "非空時改用 JSON DSL 提交",
+ execute: "執行查詢",
+ openInConsole: "在主控台開啟",
+ rowsReturned: "列",
+ tableView: "表格",
+ rawJson: "原始 JSON",
+ },
+ overview: {
+ statistics: "統計",
+ instance: "執行個體",
+ replication: "複製",
+ healthcheck: "健康檢查",
+ lastModified: "最後修改",
+ numDocs: "文件數",
+ maxDoc: "最大文件數",
+ deletedDocs: "已刪除文件",
+ version: "版本",
+ segmentCount: "段數",
+ current: "目前",
+ cwd: "工作目錄",
+ instanceDir: "執行個體目錄",
+ data: "資料目錄",
+ index: "索引目錄",
+ impl: "實作類別",
+ colVersion: "版本",
+ colGen: "Gen",
+ colSize: "大小",
+ leaderSearching: "Leader(搜尋中)",
+ leaderReplicable: "Leader(可複製)",
+ noReplication: "此 Core 沒有 Leader 複製詳細資料。",
+ noHealthcheck: "Ping 請求處理常式未設定 healthcheck 檔案。",
+ justNow: "剛剛",
+ minutesAgo: "約 {n} 分鐘前",
+ hoursAgo: "約 {n} 小時前",
+ daysAgo: "約 {n} 天前",
+ },
+ replication: {
+ refresh: "重新整理狀態",
+ disable: "停用複製",
+ enable: "啟用複製",
+ index: "索引",
+ settingsLeader: "設定(Leader)",
+ settingsFollower: "設定(Follower)",
+ noDetails: "此 Core 沒有複製詳細資料。",
+ },
+ },
});
diff --git a/apps/desktop/src/lib/__tests__/ai/aiSolr.spec.ts b/apps/desktop/src/lib/__tests__/ai/aiSolr.spec.ts
new file mode 100644
index 0000000000..0782ff5d85
--- /dev/null
+++ b/apps/desktop/src/lib/__tests__/ai/aiSolr.spec.ts
@@ -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");
+ });
+});
diff --git a/apps/desktop/src/lib/__tests__/app/documentStoreProvider.solr.spec.ts b/apps/desktop/src/lib/__tests__/app/documentStoreProvider.solr.spec.ts
new file mode 100644
index 0000000000..f6d24e9a72
--- /dev/null
+++ b/apps/desktop/src/lib/__tests__/app/documentStoreProvider.solr.spec.ts
@@ -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");
+ });
+});
diff --git a/apps/desktop/src/lib/__tests__/connection/connectionUrl.solr.spec.ts b/apps/desktop/src/lib/__tests__/connection/connectionUrl.solr.spec.ts
new file mode 100644
index 0000000000..af8dc7909e
--- /dev/null
+++ b/apps/desktop/src/lib/__tests__/connection/connectionUrl.solr.spec.ts
@@ -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:[email protected]")).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,
+ });
+ });
+});
diff --git a/apps/desktop/src/lib/__tests__/connection/spannerConnectionDialog.spec.ts b/apps/desktop/src/lib/__tests__/connection/spannerConnectionDialog.spec.ts
index 5b9f16b87c..c1342aa344 100644
--- a/apps/desktop/src/lib/__tests__/connection/spannerConnectionDialog.spec.ts
+++ b/apps/desktop/src/lib/__tests__/connection/spannerConnectionDialog.spec.ts
@@ -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.
diff --git a/apps/desktop/src/lib/__tests__/sql/sqlRisk.solr.spec.ts b/apps/desktop/src/lib/__tests__/sql/sqlRisk.solr.spec.ts
new file mode 100644
index 0000000000..785800948b
--- /dev/null
+++ b/apps/desktop/src/lib/__tests__/sql/sqlRisk.solr.spec.ts
@@ -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);
+ });
+});
diff --git a/apps/desktop/src/lib/ai/ai.ts b/apps/desktop/src/lib/ai/ai.ts
index 375a63c639..f5a1a52aa2 100644
--- a/apps/desktop/src/lib/ai/ai.ts
+++ b/apps/desktop/src/lib/ai/ai.ts
@@ -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.",
diff --git a/apps/desktop/src/lib/app/documentJsonValues.ts b/apps/desktop/src/lib/app/documentJsonValues.ts
index 295973bd45..f5417eb46b 100644
--- a/apps/desktop/src/lib/app/documentJsonValues.ts
+++ b/apps/desktop/src/lib/app/documentJsonValues.ts
@@ -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);
diff --git a/apps/desktop/src/lib/app/documentStoreProvider.ts b/apps/desktop/src/lib/app/documentStoreProvider.ts
index d04948a227..d06cb233f6 100644
--- a/apps/desktop/src/lib/app/documentStoreProvider.ts
+++ b/apps/desktop/src/lib/app/documentStoreProvider.ts
@@ -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 {
diff --git a/apps/desktop/src/lib/app/documentStoreSave.ts b/apps/desktop/src/lib/app/documentStoreSave.ts
index 0cdfb0565e..b751b5bebc 100644
--- a/apps/desktop/src/lib/app/documentStoreSave.ts
+++ b/apps/desktop/src/lib/app/documentStoreSave.ts
@@ -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).
diff --git a/apps/desktop/src/lib/connection/connectionPresentation.ts b/apps/desktop/src/lib/connection/connectionPresentation.ts
index 86b50a632f..1eb5ad075e 100644
--- a/apps/desktop/src/lib/connection/connectionPresentation.ts
+++ b/apps/desktop/src/lib/connection/connectionPresentation.ts
@@ -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";
diff --git a/apps/desktop/src/lib/connection/connectionUrl.ts b/apps/desktop/src/lib/connection/connectionUrl.ts
index cba18708bb..82592dace3 100644
--- a/apps/desktop/src/lib/connection/connectionUrl.ts
+++ b/apps/desktop/src/lib/connection/connectionUrl.ts
@@ -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(/\/+$/, "") } : {}),
diff --git a/apps/desktop/src/lib/connection/connectionUrlBuilder.ts b/apps/desktop/src/lib/connection/connectionUrlBuilder.ts
index 25f8458f77..bd9cd1dc61 100644
--- a/apps/desktop/src/lib/connection/connectionUrlBuilder.ts
+++ b/apps/desktop/src/lib/connection/connectionUrlBuilder.ts
@@ -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
diff --git a/apps/desktop/src/lib/connection/connectionVisibleDatabases.ts b/apps/desktop/src/lib/connection/connectionVisibleDatabases.ts
index 5b8627cc9f..93eebbcd72 100644
--- a/apps/desktop/src/lib/connection/connectionVisibleDatabases.ts
+++ b/apps/desktop/src/lib/connection/connectionVisibleDatabases.ts
@@ -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,
diff --git a/apps/desktop/src/lib/dataGrid/dataGridColumnNameCopy.ts b/apps/desktop/src/lib/dataGrid/dataGridColumnNameCopy.ts
index 701a523228..fe9d9f244a 100644
--- a/apps/desktop/src/lib/dataGrid/dataGridColumnNameCopy.ts
+++ b/apps/desktop/src/lib/dataGrid/dataGridColumnNameCopy.ts
@@ -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"]);
diff --git a/apps/desktop/src/lib/dataGrid/dataGridColumnType.ts b/apps/desktop/src/lib/dataGrid/dataGridColumnType.ts
index 0a65bd4abb..6f720ed92b 100644
--- a/apps/desktop/src/lib/dataGrid/dataGridColumnType.ts
+++ b/apps/desktop/src/lib/dataGrid/dataGridColumnType.ts
@@ -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";
diff --git a/apps/desktop/src/lib/dataGrid/dataGridSaveUi.ts b/apps/desktop/src/lib/dataGrid/dataGridSaveUi.ts
index 92122a9ee5..a8e39cef8a 100644
--- a/apps/desktop/src/lib/dataGrid/dataGridSaveUi.ts
+++ b/apps/desktop/src/lib/dataGrid/dataGridSaveUi.ts
@@ -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";
diff --git a/apps/desktop/src/lib/database/databaseNamespaceCreation.ts b/apps/desktop/src/lib/database/databaseNamespaceCreation.ts
index 82b53a31d3..e2d5599bbd 100644
--- a/apps/desktop/src/lib/database/databaseNamespaceCreation.ts
+++ b/apps/desktop/src/lib/database/databaseNamespaceCreation.ts
@@ -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" },
diff --git a/apps/desktop/src/lib/database/databasePropertyEditing.ts b/apps/desktop/src/lib/database/databasePropertyEditing.ts
index ad0efa218d..0f3a92331a 100644
--- a/apps/desktop/src/lib/database/databasePropertyEditing.ts
+++ b/apps/desktop/src/lib/database/databasePropertyEditing.ts
@@ -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" },
diff --git a/apps/desktop/src/lib/database/sqlExecutionTargetRegistry.ts b/apps/desktop/src/lib/database/sqlExecutionTargetRegistry.ts
index 80a36d850a..6832b1a78c 100644
--- a/apps/desktop/src/lib/database/sqlExecutionTargetRegistry.ts
+++ b/apps/desktop/src/lib/database/sqlExecutionTargetRegistry.ts
@@ -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" },
diff --git a/apps/desktop/src/lib/editor/codemirrorInsertValueHints.ts b/apps/desktop/src/lib/editor/codemirrorInsertValueHints.ts
index 2b9e097ae5..d146cc58f3 100644
--- a/apps/desktop/src/lib/editor/codemirrorInsertValueHints.ts
+++ b/apps/desktop/src/lib/editor/codemirrorInsertValueHints.ts
@@ -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 {
diff --git a/apps/desktop/src/lib/elasticsearch/elasticsearchJsonResponse.ts b/apps/desktop/src/lib/elasticsearch/elasticsearchJsonResponse.ts
index 4be3d72371..58d8f77b85 100644
--- a/apps/desktop/src/lib/elasticsearch/elasticsearchJsonResponse.ts
+++ b/apps/desktop/src/lib/elasticsearch/elasticsearchJsonResponse.ts
@@ -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;
diff --git a/apps/desktop/src/lib/sidebar/sidebarNodeOrdering.ts b/apps/desktop/src/lib/sidebar/sidebarNodeOrdering.ts
index 0e4db38834..5e59140b0b 100644
--- a/apps/desktop/src/lib/sidebar/sidebarNodeOrdering.ts
+++ b/apps/desktop/src/lib/sidebar/sidebarNodeOrdering.ts
@@ -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]);
diff --git a/apps/desktop/src/lib/solr/solrAdmin.ts b/apps/desktop/src/lib/solr/solrAdmin.ts
new file mode 100644
index 0000000000..e3fb508541
--- /dev/null
+++ b/apps/desktop/src/lib/solr/solrAdmin.ts
@@ -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);
+}
diff --git a/apps/desktop/src/lib/solr/solrRequestRisk.ts b/apps/desktop/src/lib/solr/solrRequestRisk.ts
new file mode 100644
index 0000000000..9f57da19f9
--- /dev/null
+++ b/apps/desktop/src/lib/solr/solrRequestRisk.ts
@@ -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;
+}
diff --git a/apps/desktop/src/lib/sql/semantic/diagnostics.ts b/apps/desktop/src/lib/sql/semantic/diagnostics.ts
index bb9297ade7..a44aad2582 100644
--- a/apps/desktop/src/lib/sql/semantic/diagnostics.ts
+++ b/apps/desktop/src/lib/sql/semantic/diagnostics.ts
@@ -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" ||
diff --git a/apps/desktop/src/lib/sql/sqlRisk.ts b/apps/desktop/src/lib/sql/sqlRisk.ts
index 20d8f74355..930fc402e7 100644
--- a/apps/desktop/src/lib/sql/sqlRisk.ts
+++ b/apps/desktop/src/lib/sql/sqlRisk.ts
@@ -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" };
}
diff --git a/apps/desktop/src/lib/sql/sqlStatementRanges.ts b/apps/desktop/src/lib/sql/sqlStatementRanges.ts
index 74995760a9..0c3692a113 100644
--- a/apps/desktop/src/lib/sql/sqlStatementRanges.ts
+++ b/apps/desktop/src/lib/sql/sqlStatementRanges.ts
@@ -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: [],
diff --git a/apps/desktop/src/lib/table/tableMetadataCapabilities.ts b/apps/desktop/src/lib/table/tableMetadataCapabilities.ts
index b922d4cbde..e81956fb7b 100644
--- a/apps/desktop/src/lib/table/tableMetadataCapabilities.ts
+++ b/apps/desktop/src/lib/table/tableMetadataCapabilities.ts
@@ -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,
diff --git a/apps/desktop/src/stores/connectionStore.ts b/apps/desktop/src/stores/connectionStore.ts
index 88450c1896..70ff297b71 100644
--- a/apps/desktop/src/stores/connectionStore.ts
+++ b/apps/desktop/src/stores/connectionStore.ts
@@ -1506,6 +1506,7 @@ export const useConnectionStore = defineStore("connection", () => {
elasticsearch: "Elasticsearch",
easysearch: "Easysearch",
meilisearch: "Meilisearch",
+ solr: "Apache Solr",
qdrant: "Qdrant",
milvus: "Milvus",
weaviate: "Weaviate",
@@ -4165,8 +4166,8 @@ export const useConnectionStore = defineStore("connection", () => {
await loadMongoDatabases(connectionId);
} else if (config.db_type === "dynamodb") {
await loadDynamoDbTables(connectionId);
- } else if (config.db_type === "elasticsearch" || config.db_type === "easysearch" || config.db_type === "meilisearch") {
- // Reload: list indices.
+ } else if (config.db_type === "elasticsearch" || config.db_type === "easysearch" || config.db_type === "meilisearch" || config.db_type === "solr") {
+ // Reload: list indices/cores.
await loadElasticsearchIndices(connectionId);
} else if (config.db_type === "milvus") {
await loadMilvusDatabases(connectionId);
@@ -5041,7 +5042,7 @@ export const useConnectionStore = defineStore("connection", () => {
async function loadConnectedConnectionRootForSidebarSearch(connectionId: string) {
if (!connectedIds.value.has(connectionId)) return;
const config = getConfig(connectionId);
- if (!config || ["redis", "etcd", "zookeeper", "consul", "mongodb", "dynamodb", "elasticsearch", "easysearch", "meilisearch", "milvus", "qdrant", "weaviate", "chromadb", "mq", "nacos"].includes(config.db_type)) return;
+ if (!config || ["redis", "etcd", "zookeeper", "consul", "mongodb", "dynamodb", "elasticsearch", "easysearch", "meilisearch", "solr", "milvus", "qdrant", "weaviate", "chromadb", "mq", "nacos"].includes(config.db_type)) return;
const node = findConnectionNode(connectionId);
if (!node || node.type !== "connection" || hasConnectionMetadataChildren(node.children)) return;
const scope = { kind: "connection-databases" as const, connectionId, driverProfile: metadataDriverProfile(config) };
@@ -5464,9 +5465,10 @@ export const useConnectionStore = defineStore("connection", () => {
await ensureConnected(connectionId);
load = reclaimTreeNodeLoad(load, node);
const isMeilisearch = getConfig(connectionId)?.db_type === "meilisearch";
+ const isSolr = getConfig(connectionId)?.db_type === "solr";
const collections = isMeilisearch
? sortSidebarNames(await withMetadataLoadTimeout(connectionId, api.meilisearchListIndexes(connectionId), "Meilisearch indexes")).map((name) => ({ name, aliases: [] as string[] }))
- : [...(await withMetadataLoadTimeout(connectionId, api.documentListCollections(connectionId, "default"), "Elasticsearch indices"))].sort((left, right) => compareSidebarNames(left.name, right.name));
+ : [...(await withMetadataLoadTimeout(connectionId, api.documentListCollections(connectionId, "default"), isSolr ? "Solr cores" : "Elasticsearch indices"))].sort((left, right) => compareSidebarNames(left.name, right.name));
const indexNodes = collections.map((collection) => {
const aliases = collection.aliases?.filter((alias) => alias.trim());
return {
@@ -7214,7 +7216,7 @@ export const useConnectionStore = defineStore("connection", () => {
await loadMongoDatabases(node.connectionId);
} else if (config?.db_type === "dynamodb") {
await loadDynamoDbTables(node.connectionId);
- } else if (config?.db_type === "elasticsearch" || config?.db_type === "easysearch" || config?.db_type === "meilisearch") {
+ } else if (config?.db_type === "elasticsearch" || config?.db_type === "easysearch" || config?.db_type === "meilisearch" || config?.db_type === "solr") {
await loadElasticsearchIndices(node.connectionId);
} else if (config?.db_type === "milvus") {
await loadMilvusDatabases(node.connectionId);
diff --git a/apps/desktop/src/stores/queryStore.ts b/apps/desktop/src/stores/queryStore.ts
index 34f4bde198..0ccda52b8c 100644
--- a/apps/desktop/src/stores/queryStore.ts
+++ b/apps/desktop/src/stores/queryStore.ts
@@ -3278,6 +3278,29 @@ export const useQueryStore = defineStore("query", () => {
return registerOpenTab(tab);
}
+ function openSolrAdmin(connectionId: string) {
+ const existing = tabs.value.find((tab) => tab.mode === "solr-admin" && tab.connectionId === connectionId);
+ if (existing) {
+ switchTab(existing.id);
+ return existing.id;
+ }
+
+ const conn = useConnectionStore().getConfig(connectionId);
+ const id = uuid();
+ const tab: QueryTab = {
+ id,
+ title: conn?.name ? `${conn.name} - ${t("solrAdmin.title")}` : t("solrAdmin.title"),
+ connectionId,
+ database: "",
+ sql: "",
+ isExecuting: false,
+ isCancelling: false,
+ isExplaining: false,
+ mode: "solr-admin",
+ };
+ return registerOpenTab(tab);
+ }
+
function openDamengJobAdmin(connectionId: string) {
const existing = tabs.value.find((tab) => tab.mode === "dameng-jobs" && tab.connectionId === connectionId);
if (existing) {
@@ -8997,6 +9020,7 @@ export const useQueryStore = defineStore("query", () => {
openPostgresDashboard,
openXuguDashboard,
openNacosDashboard,
+ openSolrAdmin,
openDamengUsers,
openDamengRoles,
openDamengJobAdmin,
diff --git a/apps/desktop/src/types/database.ts b/apps/desktop/src/types/database.ts
index 4cce4f6bb2..b664d4fe19 100644
--- a/apps/desktop/src/types/database.ts
+++ b/apps/desktop/src/types/database.ts
@@ -13,6 +13,10 @@ export function isMeilisearchDatabaseType(dbType?: DatabaseType): boolean {
return dbType === "meilisearch";
}
+export function isSolrDatabaseType(dbType?: DatabaseType): boolean {
+ return dbType === "solr";
+}
+
export interface SqlSnippet {
id: string;
label: string;
@@ -1796,6 +1800,7 @@ export interface QueryTab {
| "mysql-dashboard"
| "postgres-dashboard"
| "xugu-dashboard"
+ | "solr-admin"
| "dolt-version-control"
| "plugin-workbench"
| "plugin-filesystem";
diff --git a/apps/desktop/src/types/generated/connectionProfiles.ts b/apps/desktop/src/types/generated/connectionProfiles.ts
index 3842dbd283..2c73d1ca17 100644
--- a/apps/desktop/src/types/generated/connectionProfiles.ts
+++ b/apps/desktop/src/types/generated/connectionProfiles.ts
@@ -39,6 +39,7 @@ export const CONNECTION_PROFILES = {
oracle: { type: "oracle", port: 1521, user: "system", label: "Oracle", icon: "oracle" },
elasticsearch: { type: "elasticsearch", port: 9200, user: "", label: "Elasticsearch", icon: "elasticsearch" },
easysearch: { type: "easysearch", port: 9200, user: "", label: "Easysearch", icon: "easysearch" },
+ solr: { type: "solr", port: 8983, user: "", label: "Apache Solr", icon: "solr" },
meilisearch: { type: "meilisearch", port: 7700, user: "", label: "Meilisearch", icon: "meilisearch" },
hbase: { type: "hbase", port: 8080, user: "", label: "Apache HBase", icon: "hbase" },
qdrant: { type: "qdrant", port: 6333, user: "", label: "Qdrant", icon: "qdrant" },
@@ -146,6 +147,7 @@ export const CONNECTION_PROFILE_ICONS = {
oracle: "oracle",
elasticsearch: "elasticsearch",
easysearch: "easysearch",
+ solr: "solr",
meilisearch: "meilisearch",
hbase: "hbase",
qdrant: "qdrant",
@@ -252,6 +254,7 @@ export const CONNECTION_PICKER_OPTIONS = [
{ value: "oracle", label: "Oracle", category: "sql" },
{ value: "elasticsearch", label: "Elasticsearch", category: "document" },
{ value: "easysearch", label: "Easysearch", category: "document" },
+ { value: "solr", label: "Apache Solr", category: "document" },
{ value: "meilisearch", label: "Meilisearch", category: "document" },
{ value: "hbase", label: "Apache HBase", category: "document" },
{ value: "qdrant", label: "Qdrant", category: "graph_ai" },
diff --git a/apps/desktop/src/types/generated/databaseTypes.ts b/apps/desktop/src/types/generated/databaseTypes.ts
index 445c65551d..170e1839f7 100644
--- a/apps/desktop/src/types/generated/databaseTypes.ts
+++ b/apps/desktop/src/types/generated/databaseTypes.ts
@@ -16,6 +16,7 @@ export const DATABASE_TYPES = [
"elasticsearch",
"easysearch",
"meilisearch",
+ "solr",
"hbase",
"qdrant",
"chromadb",
diff --git a/crates/dbx-core/assets/database-drivers.manifest.json b/crates/dbx-core/assets/database-drivers.manifest.json
index 35b8776ce3..f25462b452 100644
--- a/crates/dbx-core/assets/database-drivers.manifest.json
+++ b/crates/dbx-core/assets/database-drivers.manifest.json
@@ -567,6 +567,35 @@
"driverManagement": false
}
},
+ {
+ "dbType": "solr",
+ "label": "Apache Solr",
+ "runtimeMode": "native",
+ "mcpMode": "bridge",
+ "singleConnectionPool": false,
+ "metadataConnectionScoped": false,
+ "skipTcpProbe": false,
+ "defaultPort": 8983,
+ "supportLevel": "browse",
+ "capabilities": {
+ "queryExecution": true,
+ "metadataBrowse": true,
+ "objectBrowser": false,
+ "objectSource": false,
+ "schemaSearch": false,
+ "diagram": false,
+ "tableDataEdit": false,
+ "tableStructureEdit": false,
+ "tableImport": false,
+ "dataTransfer": false,
+ "sqlFileExecution": false,
+ "databaseCreate": false,
+ "fieldLineage": false,
+ "sqlExplain": false,
+ "userAdmin": false,
+ "driverManagement": false
+ }
+ },
{
"dbType": "hbase",
"label": "Apache HBase",
diff --git a/crates/dbx-core/src/ai/agent_tools.rs b/crates/dbx-core/src/ai/agent_tools.rs
index 03483d1990..0661e32342 100644
--- a/crates/dbx-core/src/ai/agent_tools.rs
+++ b/crates/dbx-core/src/ai/agent_tools.rs
@@ -358,6 +358,11 @@ pub fn all_tools(db_type: DatabaseType, sql_permissions: AgentSqlPermissions) ->
let mut tools = vec![list_databases_tool(), list_tables_tool(), get_columns_tool(db_type), get_current_time_tool()];
if db_type == DatabaseType::MongoDb {
tools.push(mongo_execute_query_tool(sql_permissions));
+ } else if db_type == DatabaseType::Solr {
+ // Solr has no SQL surface; the agent drives the same `METHOD /path`
+ // REST requests the query console accepts. Writes (`/{core}/update`)
+ // still flow through the shared risk classifier and confirmation gate.
+ tools.push(solr_execute_query_tool(sql_permissions));
} else if supports_sql_query(db_type) {
tools.push(execute_query_tool(sql_permissions));
tools.push(get_sample_data_tool());
@@ -401,6 +406,58 @@ fn mongo_execute_query_tool(_sql_permissions: AgentSqlPermissions) -> ToolDefini
}
}
+/// Solr `execute_query` tool — the `sql` argument carries a DBX REST-console
+/// request (`METHOD /path` plus an optional JSON body), not SQL.
+fn solr_execute_query_tool(sql_permissions: AgentSqlPermissions) -> ToolDefinition {
+ let description = if sql_permissions.allow_dangerous {
+ "Execute a Solr REST request after the user explicitly confirmed this operation. Read, write, and admin requests are allowed for this run."
+ } else if sql_permissions.allow_writes {
+ "Execute a Solr REST request after the user explicitly confirmed this operation. Read requests and document writes are allowed for this run."
+ } else {
+ "Execute a read-only Solr REST request and return results (default 50 rows, up to 1000 with the limit argument). \
+ The request uses the DBX REST-console format: `METHOD /path` on the first line, then an optional JSON body. \
+ Examples: `GET /{core}/select?q=*:*&rows=20`, `GET /{core}/schema/fields`, `POST /{core}/query` with a JSON body \
+ such as {\"query\":\"name:foo\",\"limit\":10}. The leading /solr segment may be omitted — paths are resolved \
+ against the Solr server root. This run cannot execute writes (`/{core}/update`) or admin/schema requests \
+ because no specific request has been confirmed yet; when the user requests a write, first propose the exact \
+ request in one ```sql code block and ask for confirmation."
+ };
+ ToolDefinition {
+ name: "execute_query",
+ description,
+ parameters: json!({
+ "type": "object",
+ "properties": {
+ "sql": {
+ "type": "string",
+ "description": "The Solr REST request to execute (`METHOD /path` plus optional JSON body)"
+ },
+ "limit": {
+ "type": "number",
+ "minimum": 1,
+ "maximum": MAX_EXECUTE_QUERY_ROWS,
+ "description": format!("Max rows to return (default {EXECUTE_QUERY_LIMIT}, max {MAX_EXECUTE_QUERY_ROWS})")
+ },
+ "cell_char_offset": {
+ "type": "integer",
+ "minimum": 0,
+ "maximum": 1000000,
+ "description": "Start character offset for every string cell (default 0). Use the next offset reported by a truncated result to slide through long values. Narrow the request to the target document and field before expanding."
+ },
+ "cell_char_limit": {
+ "type": "integer",
+ "minimum": 1,
+ "maximum": 4000,
+ "description": "Maximum characters returned per string cell (default 200, max 4000). Increase only for an explicit long-value expansion."
+ }
+ },
+ "required": ["sql"]
+ }),
+ read_only: true,
+ parallel_ok: false,
+ }
+}
+
/// list_tables tool definition.
fn list_tables_tool() -> ToolDefinition {
ToolDefinition {
@@ -1657,6 +1714,34 @@ for line in sys.stdin:
assert!(names.contains(&"get_current_time"));
}
+ #[test]
+ fn solr_agent_registers_rest_execute_query_tool() {
+ let tools = all_tools(DatabaseType::Solr, AgentSqlPermissions::default());
+ let names = tools.iter().map(|tool| tool.name).collect::<Vec<_>>();
+ // Solr gets the shared metadata tools plus a REST `execute_query`; SQL
+ // sample/explain helpers are not meaningful for a non-SQL backend.
+ assert!(names.contains(&"list_tables"));
+ assert!(names.contains(&"get_columns"));
+ assert!(names.contains(&"execute_query"));
+ assert!(!names.contains(&"get_sample_data"));
+ assert!(!names.contains(&"explain_query"));
+
+ let execute_query = tools.iter().find(|tool| tool.name == "execute_query").unwrap();
+ assert!(execute_query.description.contains("METHOD /path"));
+ assert!(!execute_query.description.contains("SQL query to execute"));
+
+ let confirmed_tools = all_tools(
+ DatabaseType::Solr,
+ AgentSqlPermissions {
+ allow_writes: true,
+ allow_dangerous: false,
+ confirmed_write_sql: Some("POST /mycore/update\n{\"add\":{\"doc\":{\"id\":\"1\"}}}".to_string()),
+ },
+ );
+ let confirmed_execute_query = confirmed_tools.iter().find(|tool| tool.name == "execute_query").unwrap();
+ assert!(confirmed_execute_query.description.contains("confirmed"));
+ }
+
#[cfg(unix)]
#[tokio::test]
async fn mongodb_agent_registers_shell_query_tool_and_routes_find_one_as_read_only() {
diff --git a/crates/dbx-core/src/connection/mod.rs b/crates/dbx-core/src/connection/mod.rs
index 9005c7dc34..db67f4b661 100644
--- a/crates/dbx-core/src/connection/mod.rs
+++ b/crates/dbx-core/src/connection/mod.rs
@@ -110,6 +110,7 @@ pub enum PoolKind {
SqlServer(Arc<tokio::sync::Mutex<db::sqlserver::SqlServerClient>>),
Elasticsearch(db::elasticsearch_driver::EsClient),
Easysearch(db::easysearch_driver::EasysearchClient),
+ Solr(db::solr_driver::SolrClient),
Meilisearch(db::meilisearch_driver::MeilisearchClient),
HBase(db::hbase_driver::HBaseClient),
VectorDb(db::vector_driver::VectorClient),
@@ -2742,6 +2743,22 @@ impl AppState {
db::easysearch_driver::test_connection(&mut client, connect_timeout).await?;
PoolKind::Easysearch(client)
}
+ DatabaseType::Solr => {
+ let mut client = db::solr_driver::SolrClient::from_config(
+ &url,
+ Some(&db_config.username),
+ Some(&db_config.password),
+ db_config.ssl,
+ db_config.url_params.as_deref(),
+ db_config.external_config.as_ref(),
+ connect_timeout,
+ Some(db_config.ca_cert_path.as_str()),
+ Some(db_config.client_cert_path.as_str()),
+ Some(db_config.client_key_path.as_str()),
+ )?;
+ db::solr_driver::test_connection(&mut client, connect_timeout).await?;
+ PoolKind::Solr(client)
+ }
DatabaseType::Meilisearch => {
let client = db::meilisearch_driver::MeilisearchClient::new_for_config(
&url,
@@ -4084,6 +4101,17 @@ impl AppState {
}
}
}
+ PoolKind::Solr(client) => {
+ let mut client = client.clone();
+ let timeout = crate::db::connection_timeout();
+ match db::solr_driver::test_connection(&mut client, timeout).await {
+ Ok(()) => false,
+ Err(err) => {
+ log::warn!("Solr connection pool '{pool_key}' is stale: {err}");
+ true
+ }
+ }
+ }
PoolKind::Meilisearch(client) => {
let client = client.clone();
let timeout = crate::db::connection_timeout();
@@ -5198,6 +5226,16 @@ impl AppState {
}
}
}
+ PoolKind::Solr(client) => {
+ let mut client = client.clone();
+ match db::solr_driver::test_connection(&mut client, timeout).await {
+ Ok(()) => true,
+ Err(e) => {
+ log::warn!("Solr connection pool '{key}' is unhealthy: {e}");
+ false
+ }
+ }
+ }
PoolKind::Meilisearch(client) => {
let client = client.clone();
match db::meilisearch_driver::test_connection(&client, timeout).await {
@@ -5599,6 +5637,7 @@ enum KeepaliveTarget {
SqlServer(Arc<tokio::sync::Mutex<db::sqlserver::SqlServerClient>>),
Elasticsearch(db::elasticsearch_driver::EsClient),
Easysearch(db::easysearch_driver::EasysearchClient),
+ Solr(db::solr_driver::SolrClient),
HBase(db::hbase_driver::HBaseClient),
VectorDb(db::vector_driver::VectorClient),
InfluxDb(db::influxdb_driver::InfluxdbClient),
@@ -5700,6 +5739,7 @@ fn keepalive_target_from_pool(pool: &PoolKind, config: &ConnectionConfig) -> Opt
PoolKind::SqlServer(client) => Some(KeepaliveTarget::SqlServer(client.clone())),
PoolKind::Elasticsearch(client) => Some(KeepaliveTarget::Elasticsearch(client.clone())),
PoolKind::Easysearch(client) => Some(KeepaliveTarget::Easysearch(client.clone())),
+ PoolKind::Solr(client) => Some(KeepaliveTarget::Solr(client.clone())),
PoolKind::HBase(client) => Some(KeepaliveTarget::HBase(client.clone())),
PoolKind::VectorDb(client) => Some(KeepaliveTarget::VectorDb(client.clone())),
PoolKind::InfluxDb(client) => Some(KeepaliveTarget::InfluxDb(client.clone())),
@@ -5742,6 +5782,7 @@ async fn ping_keepalive_target(target: &mut KeepaliveTarget, timeout: Duration)
KeepaliveTarget::Easysearch(client) => {
db::easysearch_driver::test_connection(client, timeout).await.map_err(Into::into)
}
+ KeepaliveTarget::Solr(client) => db::solr_driver::test_connection(client, timeout).await.map_err(Into::into),
KeepaliveTarget::HBase(client) => {
db::hbase_driver::test_connection(client, timeout).await.map(|_| ()).map_err(Into::into)
}
@@ -6162,6 +6203,7 @@ fn clone_pool_kind(pool: &PoolKind) -> PoolKind {
PoolKind::SqlServer(client) => PoolKind::SqlServer(client.clone()),
PoolKind::Elasticsearch(client) => PoolKind::Elasticsearch(client.clone()),
PoolKind::Easysearch(client) => PoolKind::Easysearch(client.clone()),
+ PoolKind::Solr(client) => PoolKind::Solr(client.clone()),
PoolKind::Meilisearch(client) => PoolKind::Meilisearch(client.clone()),
PoolKind::HBase(client) => PoolKind::HBase(client.clone()),
PoolKind::VectorDb(client) => PoolKind::VectorDb(client.clone()),
@@ -6221,6 +6263,9 @@ async fn close_pool_kind(pool: PoolKind) -> Result<(), String> {
PoolKind::Easysearch(client) => {
drop(client);
}
+ PoolKind::Solr(client) => {
+ drop(client);
+ }
PoolKind::Meilisearch(client) => {
drop(client);
}
@@ -6319,6 +6364,7 @@ fn base_pool_key_for_with_catalog(
db_type,
DatabaseType::Elasticsearch
| DatabaseType::Easysearch
+ | DatabaseType::Solr
| DatabaseType::Qdrant
| DatabaseType::Milvus
| DatabaseType::Weaviate
diff --git a/crates/dbx-core/src/query/document_ops.rs b/crates/dbx-core/src/query/document_ops.rs
index f5db665ceb..81050a02b7 100644
--- a/crates/dbx-core/src/query/document_ops.rs
+++ b/crates/dbx-core/src/query/document_ops.rs
@@ -1,7 +1,7 @@
use crate::connection::{AppState, PoolKind};
use crate::db::agent_driver::mongo_document_id_params;
use crate::db::document_result::DocumentQueryResult;
-use crate::db::{dynamodb_driver, easysearch_driver, elasticsearch_driver, mongo_driver, vector_driver};
+use crate::db::{dynamodb_driver, easysearch_driver, elasticsearch_driver, mongo_driver, solr_driver, vector_driver};
pub use crate::db::vector_driver::CollectionInfo;
@@ -61,6 +61,7 @@ pub async fn list_databases_core(state: &AppState, connection_id: &str) -> Resul
PoolKind::DynamoDb(client) => Ok(vec![client.region.clone()]),
PoolKind::Elasticsearch(_) => Ok(vec!["default".to_string()]),
PoolKind::Easysearch(_) => Ok(vec!["default".to_string()]),
+ PoolKind::Solr(_) => Ok(vec!["default".to_string()]),
PoolKind::Meilisearch(_) => Ok(vec!["default".to_string()]),
PoolKind::VectorDb(client) => vector_driver::list_databases(client).await,
PoolKind::Agent(client) => {
@@ -270,6 +271,18 @@ pub async fn list_collections_core(
PoolKind::Easysearch(client) => {
Ok(elasticsearch_collection_infos(easysearch_driver::list_indices_with_aliases(client).await?))
}
+ PoolKind::Solr(client) => {
+ let names = sort_names(solr_driver::list_cores(client).await?);
+ Ok(names
+ .into_iter()
+ .map(|n| CollectionInfo {
+ name: n.clone(),
+ id: n,
+ kind: Some("core".to_string()),
+ ..Default::default()
+ })
+ .collect())
+ }
PoolKind::Meilisearch(client) => {
let names = sort_names(crate::db::meilisearch_driver::list_indexes(client).await?);
Ok(names.into_iter().map(|n| CollectionInfo { name: n.clone(), id: n, ..Default::default() }).collect())
@@ -459,6 +472,15 @@ pub async fn find_documents_core(
easysearch_driver::find_documents(&client, collection, skip, limit, filter, sort).await
}
}
+ PoolKind::Solr(client) => {
+ let client = client.clone();
+ let _ = projection;
+ if cursor_pagination {
+ solr_driver::find_documents_with_cursor(&client, collection, limit, filter, sort, cursor).await
+ } else {
+ solr_driver::find_documents(&client, collection, skip, limit, filter, sort).await
+ }
+ }
PoolKind::Meilisearch(client) => {
let client = client.clone();
crate::db::meilisearch_driver::find_documents(&client, collection, skip, limit, filter, sort).await
@@ -517,6 +539,10 @@ pub async fn count_document_store_documents_core(
let client = client.clone();
easysearch_driver::count_documents(&client, collection, filter).await
}
+ PoolKind::Solr(client) => {
+ let client = client.clone();
+ solr_driver::count_documents(&client, collection, filter).await
+ }
_ => Err("Document count is not supported for this connection".to_string()),
}
}
@@ -643,6 +669,11 @@ pub async fn insert_document_core(
let client = client.clone();
easysearch_driver::insert_document(&client, collection, doc_json, routing).await
}
+ PoolKind::Solr(client) => {
+ let client = client.clone();
+ let _ = routing;
+ solr_driver::insert_document(&client, collection, doc_json).await
+ }
PoolKind::Meilisearch(client) => {
let client = client.clone();
crate::db::meilisearch_driver::insert_document(&client, collection, doc_json).await
@@ -707,6 +738,11 @@ pub async fn update_document_core(
let client = client.clone();
easysearch_driver::update_document(&client, collection, id, doc_json, routing).await
}
+ PoolKind::Solr(client) => {
+ let client = client.clone();
+ let _ = routing;
+ solr_driver::update_document(&client, collection, id, doc_json).await
+ }
PoolKind::Meilisearch(client) => {
let client = client.clone();
crate::db::meilisearch_driver::update_document(&client, collection, id, doc_json).await
@@ -765,6 +801,11 @@ pub async fn delete_document_core_with_type(
let client = client.clone();
easysearch_driver::delete_document(&client, collection, id, document_type, routing).await
}
+ PoolKind::Solr(client) => {
+ let client = client.clone();
+ let _ = (document_type, routing);
+ solr_driver::delete_document(&client, collection, id).await
+ }
PoolKind::Meilisearch(client) => {
let client = client.clone();
crate::db::meilisearch_driver::delete_document(&client, collection, id).await
diff --git a/crates/dbx-core/src/query/mod.rs b/crates/dbx-core/src/query/mod.rs
index 50c6848777..157905d134 100644
--- a/crates/dbx-core/src/query/mod.rs
+++ b/crates/dbx-core/src/query/mod.rs
@@ -1963,6 +1963,20 @@ async fn do_execute_typed(
}
result
}
+ PoolKind::Solr(client) => {
+ let client = client.clone();
+ let sql = sql.to_string();
+ let max_rows = options.max_rows;
+ // cursorMark 分页只服务文档浏览器;REST 查询是一次性请求,不需要 session 游标。
+ let result =
+ wait_for_query_opt(cancel_token, query_timeout, db::solr_driver::execute_rest_query(&client, &sql))
+ .await
+ .map(|result| truncate_result_with_max_rows(result, max_rows));
+ if matches!(result.as_ref(), Err(err) if should_discard_pool_after_error(pool_db_type, err)) {
+ state.remove_pool_by_key(pool_key).await;
+ }
+ result
+ }
PoolKind::Meilisearch(client) => {
let client = client.clone();
let sql = sql.to_string();
@@ -2926,6 +2940,11 @@ pub async fn close_query_session(
db::easysearch_driver::close_cursor(&client, session_id).await?;
Ok(true)
}
+ PoolKind::Solr(client) => {
+ let client = client.clone();
+ db::solr_driver::close_cursor(&client, session_id).await?;
+ Ok(true)
+ }
_ => Ok(false),
}
}
@@ -4301,6 +4320,7 @@ fn pool_kind_has_transactional_path(pool: &PoolKind) -> bool {
| PoolKind::DynamoDb(_)
| PoolKind::Elasticsearch(_)
| PoolKind::Easysearch(_)
+ | PoolKind::Solr(_)
| PoolKind::Meilisearch(_)
| PoolKind::VectorDb(_)
| PoolKind::InfluxDb(_)
@@ -4704,6 +4724,7 @@ fn batch_transaction_path(pool: &PoolKind) -> BatchTransactionPath {
| PoolKind::CloudflareD1(_)
| PoolKind::Elasticsearch(_)
| PoolKind::Easysearch(_)
+ | PoolKind::Solr(_)
| PoolKind::Meilisearch(_)
| PoolKind::VectorDb(_)
| PoolKind::InfluxDb(_)
diff --git a/crates/dbx-core/src/schema/providers/native.rs b/crates/dbx-core/src/schema/providers/native.rs
index ee8a627670..eb576e05b1 100644
--- a/crates/dbx-core/src/schema/providers/native.rs
+++ b/crates/dbx-core/src/schema/providers/native.rs
@@ -64,6 +64,9 @@ pub(in crate::schema) async fn list_tables(
PoolKind::Easysearch(client) => {
db::easysearch_driver::list_indices(client).await.map(|names| collection_names_to_tables(names, "INDEX"))
}
+ PoolKind::Solr(client) => {
+ db::solr_driver::list_cores(client).await.map(|names| collection_names_to_tables(names, "CORE"))
+ }
PoolKind::Meilisearch(client) => {
db::meilisearch_driver::list_indexes(client).await.map(|names| collection_names_to_tables(names, "INDEX"))
}
@@ -158,6 +161,7 @@ pub(in crate::schema) async fn get_columns(
PoolKind::Turso(client) => db::turso_driver::get_columns(client, schema, table).await,
PoolKind::Elasticsearch(client) => db::elasticsearch_driver::get_columns(client, table).await,
PoolKind::Easysearch(client) => db::easysearch_driver::get_columns(client, table).await,
+ PoolKind::Solr(client) => db::solr_driver::get_columns(client, table).await,
PoolKind::Meilisearch(client) => db::meilisearch_driver::get_columns(client, table).await,
PoolKind::HBase(client) => db::hbase_driver::get_columns(client, database, table).await,
PoolKind::VectorDb(_) => Ok(vec![]),
diff --git a/crates/dbx-drivers/src/db/mod.rs b/crates/dbx-drivers/src/db/mod.rs
index 7bb5c604b4..e9ed1e3f21 100644
--- a/crates/dbx-drivers/src/db/mod.rs
+++ b/crates/dbx-drivers/src/db/mod.rs
@@ -39,6 +39,7 @@ pub mod proxy_tunnel;
pub mod questdb;
pub mod redis_driver;
pub mod rqlite_driver;
+pub mod solr_driver;
pub mod sqlite;
pub mod sqlite_worker;
pub mod sqlserver;
diff --git a/crates/dbx-drivers/src/db/solr_driver.rs b/crates/dbx-drivers/src/db/solr_driver.rs
new file mode 100644
index 0000000000..7e953922b2
--- /dev/null
+++ b/crates/dbx-drivers/src/db/solr_driver.rs
@@ -0,0 +1,1143 @@
+use percent_encoding::{utf8_percent_encode, AsciiSet, CONTROLS};
+use reqwest::{Client as HttpClient, Method};
+use serde::Deserialize;
+use serde_json::Value;
+use std::collections::{BTreeSet, HashMap, HashSet};
+use std::error::Error;
+use std::sync::{Arc, Mutex};
+use std::time::Duration;
+
+use super::{apply_tls_certificates, http_client_builder, with_connection_timeout};
+use crate::db::document_result::DocumentQueryResult;
+use crate::types::QueryResult;
+
+const SOLR_PATH_SEGMENT_ENCODE_SET: &AsciiSet = &CONTROLS
+ .add(b' ')
+ .add(b'"')
+ .add(b'#')
+ .add(b'%')
+ .add(b'/')
+ .add(b'<')
+ .add(b'>')
+ .add(b'?')
+ .add(b'[')
+ .add(b'\\')
+ .add(b']')
+ .add(b'^')
+ .add(b'`')
+ .add(b'{')
+ .add(b'|')
+ .add(b'}');
+
+const SOLR_REST_TABLE_MAX_BODY_BYTES: usize = 8 * 1024 * 1024;
+const SOLR_REST_TABLE_MAX_ROWS: usize = 2_000;
+const SOLR_REST_TABLE_MAX_CELLS: usize = 200_000;
+/// `get_columns` 在无显式 schema 字段(schemaless core 只有 dynamicFields)时
+/// 抽样文档数量,用于推断列。
+const SOLR_SCHEMA_SAMPLE_LIMIT: usize = 50;
+
+#[derive(Clone)]
+pub struct SolrClient {
+ http: HttpClient,
+ /// Base URL including the Solr context path, e.g. `http://host:8983/solr`.
+ base_url: String,
+ auth: Option<(String, String)>,
+ /// `/{core}/schema/uniquekey` 结果缓存:文档的 `_id` 别名、cursorMark 排序
+ /// 兜底字段和文档更新都要靠它定位唯一键。
+ unique_keys: Arc<Mutex<HashMap<String, Option<String>>>>,
+}
+
+impl SolrClient {
+ #[allow(clippy::too_many_arguments)]
+ pub fn from_config(
+ url: &str,
+ username: Option<&str>,
+ password: Option<&str>,
+ tls_enabled: bool,
+ url_params: Option<&str>,
+ _external_config: Option<&Value>,
+ timeout: Duration,
+ ca_cert_path: Option<&str>,
+ client_cert_path: Option<&str>,
+ client_key_path: Option<&str>,
+ ) -> Result<Self, String> {
+ let base_url = normalize_solr_base_url(url);
+ let auth = match (username, password) {
+ (Some(u), Some(p)) if !u.is_empty() => Some((u.to_string(), p.to_string())),
+ _ => None,
+ };
+ let mut builder = http_client_builder(timeout)
+ .danger_accept_invalid_certs(solr_accept_invalid_certs(tls_enabled, url_params));
+ builder = apply_tls_certificates(builder, ca_cert_path, client_cert_path, client_key_path)?;
+ let http = builder.build().map_err(|e| format!("Failed to initialize Solr HTTP client: {e}"))?;
+ Ok(Self { http, base_url, auth, unique_keys: Arc::new(Mutex::new(HashMap::new())) })
+ }
+
+ fn request(&self, method: Method, path: &str) -> reqwest::RequestBuilder {
+ let req = self.http.request(method, format!("{}{}", self.base_url, path));
+ if let Some((ref user, ref pass)) = self.auth {
+ req.basic_auth(user, Some(pass))
+ } else {
+ req
+ }
+ }
+
+ fn get(&self, path: &str) -> reqwest::RequestBuilder {
+ self.request(Method::GET, path)
+ }
+
+ fn post(&self, path: &str) -> reqwest::RequestBuilder {
+ self.request(Method::POST, path)
+ }
+
+ fn core_path(&self, core: &str, endpoint: &str) -> String {
+ format!("/{}/{}", solr_path_segment(core), endpoint.trim_start_matches('/'))
+ }
+
+ /// `/schema/uniquekey` 返回 core 的唯一键字段名(通常 `id`)。结果按连接缓存:
+ /// 每个分页请求都会用到它,逐页重查浪费一次 HTTP 往返。
+ async fn unique_key(&self, core: &str) -> Option<String> {
+ if let Some(cached) = self.unique_keys.lock().ok().and_then(|keys| keys.get(core).cloned()) {
+ return cached;
+ }
+ let resolved = self.fetch_unique_key(core).await.unwrap_or(None);
+ if let Ok(mut keys) = self.unique_keys.lock() {
+ keys.insert(core.to_string(), resolved.clone());
+ }
+ resolved
+ }
+
+ async fn fetch_unique_key(&self, core: &str) -> Result<Option<String>, String> {
+ let path = self.core_path(core, "schema/uniquekey?wt=json");
+ let resp = self.get(&path).send().await.map_err(|e| format!("Solr request failed: {e}"))?;
+ if !resp.status().is_success() {
+ return Ok(None);
+ }
+ let body: Value = resp.json().await.map_err(|e| format!("Solr parse error: {e}"))?;
+ Ok(body.get("uniqueKey").and_then(Value::as_str).map(str::to_string))
+ }
+}
+
+/// `http://host:8983` 需要补 `/solr` 上下文路径;反向代理或显式带路径的 URL 原样保留。
+fn normalize_solr_base_url(url: &str) -> String {
+ let trimmed = url.trim_end_matches('/');
+ let has_context_path =
+ reqwest::Url::parse(trimmed).map(|u| !u.path().trim_matches('/').is_empty()).unwrap_or(false);
+ if has_context_path {
+ trimmed.to_string()
+ } else {
+ format!("{trimmed}/solr")
+ }
+}
+
+pub fn solr_accept_invalid_certs(tls_enabled: bool, url_params: Option<&str>) -> bool {
+ tls_enabled
+ || solr_url_params_flag(url_params, "sslmode", &["disable", "allow"])
+ || solr_url_params_flag(url_params, "tlsverify", &["false", "0", "no", "off"])
+ || solr_url_params_flag(url_params, "verify", &["false", "0", "no", "off"])
+ || solr_url_params_flag(url_params, "insecure", &["true", "1", "yes", "on"])
+ || solr_url_params_flag(url_params, "accept_invalid_certs", &["true", "1", "yes", "on"])
+}
+
+fn solr_url_params_flag(params: Option<&str>, key: &str, expected_values: &[&str]) -> bool {
+ params.unwrap_or("").trim().trim_start_matches('?').split('&').filter_map(|pair| pair.split_once('=')).any(
+ |(k, v)| {
+ k.trim().eq_ignore_ascii_case(key)
+ && expected_values.iter().any(|expected| v.trim().eq_ignore_ascii_case(expected))
+ },
+ )
+}
+
+fn solr_path_segment(value: &str) -> String {
+ utf8_percent_encode(value, SOLR_PATH_SEGMENT_ENCODE_SET).to_string()
+}
+
+fn format_reqwest_error(err: &reqwest::Error) -> String {
+ let mut parts = vec![err.to_string()];
+ let mut source = err.source();
+ while let Some(err) = source {
+ let text = err.to_string();
+ if !text.is_empty() && !parts.iter().any(|part| part == &text) {
+ parts.push(text);
+ }
+ source = err.source();
+ }
+ parts.join(": ")
+}
+
+async fn read_solr_json(resp: reqwest::Response) -> Result<Value, String> {
+ let status = resp.status();
+ let body = resp.text().await.map_err(|e| format!("Solr response read failed: {e}"))?;
+ if !status.is_success() {
+ return Err(format!("Solr error ({status}): {}", solr_error_message(&body)));
+ }
+ serde_json::from_str(&body).map_err(|e| format!("Solr parse error: {e}"))
+}
+
+/// Solr 错误体是 `{"error": {"msg", "code", ...}}`;非 JSON 时回退原文。
+fn solr_error_message(body: &str) -> String {
+ if let Ok(value) = serde_json::from_str::<Value>(body) {
+ if let Some(msg) = value.pointer("/error/msg").and_then(Value::as_str) {
+ return msg.to_string();
+ }
+ }
+ body.chars().take(1_000).collect()
+}
+
+pub async fn test_connection(client: &mut SolrClient, timeout: Duration) -> Result<(), String> {
+ let path = "/admin/info/system?wt=json";
+ let resp = with_connection_timeout("Solr", timeout, async {
+ client
+ .get(path)
+ .send()
+ .await
+ .map_err(|e| format!("Solr connection failed for {}: {}", client.base_url, format_reqwest_error(&e)))
+ })
+ .await?;
+
+ let status = resp.status();
+ if !status.is_success() {
+ let body = resp.text().await.unwrap_or_default();
+ return Err(format!("Solr error ({status}) for {path}: {}", solr_error_message(&body)));
+ }
+ Ok(())
+}
+
+/// 单机模式枚举 core:`GET /solr/admin/cores?action=STATUS`。
+/// SolrCloud 语义上的 collection 列表(`/api/collections`)留待后续扩展。
+pub async fn list_cores(client: &SolrClient) -> Result<Vec<String>, String> {
+ let resp = client
+ .get("/admin/cores?action=STATUS&wt=json")
+ .send()
+ .await
+ .map_err(|e| format!("Solr request failed: {e}"))?;
+ let body = read_solr_json(resp).await?;
+ let mut names: Vec<String> = body
+ .get("status")
+ .and_then(Value::as_object)
+ .map(|status| status.keys().cloned().collect())
+ .unwrap_or_default();
+ names.sort();
+ Ok(names)
+}
+
+#[derive(Deserialize)]
+struct SolrSchemaField {
+ name: String,
+ #[serde(rename = "type", default)]
+ field_type: Option<String>,
+ #[serde(default)]
+ required: bool,
+ #[serde(rename = "multiValued", default)]
+ multi_valued: bool,
+}
+
+pub async fn get_columns(client: &SolrClient, core: &str) -> Result<Vec<crate::db::ColumnInfo>, String> {
+ let path = client.core_path(core, "schema?wt=json");
+ let resp = client.get(&path).send().await.map_err(|e| format!("Solr request failed: {e}"))?;
+ if !resp.status().is_success() {
+ let body = resp.text().await.unwrap_or_default();
+ return Err(format!("Solr error: {}", solr_error_message(&body)));
+ }
+ let body: Value = resp.json().await.map_err(|e| format!("Solr parse error: {e}"))?;
+ let schema = body.get("schema").unwrap_or(&body);
+ let unique_key = schema.get("uniqueKey").and_then(Value::as_str);
+
+ let mut columns: Vec<crate::db::ColumnInfo> = Vec::new();
+ if let Some(fields) = schema.get("fields").and_then(Value::as_array) {
+ for field in fields {
+ let Ok(field) = serde_json::from_value::<SolrSchemaField>(field.clone()) else { continue };
+ let mut extras = Vec::new();
+ if field.multi_valued {
+ extras.push("multiValued");
+ }
+ if field.required {
+ extras.push("required");
+ }
+ columns.push(crate::db::ColumnInfo {
+ name: field.name.clone(),
+ data_type: field.field_type.unwrap_or_default(),
+ is_nullable: !field.required,
+ is_primary_key: unique_key == Some(field.name.as_str()),
+ is_unique: unique_key == Some(field.name.as_str()),
+ extra: (!extras.is_empty()).then(|| extras.join(",")),
+ ..Default::default()
+ });
+ }
+ }
+ columns.sort_by(|left, right| left.name.cmp(&right.name));
+ if !columns.is_empty() {
+ return Ok(columns);
+ }
+
+ // Schemaless core 只有 dynamicFields,没有具体列名——抽样文档推断列。
+ sample_columns_from_documents(client, core, unique_key).await
+}
+
+async fn sample_columns_from_documents(
+ client: &SolrClient,
+ core: &str,
+ unique_key: Option<&str>,
+) -> Result<Vec<crate::db::ColumnInfo>, String> {
+ let body = serde_json::json!({ "query": "*:*", "limit": SOLR_SCHEMA_SAMPLE_LIMIT });
+ let path = client.core_path(core, "query");
+ let resp = client.post(&path).json(&body).send().await.map_err(|e| format!("Solr request failed: {e}"))?;
+ let body = read_solr_json(resp).await?;
+ let docs = body.pointer("/response/docs").and_then(Value::as_array).cloned().unwrap_or_default();
+
+ let mut names = Vec::<String>::new();
+ let mut seen = HashSet::<String>::new();
+ let mut types = HashMap::<String, &str>::new();
+ for doc in &docs {
+ let Some(object) = doc.as_object() else { continue };
+ for (key, value) in object {
+ if seen.insert(key.clone()) {
+ names.push(key.clone());
+ }
+ let value_type = match value {
+ Value::Null => continue,
+ Value::Bool(_) => "boolean",
+ Value::Number(_) => "number",
+ Value::String(_) => "text",
+ Value::Array(_) | Value::Object(_) => "json",
+ };
+ match types.get(key.as_str()) {
+ None => {
+ types.insert(key.clone(), value_type);
+ }
+ Some(existing) if *existing != value_type => {
+ types.insert(key.clone(), "json");
+ }
+ _ => {}
+ }
+ }
+ }
+ names.sort();
+ Ok(names
+ .into_iter()
+ .map(|name| crate::db::ColumnInfo {
+ is_primary_key: unique_key == Some(name.as_str()),
+ is_unique: unique_key == Some(name.as_str()),
+ data_type: types.get(name.as_str()).unwrap_or(&"unknown").to_string(),
+ name,
+ ..Default::default()
+ })
+ .collect())
+}
+
+// ---------------------------------------------------------------------------
+// 文档查询:Mongo 风格 filter JSON → Solr fq 列表(多个 fq 之间是 AND 语义)。
+// ---------------------------------------------------------------------------
+
+fn solr_term_value(value: &Value) -> Result<String, String> {
+ match value {
+ Value::String(text) => Ok(format!("\"{}\"", text.replace('\\', "\\\\").replace('"', "\\\""))),
+ Value::Number(number) => Ok(number.to_string()),
+ Value::Bool(flag) => Ok(flag.to_string()),
+ _ => Err("Solr term value must be a string, number, or boolean".to_string()),
+ }
+}
+
+/// Solr 通配符查询里的特殊字符转义(`\`、`?`、`*`、`:` 等)。
+fn solr_escape_wildcard_literal(text: &str) -> String {
+ let mut escaped = String::with_capacity(text.len());
+ for ch in text.chars() {
+ if matches!(
+ ch,
+ '\\' | '+' | '-' | '=' | '&' | '|' | '!' | '(' | ')' | '{' | '}' | '[' | ']' | '^' | '"' | '~' | ':' | '/'
+ ) {
+ escaped.push('\\');
+ }
+ escaped.push(ch);
+ }
+ escaped
+}
+
+fn solr_field_name(field: &str) -> String {
+ field.trim().to_string()
+}
+
+fn translate_field_term(field: &str, value: &Value) -> Result<String, String> {
+ if value.is_null() {
+ // `field:*` 是"字段存在",取反即"字段为空"。纯负查询在 fq 里合法。
+ return Ok(format!("-{}:*", solr_field_name(field)));
+ }
+ if let Value::Array(items) = value {
+ return translate_in_filter(field, items);
+ }
+ Ok(format!("{}:{}", solr_field_name(field), solr_term_value(value)?))
+}
+
+fn translate_in_filter(field: &str, items: &[Value]) -> Result<String, String> {
+ if items.is_empty() {
+ // Mongo `$in: []` 匹配不到任何文档;用恒假条件保持语义一致。
+ return Ok("(*:* AND -*:*)".to_string());
+ }
+ let terms = items.iter().map(solr_term_value).collect::<Result<Vec<_>, _>>()?;
+ Ok(format!("{}:({})", solr_field_name(field), terms.join(" OR ")))
+}
+
+fn translate_regex_filter(field: &str, pattern: &str) -> String {
+ let field = solr_field_name(field);
+ // 用户直接手写 `*`/`?` 时视为 Solr 通配符原样透传。
+ if pattern.chars().any(|ch| matches!(ch, '*' | '?')) {
+ return format!("{field}:{pattern}");
+ }
+ // begins-with/ends-with 产出的 `^lit`/`lit$` 锚点映射为前缀/后缀通配;
+ // 其余按正则字面量反转义后包成 contains 通配。
+ if let Some(rest) = pattern.strip_prefix('^') {
+ return format!("{field}:{}*", solr_escape_wildcard_literal(&regex_unescape_literal(rest)));
+ }
+ if let Some(rest) = pattern.strip_suffix('$') {
+ return format!("{field}:*{}", solr_escape_wildcard_literal(&regex_unescape_literal(rest)));
+ }
+ let literal = regex_unescape_literal(pattern);
+ if literal == pattern {
+ // 没有正则转义也不是通配符——按真实正则走 `field:/re/`。
+ if pattern.chars().any(|ch| matches!(ch, '.' | '+' | '{' | '}' | '(' | ')' | '[' | ']' | '|')) {
+ return format!("{field}:/{}/", pattern.replace('/', "\\/"));
+ }
+ }
+ format!("{field}:*{}*", solr_escape_wildcard_literal(&literal))
+}
+
+/// 反转义前端 `escapeRegexLiteral` 产生的 `\X`(X 为正则元字符)。
+/// 只处理反斜杠+元字符的转义对,其余内容原样保留。
+fn regex_unescape_literal(pattern: &str) -> String {
+ const REGEX_META: &str = ".*+?^${}()|[]\\";
+ let mut out = String::with_capacity(pattern.len());
+ let mut chars = pattern.chars().peekable();
+ while let Some(ch) = chars.next() {
+ if ch == '\\' {
+ match chars.peek() {
+ Some(&next) if REGEX_META.contains(next) => {
+ out.push(next);
+ chars.next();
+ }
+ _ => out.push(ch),
+ }
+ } else {
+ out.push(ch);
+ }
+ }
+ out
+}
+
+fn translate_field_operator_filter(
+ field: &str,
+ object: &serde_json::Map<String, Value>,
+) -> Result<Vec<String>, String> {
+ let field = solr_field_name(field);
+ let mut filters = Vec::new();
+ let mut range = serde_json::Map::new();
+
+ for (operator, value) in object {
+ match operator.as_str() {
+ "$options" => {}
+ "$eq" => filters.push(translate_field_term(&field, value)?),
+ "$ne" => {
+ if value.is_null() {
+ filters.push(format!("{field}:*"));
+ } else {
+ filters.push(format!("-{field}:{}", solr_term_value(value)?));
+ }
+ }
+ "$gt" => {
+ range.insert("gt".to_string(), value.clone());
+ }
+ "$gte" => {
+ range.insert("gte".to_string(), value.clone());
+ }
+ "$lt" => {
+ range.insert("lt".to_string(), value.clone());
+ }
+ "$lte" => {
+ range.insert("lte".to_string(), value.clone());
+ }
+ "$in" => {
+ let items = value.as_array().ok_or_else(|| "$in must be an array".to_string())?;
+ filters.push(translate_in_filter(&field, items)?);
+ }
+ "$nin" => {
+ let items = value.as_array().ok_or_else(|| "$nin must be an array".to_string())?;
+ if !items.is_empty() {
+ let terms = items.iter().map(solr_term_value).collect::<Result<Vec<_>, _>>()?;
+ filters.push(format!("-({}:({}))", field, terms.join(" OR ")));
+ }
+ }
+ "$regex" => {
+ let pattern = value.as_str().ok_or_else(|| "$regex must be a string for Solr filters".to_string())?;
+ filters.push(translate_regex_filter(&field, pattern));
+ }
+ "$not" => {
+ let Some(inner) = value.as_object() else {
+ return Err("$not must be a JSON object".to_string());
+ };
+ let clauses = translate_field_operator_filter(&field, inner)?;
+ for clause in clauses {
+ filters.push(format!("-({clause})"));
+ }
+ }
+ "$exists" => match value.as_bool() {
+ Some(true) => filters.push(format!("{field}:*")),
+ Some(false) => filters.push(format!("-{field}:*")),
+ None => return Err("$exists must be a boolean".to_string()),
+ },
+ other => return Err(format!("Unsupported Solr field filter operator: {other}")),
+ }
+ }
+
+ if !range.is_empty() {
+ // `$gt`/`$lt` → `{`/`}` 开区间,`$gte`/`$lte` → `[`/`]` 闭区间,缺省端点用 `*`。
+ let (lower_bound, lower_open) = match (range.get("gt"), range.get("gte")) {
+ (Some(v), _) => (solr_range_endpoint(v)?, true),
+ (None, Some(v)) => (solr_range_endpoint(v)?, false),
+ (None, None) => ("*".to_string(), false),
+ };
+ let (upper_bound, upper_open) = match (range.get("lt"), range.get("lte")) {
+ (Some(v), _) => (solr_range_endpoint(v)?, true),
+ (None, Some(v)) => (solr_range_endpoint(v)?, false),
+ (None, None) => ("*".to_string(), true),
+ };
+ filters.push(format!(
+ "{field}:{}{lower_bound} TO {upper_bound}{}",
+ if lower_open { "{" } else { "[" },
+ if upper_open { "}" } else { "]" }
+ ));
+ }
+
+ Ok(filters)
+}
+
+fn solr_range_endpoint(value: &Value) -> Result<String, String> {
+ match value {
+ Value::Null => Ok("*".to_string()),
+ _ => solr_term_value(value),
+ }
+}
+
+fn translate_solr_document_filter_value(value: &Value) -> Result<Vec<String>, String> {
+ let Some(object) = value.as_object() else {
+ return Err("Solr filter must be a JSON object".to_string());
+ };
+ let mut filters = Vec::new();
+ for (key, value) in object {
+ match key.as_str() {
+ "$and" => {
+ let items = value.as_array().ok_or_else(|| "$and must be an array".to_string())?;
+ for item in items {
+ filters.extend(translate_solr_document_filter_value(item)?);
+ }
+ }
+ "$or" => {
+ let items = value.as_array().ok_or_else(|| "$or must be an array".to_string())?;
+ let mut groups = Vec::new();
+ for item in items {
+ let clauses = translate_solr_document_filter_value(item)?;
+ if clauses.is_empty() {
+ continue;
+ }
+ groups.push(clauses.join(" AND "));
+ }
+ if !groups.is_empty() {
+ filters.push(format!("({})", groups.join(" OR ")));
+ }
+ }
+ "$solrQuery" => {
+ // 逃生舱:直接透传一段 Solr 查询语法作为 fq。
+ let raw = value.as_str().ok_or_else(|| "$solrQuery must be a string".to_string())?;
+ if !raw.trim().is_empty() {
+ filters.push(raw.trim().to_string());
+ }
+ }
+ key if key.starts_with('$') => {
+ return Err(format!("Unsupported Solr filter operator: {key}"));
+ }
+ field => match value.as_object() {
+ Some(object) if object.keys().any(|k| k.starts_with('$')) => {
+ filters.extend(translate_field_operator_filter(field, object)?);
+ }
+ Some(_) => {
+ return Err("Nested object filters are not supported for Solr".to_string());
+ }
+ None => filters.push(translate_field_term(field, value)?),
+ },
+ }
+ }
+ Ok(filters)
+}
+
+fn solr_filters_from_document_filter(filter: Option<&str>) -> Result<Vec<String>, String> {
+ let Some(filter) = filter.map(str::trim).filter(|value| !value.is_empty()) else {
+ return Ok(Vec::new());
+ };
+ let value: Value = serde_json::from_str(filter).map_err(|e| format!("Invalid filter JSON: {e}"))?;
+ translate_solr_document_filter_value(&value)
+}
+
+/// `{"a": -1, "b": "asc"}` → `"a desc,b asc"`;空输入返回 `None`。
+fn solr_sort_from_document_sort(sort: Option<&str>) -> Result<Option<String>, String> {
+ let Some(sort) = sort.map(str::trim).filter(|value| !value.is_empty()) else {
+ return Ok(None);
+ };
+ let value: Value = serde_json::from_str(sort).map_err(|e| format!("Invalid sort JSON: {e}"))?;
+ let object = value.as_object().ok_or_else(|| "Solr sort must be a JSON object".to_string())?;
+ if object.is_empty() {
+ return Ok(None);
+ }
+ let items = object
+ .iter()
+ .map(|(field, direction)| {
+ let order = match direction {
+ Value::Number(number) if number.as_i64().unwrap_or(1) < 0 => "desc",
+ Value::String(value) if value.eq_ignore_ascii_case("desc") => "desc",
+ _ => "asc",
+ };
+ format!("{} {}", field.trim(), order)
+ })
+ .collect::<Vec<_>>();
+ Ok(Some(items.join(",")))
+}
+
+fn solr_query_body(
+ filter: Option<&str>,
+ sort: Option<&str>,
+ offset: u64,
+ limit: i64,
+ cursor_mark: Option<&str>,
+ unique_key: Option<&str>,
+) -> Result<Value, String> {
+ let filters = solr_filters_from_document_filter(filter)?;
+ let mut body = serde_json::json!({
+ "query": "*:*",
+ "offset": offset,
+ "limit": limit.max(0),
+ });
+ if !filters.is_empty() {
+ body["filter"] = Value::Array(filters.into_iter().map(Value::String).collect());
+ }
+ let mut sort = solr_sort_from_document_sort(sort)?;
+ if cursor_mark.is_some() {
+ // cursorMark 要求 sort 包含 uniqueKey 字段作稳定 tiebreaker。
+ let Some(unique_key) = unique_key else {
+ return Err("Solr cursor pagination requires a uniqueKey field in the schema".to_string());
+ };
+ let uk = unique_key.to_string();
+ let has_uk = sort.as_deref().is_some_and(|s| {
+ s.split(',').any(|item| item.trim_start().starts_with(&format!("{uk} ")) || item.trim() == uk)
+ });
+ sort = Some(match sort {
+ Some(s) if has_uk => s,
+ Some(s) => format!("{s},{uk} asc"),
+ None => format!("{uk} asc"),
+ });
+ }
+ if let Some(sort) = sort {
+ body["sort"] = Value::String(sort);
+ }
+ if let Some(mark) = cursor_mark {
+ body["params"] = serde_json::json!({ "cursorMark": mark });
+ }
+ Ok(body)
+}
+
+#[derive(Deserialize)]
+struct SolrSelectResponse {
+ #[serde(default)]
+ response: SolrResponseBody,
+ #[serde(rename = "nextCursorMark", default)]
+ next_cursor_mark: Option<String>,
+}
+
+#[derive(Deserialize, Default)]
+struct SolrResponseBody {
+ #[serde(rename = "numFound", default)]
+ num_found: u64,
+ #[serde(default)]
+ docs: Vec<Value>,
+}
+
+async fn solr_select(client: &SolrClient, core: &str, body: &Value) -> Result<SolrSelectResponse, String> {
+ let path = client.core_path(core, "query");
+ let resp = client.post(&path).json(body).send().await.map_err(|e| format!("Solr request failed: {e}"))?;
+ let status = resp.status();
+ let text = resp.text().await.map_err(|e| format!("Solr response read failed: {e}"))?;
+ if !status.is_success() {
+ return Err(format!("Solr error: {}", solr_error_message(&text)));
+ }
+ serde_json::from_str(&text).map_err(|e| format!("Solr parse error: {e}"))
+}
+
+fn solr_docs_to_document_result(
+ docs: Vec<Value>,
+ unique_key: Option<&str>,
+ total: u64,
+ next_cursor: Option<String>,
+) -> Result<DocumentQueryResult, String> {
+ let documents: Vec<Value> = docs
+ .into_iter()
+ .map(|doc| {
+ let Value::Object(mut map) = doc else { return doc };
+ if let Some(uk) = unique_key {
+ if let Some(id) = map.get(uk).cloned() {
+ map.insert("_id".to_string(), id);
+ }
+ }
+ Value::Object(map)
+ })
+ .collect();
+
+ // 与 ES 驱动一致:保留原始 JSON 数字字面量,避免 IPC/JS Number 精度损失。
+ let raw_documents = documents
+ .iter()
+ .map(serde_json::to_string)
+ .collect::<Result<Vec<_>, _>>()
+ .map_err(|e| format!("Solr document serialization failed: {e}"))?;
+
+ Ok(DocumentQueryResult {
+ documents,
+ raw_documents: Some(raw_documents),
+ extended_documents: None,
+ total,
+ total_is_exact: true,
+ next_cursor,
+ })
+}
+
+pub async fn find_documents(
+ client: &SolrClient,
+ core: &str,
+ skip: u64,
+ limit: i64,
+ filter: Option<&str>,
+ sort: Option<&str>,
+) -> Result<DocumentQueryResult, String> {
+ let unique_key = client.unique_key(core).await;
+ let body = solr_query_body(filter, sort, skip, limit, None, None)?;
+ let result = solr_select(client, core, &body).await?;
+ solr_docs_to_document_result(result.response.docs, unique_key.as_deref(), result.response.num_found, None)
+}
+
+/// cursorMark 分页游标:携带过滤条件指纹,翻页途中修改条件时明确报错而不是静默错位。
+#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
+struct SolrPageCursor {
+ collection: String,
+ filter: Option<String>,
+ sort: Option<String>,
+ mark: String,
+}
+
+fn encode_solr_cursor(cursor: &SolrPageCursor) -> Result<String, String> {
+ serde_json::to_string(cursor).map_err(|e| format!("Failed to encode Solr cursor: {e}"))
+}
+
+fn decode_solr_cursor(cursor: &str) -> Result<SolrPageCursor, String> {
+ serde_json::from_str(cursor).map_err(|e| format!("Invalid Solr cursor: {e}"))
+}
+
+pub async fn find_documents_with_cursor(
+ client: &SolrClient,
+ core: &str,
+ limit: i64,
+ filter: Option<&str>,
+ sort: Option<&str>,
+ cursor: Option<&str>,
+) -> Result<DocumentQueryResult, String> {
+ let unique_key = client.unique_key(core).await;
+ let mark = match cursor {
+ None => "*".to_string(),
+ Some(raw) => {
+ let decoded = decode_solr_cursor(raw)?;
+ if decoded.collection != core || decoded.filter.as_deref() != filter || decoded.sort.as_deref() != sort {
+ return Err("Solr cursor cannot be reused after the collection, filter, or sort changed".to_string());
+ }
+ decoded.mark
+ }
+ };
+
+ let body = solr_query_body(filter, sort, 0, limit, Some(&mark), unique_key.as_deref())?;
+ let result = solr_select(client, core, &body).await?;
+
+ // Solr 用「nextCursorMark == 传入 mark」表示游标耗尽。
+ let next_cursor = match result.next_cursor_mark {
+ Some(next) if next != mark => Some(encode_solr_cursor(&SolrPageCursor {
+ collection: core.to_string(),
+ filter: filter.map(str::to_string),
+ sort: sort.map(str::to_string),
+ mark: next,
+ })?),
+ _ => None,
+ };
+
+ solr_docs_to_document_result(result.response.docs, unique_key.as_deref(), result.response.num_found, next_cursor)
+}
+
+/// cursorMark 在服务端无状态,无需释放资源。
+pub async fn close_cursor(_client: &SolrClient, _cursor: &str) -> Result<(), String> {
+ Ok(())
+}
+
+pub async fn count_documents(client: &SolrClient, core: &str, filter: Option<&str>) -> Result<u64, String> {
+ let body = solr_query_body(filter, None, 0, 0, None, None)?;
+ let result = solr_select(client, core, &body).await?;
+ Ok(result.response.num_found)
+}
+
+fn solr_update_body_doc(client_doc: &mut serde_json::Map<String, Value>, unique_key: Option<&str>, id: Option<&str>) {
+ // `_id`/`_routing` 是前端文档编辑器侧的元字段,不写入 Solr。数值/布尔型
+ // `_id`(数值 uniqueKey 的 core)序列化为字符串写入,避免静默丢失文档标识。
+ let id_value = id.map(str::to_string).or_else(|| {
+ client_doc.get("_id").and_then(|v| match v {
+ Value::String(s) => Some(s.clone()),
+ Value::Number(n) => Some(n.to_string()),
+ Value::Bool(b) => Some(b.to_string()),
+ _ => None,
+ })
+ });
+ if let (Some(uk), Some(id)) = (unique_key, id_value) {
+ client_doc.insert(uk.to_string(), Value::String(id));
+ }
+ client_doc.remove("_id");
+ client_doc.remove("_routing");
+}
+
+async fn solr_post_update(client: &SolrClient, core: &str, body: &Value) -> Result<(), String> {
+ // softCommit 让变更立刻对搜索可见(对齐 ES `refresh=true` 的交互语义),
+ // 持久化仍由后台 hard commit 保证。
+ let path = client.core_path(core, "update?softCommit=true");
+ let resp = client.post(&path).json(body).send().await.map_err(|e| format!("Solr request failed: {e}"))?;
+ if !resp.status().is_success() {
+ let body = resp.text().await.unwrap_or_default();
+ return Err(format!("Solr error: {}", solr_error_message(&body)));
+ }
+ Ok(())
+}
+
+pub async fn insert_document(client: &SolrClient, core: &str, doc_json: &str) -> Result<String, String> {
+ let mut doc: Value = serde_json::from_str(doc_json).map_err(|e| format!("Invalid JSON: {e}"))?;
+ let unique_key = client.unique_key(core).await;
+ let Value::Object(ref mut map) = doc else {
+ return Err("Solr document must be a JSON object".to_string());
+ };
+ solr_update_body_doc(map, unique_key.as_deref(), None);
+ let inserted_id = unique_key.as_deref().and_then(|uk| map.get(uk).and_then(Value::as_str).map(str::to_string));
+ solr_post_update(client, core, &Value::Array(vec![doc])).await?;
+ Ok(inserted_id.unwrap_or_default())
+}
+
+pub async fn update_document(client: &SolrClient, core: &str, id: &str, doc_json: &str) -> Result<u64, String> {
+ let mut doc: Value = serde_json::from_str(doc_json).map_err(|e| format!("Invalid JSON: {e}"))?;
+ let unique_key = client.unique_key(core).await;
+ let Value::Object(ref mut map) = doc else {
+ return Err("Solr document must be a JSON object".to_string());
+ };
+ solr_update_body_doc(map, unique_key.as_deref(), Some(id));
+ // Solr 按 uniqueKey 整篇覆盖,等价于 ES 的 PUT /{index}/_doc/{id}。
+ solr_post_update(client, core, &Value::Array(vec![doc])).await?;
+ Ok(1)
+}
+
+pub async fn delete_document(client: &SolrClient, core: &str, id: &str) -> Result<u64, String> {
+ solr_post_update(client, core, &serde_json::json!({ "delete": { "id": id } })).await?;
+ Ok(1)
+}
+
+// ---------------------------------------------------------------------------
+// REST console:`METHOD /path` + 可选 JSON body 透传,对齐 ES 编辑器体验。
+// ---------------------------------------------------------------------------
+
+struct SolrRestRequest {
+ method: Method,
+ path: String,
+ body: Option<String>,
+}
+
+fn strip_leading_solr_comments(input: &str) -> &str {
+ let mut rest = input;
+ loop {
+ rest = rest.trim_start();
+ if let Some(comment) = rest.strip_prefix('#').or_else(|| rest.strip_prefix("//")) {
+ rest = comment.split_once('\n').map_or("", |(_, remaining)| remaining);
+ continue;
+ }
+ if let Some(comment) = rest.strip_prefix("/*") {
+ rest = comment.split_once("*/").map_or("", |(_, remaining)| remaining);
+ continue;
+ }
+ return rest.trim();
+ }
+}
+
+fn parse_solr_rest_request(input: &str) -> Result<SolrRestRequest, String> {
+ let input = strip_leading_solr_comments(input);
+ if input.is_empty() {
+ return Err("Invalid query: expected METHOD /path".to_string());
+ }
+ let (request_line, body) = input.split_once('\n').map_or((input, None), |(line, body)| {
+ let body = body.trim();
+ (line, (!body.is_empty()).then(|| body.to_string()))
+ });
+ let (method, path) =
+ request_line.trim().split_once(char::is_whitespace).ok_or("Invalid query: expected METHOD /path")?;
+ let method = method.to_ascii_uppercase();
+ let method = Method::from_bytes(method.as_bytes())
+ .map_err(|_| format!("Unsupported HTTP method: {method}. Use GET, POST, PUT, DELETE, or HEAD."))?;
+ if !matches!(method, Method::GET | Method::POST | Method::PUT | Method::DELETE | Method::HEAD) {
+ return Err(format!("Unsupported HTTP method: {}. Use GET, POST, PUT, DELETE, or HEAD.", method.as_str()));
+ }
+
+ let mut path = path.trim().to_string();
+ if path.is_empty() {
+ return Err("Invalid query: expected METHOD /path".to_string());
+ }
+ if !path.starts_with('/') {
+ path = format!("/{path}");
+ }
+ // base_url 已含 /solr 上下文;用户照抄文档写的 `/solr/xxx` 要去掉前缀避免 /solr/solr。
+ if path == "/solr" {
+ path = "/".to_string();
+ } else if let Some(rest) = path.strip_prefix("/solr/") {
+ path = format!("/{rest}");
+ }
+ // Solr 默认 wt 取决于 handler 配置(老版本常是 XML);统一补 wt=json 让响应可解析。
+ if !path.split('?').nth(1).is_some_and(|query| query.split('&').any(|p| p.split('=').next() == Some("wt"))) {
+ path.push(if path.contains('?') { '&' } else { '?' });
+ path.push_str("wt=json");
+ }
+ Ok(SolrRestRequest { method, path, body })
+}
+
+fn solr_docs_to_table(docs: &[Value]) -> (Vec<String>, Vec<String>, Vec<Vec<Value>>) {
+ let mut columns = Vec::<String>::new();
+ let mut column_indexes = HashMap::<String, usize>::new();
+ let mut json_column_indexes = HashSet::<usize>::new();
+ let mut rows = Vec::<Vec<Value>>::with_capacity(docs.len());
+
+ for doc in docs {
+ let mut row = vec![Value::Null; columns.len()];
+ if let Some(object) = doc.as_object() {
+ for (key, value) in object {
+ let is_json_cell = matches!(value, Value::Array(_) | Value::Object(_));
+ let value = if is_json_cell { Value::String(value.to_string()) } else { value.clone() };
+ match column_indexes.get(key).copied() {
+ Some(index) => {
+ if is_json_cell {
+ json_column_indexes.insert(index);
+ }
+ row[index] = value;
+ }
+ None => {
+ let index = columns.len();
+ if is_json_cell {
+ json_column_indexes.insert(index);
+ }
+ column_indexes.insert(key.clone(), index);
+ columns.push(key.clone());
+ for previous_row in rows.iter_mut() {
+ previous_row.push(Value::Null);
+ }
+ row.push(value);
+ }
+ }
+ }
+ }
+ rows.push(row);
+ }
+
+ let column_types = columns
+ .iter()
+ .enumerate()
+ .map(|(index, _)| {
+ if json_column_indexes.contains(&index) {
+ return "json".to_string();
+ }
+ let mut inferred = None;
+ for value in rows.iter().filter_map(|row| row.get(index)) {
+ let value_type = match value {
+ Value::Null => continue,
+ Value::Bool(_) => "boolean",
+ Value::Number(_) => "number",
+ Value::String(_) => "text",
+ Value::Array(_) | Value::Object(_) => "json",
+ };
+ inferred = match inferred {
+ None => Some(value_type),
+ Some(existing) if existing == value_type => Some(existing),
+ Some(_) => Some("json"),
+ };
+ }
+ inferred.unwrap_or("unknown").to_string()
+ })
+ .collect();
+ (columns, column_types, rows)
+}
+
+fn solr_table_result(
+ columns: Vec<String>,
+ column_types: Vec<String>,
+ rows: Vec<Vec<Value>>,
+ start: std::time::Instant,
+) -> QueryResult {
+ let row_count = rows.len() as u64;
+ QueryResult {
+ columns,
+ column_types,
+ column_sortables: vec![],
+ spatial_columns: vec![],
+ spatial_values: vec![],
+ rows,
+ affected_rows: row_count,
+ execution_time_ms: start.elapsed().as_millis(),
+ server_execute_time_us: None,
+ truncated: false,
+ session_id: None,
+ has_more: false,
+ elasticsearch_raw_body: None,
+ messages: Vec::new(),
+ }
+}
+
+fn solr_raw_json_response_result(status: u16, body_text: impl Into<String>, start: std::time::Instant) -> QueryResult {
+ QueryResult {
+ columns: vec!["status".to_string(), "response".to_string()],
+ column_types: Vec::new(),
+ column_sortables: vec![],
+ spatial_columns: vec![],
+ spatial_values: vec![],
+ rows: vec![vec![Value::Number(status.into()), Value::String(body_text.into())]],
+ affected_rows: 0,
+ execution_time_ms: start.elapsed().as_millis(),
+ server_execute_time_us: None,
+ truncated: false,
+ session_id: None,
+ has_more: false,
+ elasticsearch_raw_body: None,
+ messages: Vec::new(),
+ }
+}
+
+fn solr_rest_exceeds_table_limits(docs: &[Value]) -> bool {
+ if docs.len() > SOLR_REST_TABLE_MAX_ROWS {
+ return true;
+ }
+ let mut columns = BTreeSet::<&str>::new();
+ for doc in docs {
+ if let Some(object) = doc.as_object() {
+ columns.extend(object.keys().map(String::as_str));
+ }
+ if docs.len().saturating_mul(columns.len()) > SOLR_REST_TABLE_MAX_CELLS {
+ return true;
+ }
+ }
+ false
+}
+
+fn parse_solr_rest_response(status: u16, body_text: &str, start: std::time::Instant) -> Result<QueryResult, String> {
+ if body_text.trim().is_empty() {
+ return Ok(solr_raw_json_response_result(status, "null", start));
+ }
+ if status >= 400 || body_text.len() > SOLR_REST_TABLE_MAX_BODY_BYTES {
+ return Ok(solr_raw_json_response_result(status, body_text, start));
+ }
+ match serde_json::from_str::<Value>(body_text) {
+ Ok(body) => {
+ if let Some(docs) = body.pointer("/response/docs").and_then(Value::as_array) {
+ if solr_rest_exceeds_table_limits(docs) {
+ return Ok(solr_raw_json_response_result(status, body_text, start));
+ }
+ let (columns, column_types, rows) = solr_docs_to_table(docs);
+ let mut result = solr_table_result(columns, column_types, rows, start);
+ // 让前端可以在表格视图与原始 JSON 响应之间切换。
+ result.elasticsearch_raw_body = Some(body_text.to_string());
+ return Ok(result);
+ }
+ Ok(solr_raw_json_response_result(
+ status,
+ serde_json::to_string_pretty(&body).unwrap_or_else(|_| body_text.to_string()),
+ start,
+ ))
+ }
+ Err(_) => {
+ let rows: Vec<Vec<Value>> = body_text.lines().map(|line| vec![Value::String(line.to_string())]).collect();
+ let mut result = solr_table_result(vec!["response".to_string()], Vec::new(), rows, start);
+ result.affected_rows = result.rows.len() as u64;
+ Ok(result)
+ }
+ }
+}
+
+pub async fn execute_rest_query(client: &SolrClient, input: &str) -> Result<QueryResult, String> {
+ let start = std::time::Instant::now();
+ let request = parse_solr_rest_request(input)?;
+ let mut builder = client.request(request.method, &request.path);
+ if let Some(body) = request.body {
+ let json: Value = serde_json::from_str(&body).map_err(|e| format!("Invalid JSON body: {e}"))?;
+ builder = builder.json(&json);
+ }
+ let resp = builder.send().await.map_err(|e| format!("Solr request failed: {e}"))?;
+ let status = resp.status().as_u16();
+ let body = resp.text().await.map_err(|e| format!("Solr response read failed: {e}"))?;
+ parse_solr_rest_response(status, &body, start)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use serde_json::json;
+
+ #[test]
+ fn base_url_appends_solr_context_when_missing() {
+ assert_eq!(normalize_solr_base_url("http://localhost:8983"), "http://localhost:8983/solr");
+ assert_eq!(normalize_solr_base_url("http://localhost:8983/"), "http://localhost:8983/solr");
+ assert_eq!(normalize_solr_base_url("http://localhost:8983/solr"), "http://localhost:8983/solr");
+ assert_eq!(normalize_solr_base_url("http://localhost:8983/solr/"), "http://localhost:8983/solr");
+ }
+
+ #[test]
+ fn filter_translation_covers_mongo_style_operators() {
+ let filters = solr_filters_from_document_filter(Some(
+ r#"{"city":"长治","age":{"$gte":18,"$lt":60},"status":{"$ne":"closed"},"tags":{"$in":["a","b"]},"deleted":null}"#,
+ ))
+ .unwrap();
+ assert_eq!(
+ filters,
+ vec![
+ "city:\"长治\"".to_string(),
+ "age:[18 TO 60}".to_string(),
+ "-status:\"closed\"".to_string(),
+ "tags:(\"a\" OR \"b\")".to_string(),
+ "-deleted:*".to_string()
+ ]
+ );
+ }
+
+ #[test]
+ fn or_group_wraps_clauses() {
+ let filters = solr_filters_from_document_filter(Some(r#"{"$or":[{"city":"长治"},{"city":"上海"}]}"#)).unwrap();
+ assert_eq!(filters, vec!["(city:\"长治\" OR city:\"上海\")".to_string()]);
+ }
+
+ #[test]
+ fn sort_translation_matches_solr_syntax() {
+ assert_eq!(
+ solr_sort_from_document_sort(Some(r#"{"created_at":-1}"#)).unwrap().as_deref(),
+ Some("created_at desc")
+ );
+ assert_eq!(solr_sort_from_document_sort(None).unwrap(), None);
+ }
+
+ #[test]
+ fn cursor_body_appends_unique_key_sort() {
+ let body = solr_query_body(None, Some(r#"{"ts":-1}"#), 0, 10, Some("*"), Some("id")).unwrap();
+ assert_eq!(body["sort"], json!("ts desc,id asc"));
+ assert_eq!(body["params"], json!({ "cursorMark": "*" }));
+ }
+
+ #[test]
+ fn rest_request_strips_solr_prefix_and_adds_wt() {
+ let req = parse_solr_rest_request("GET /solr/gettingstarted/select?q=*:*").unwrap();
+ assert_eq!(req.path, "/gettingstarted/select?q=*:*&wt=json");
+ let req = parse_solr_rest_request("GET /gettingstarted/select?q=*:*&wt=xml").unwrap();
+ assert_eq!(req.path, "/gettingstarted/select?q=*:*&wt=xml");
+ }
+}
diff --git a/crates/dbx-mcp/src/backend.rs b/crates/dbx-mcp/src/backend.rs
index da02fa2468..c86ac562f2 100644
--- a/crates/dbx-mcp/src/backend.rs
+++ b/crates/dbx-mcp/src/backend.rs
@@ -2663,9 +2663,32 @@ mod tests {
fn parses_database_type_using_dbx_protocol_names() {
assert_eq!(parse_database_type("Postgres").unwrap(), DatabaseType::Postgres);
assert_eq!(parse_database_type("mongodb").unwrap(), DatabaseType::MongoDb);
+ assert_eq!(parse_database_type("Solr").unwrap(), DatabaseType::Solr);
+ assert_eq!(parse_database_type("solr").unwrap(), DatabaseType::Solr);
assert!(parse_database_type("unknown").is_err());
}
+ #[test]
+ fn new_connection_config_accepts_solr() {
+ // Solr connections are created through the generic descriptor path; the
+ // REST core lives in the query text, not a database field.
+ let connection = new_connection_config(
+ "solr".to_string(),
+ "solr".to_string(),
+ DatabaseType::Solr,
+ "localhost".to_string(),
+ 8983,
+ String::new(),
+ String::new(),
+ None,
+ false,
+ None,
+ )
+ .unwrap();
+ assert_eq!(connection.db_type, DatabaseType::Solr);
+ assert_eq!(connection.port, 8983);
+ }
+
#[test]
fn native_mysql_transaction_gate_accepts_the_builtin_mysql_profile_only() {
let mut connection: ConnectionConfig = serde_json::from_value(json!({
diff --git a/crates/dbx-mcp/src/server.rs b/crates/dbx-mcp/src/server.rs
index 503691a6c2..ee83c5c556 100644
--- a/crates/dbx-mcp/src/server.rs
+++ b/crates/dbx-mcp/src/server.rs
@@ -6127,6 +6127,20 @@ mod tests {
assert!(!sql_requires_batch_execution("SELECT 1", DatabaseType::Mysql));
}
+ #[test]
+ fn solr_rest_requests_stay_on_the_single_request_path() {
+ // Solr speaks the DBX REST-console format (`METHOD /path` + optional
+ // JSON body), not SQL. A single request must not be routed through the
+ // `;`-splitting batch executor.
+ assert!(!sql_requires_batch_execution("GET /mycore/select?q=*:*&rows=20", DatabaseType::Solr));
+ assert!(!sql_requires_batch_execution(
+ "POST /mycore/update\n{\"add\":{\"doc\":{\"id\":\"1\",\"title\":\"x\"}}}",
+ DatabaseType::Solr
+ ));
+ // A REST request is never a forbidden database switch.
+ assert!(!mcp_sql_has_forbidden_database_switch("GET /mycore/select?q=*:*", DatabaseType::Solr));
+ }
+
#[test]
fn format_batch_results_renders_failed_statement() {
let results = vec![crate::backend::BatchStatementResult {
diff --git a/crates/dbx-sql/src/query_execution_sql.rs b/crates/dbx-sql/src/query_execution_sql.rs
index 32c4c1b0f9..85033287b3 100644
--- a/crates/dbx-sql/src/query_execution_sql.rs
+++ b/crates/dbx-sql/src/query_execution_sql.rs
@@ -200,6 +200,7 @@ pub fn supports_sql_query(database_type: DatabaseType) -> bool {
| DatabaseType::MongoDb
| DatabaseType::Elasticsearch
| DatabaseType::Easysearch
+ | DatabaseType::Solr
| DatabaseType::Qdrant
| DatabaseType::Milvus
| DatabaseType::Weaviate
@@ -334,6 +335,9 @@ pub enum SearchEngineQueryRisk {
}
pub fn classify_search_engine_query_risk(source: &str, database_type: DatabaseType) -> Option<SearchEngineQueryRisk> {
+ if database_type == DatabaseType::Solr {
+ return classify_solr_query_risk(source);
+ }
if !matches!(database_type, DatabaseType::Elasticsearch | DatabaseType::Easysearch) {
return None;
}
@@ -382,6 +386,113 @@ pub fn classify_search_engine_query_risk(source: &str, database_type: DatabaseTy
}
}
+/// Solr REST 写请求集中在 `/{core}/update`(含 JSON/XML/CSV update handlers);
+/// 只读 POST handler 名单之外的写路径(`/admin/*`、`/schema`、`/config`、
+/// collection/core 管理)一律按 Dangerous 处理。
+fn classify_solr_query_risk(source: &str) -> Option<SearchEngineQueryRisk> {
+ const READ_ONLY_POST_ENDPOINTS: &[&str] = &[
+ "select",
+ "query",
+ "get",
+ "export",
+ "terms",
+ "suggest",
+ "spell",
+ "mlt",
+ "sql",
+ "graph",
+ "clustering",
+ "tvrh",
+ "luke",
+ "elevate",
+ "browse",
+ "debug",
+ ];
+ let source = strip_leading_search_engine_comments(source);
+ let request_line = source.lines().next()?.trim();
+ let mut parts = request_line.split_whitespace();
+ let method = parts.next()?.to_ascii_uppercase();
+ let raw_path = parts.next()?;
+ let path = raw_path.split('?').next().unwrap_or(raw_path).trim_end_matches('/');
+ let mut segments: Vec<&str> = path.split('/').filter(|segment| !segment.is_empty()).collect();
+ if segments.first().is_some_and(|segment| segment.eq_ignore_ascii_case("solr")) {
+ segments.remove(0);
+ }
+ let endpoint = segments.last().copied().unwrap_or("");
+ // update handler 的变体(/update/json、/update/json/docs、/update/csv)在
+ // update 段之后还有子路径,所以不能只检查末段。
+ let is_update_path = segments.iter().any(|segment| segment.starts_with("update") || *segment == "commit");
+
+ match method.as_str() {
+ // Solr 的 update handler 也响应 GET(commit/optimize/stream.body 都能
+ // 改数据),所以 update 路径对任何方法都算写,不能只放行 POST。
+ _ if is_update_path => Some(SearchEngineQueryRisk::Write),
+ "GET" | "HEAD" | "OPTIONS" => {
+ if solr_admin_request_is_mutation(raw_path, &segments)
+ || solr_replication_request_is_mutation(raw_path, &segments)
+ {
+ Some(SearchEngineQueryRisk::Dangerous)
+ } else {
+ Some(SearchEngineQueryRisk::ReadOnly)
+ }
+ }
+ "POST" if READ_ONLY_POST_ENDPOINTS.contains(&endpoint) => Some(SearchEngineQueryRisk::ReadOnly),
+ "POST" | "PUT" | "PATCH" | "DELETE" => Some(SearchEngineQueryRisk::Dangerous),
+ _ => None,
+ }
+}
+
+/// CoreAdmin/Collections 管理端点接受 GET 触发的变更动作
+///(`GET /admin/cores?action=CREATE&name=x` 会真实建 core),只有显式只读的
+/// action 才能算 ReadOnly;其余带 action 的一律按 Dangerous 处理。
+fn solr_admin_request_is_mutation(raw_path: &str, segments: &[&str]) -> bool {
+ let is_admin_target = segments.windows(2).any(|pair| {
+ pair[0].eq_ignore_ascii_case("admin")
+ && matches!(pair[1].to_ascii_lowercase().as_str(), "cores" | "collections")
+ });
+ if !is_admin_target {
+ return false;
+ }
+ let Some(query) = raw_path.split('?').nth(1) else { return false };
+ let action = query.split('&').find_map(|param| {
+ param.split_once('=').filter(|(key, _)| key.eq_ignore_ascii_case("action")).map(|(_, value)| value)
+ });
+ match action {
+ None => false,
+ Some(action) => !matches!(action.to_ascii_uppercase().as_str(), "STATUS" | "REQUESTSTATUS" | "LIST"),
+ }
+}
+
+/// ReplicationHandler 也接受 GET 触发的变更
+///(`GET /{core}/replication?command=disablereplication` 会真实停用复制),
+/// 只有显式只读的 command 才算 ReadOnly;不带 command 时 handler 默认返回
+/// 详情,按只读处理。
+fn solr_replication_request_is_mutation(raw_path: &str, segments: &[&str]) -> bool {
+ if !segments.last().is_some_and(|segment| segment.eq_ignore_ascii_case("replication")) {
+ return false;
+ }
+ const READ_ONLY_COMMANDS: &[&str] = &[
+ "details",
+ "restorestatus",
+ "filelist",
+ "filecontent",
+ "filedownload",
+ "filemtime",
+ "indexversion",
+ "showversion",
+ ];
+ let Some(query) = raw_path.split('?').nth(1) else {
+ return false;
+ };
+ let command = query.split('&').find_map(|param| {
+ param.split_once('=').filter(|(key, _)| key.eq_ignore_ascii_case("command")).map(|(_, value)| value)
+ });
+ match command {
+ None => false,
+ Some(command) => !READ_ONLY_COMMANDS.iter().any(|readonly| readonly.eq_ignore_ascii_case(command)),
+ }
+}
+
fn strip_leading_search_engine_comments(input: &str) -> &str {
let mut rest = input;
loop {
@@ -2015,6 +2126,86 @@ mod tests {
));
}
+ #[test]
+ fn classifies_solr_rest_requests() {
+ // Read-only requests: select/query/get and other read handlers.
+ assert!(!is_write_sql_for_database("GET /mycore/select?q=*:*&rows=20", DatabaseType::Solr));
+ assert!(!is_write_sql_for_database(
+ "POST /mycore/query\n{\"query\":\"name:foo\",\"limit\":10}",
+ DatabaseType::Solr
+ ));
+ assert!(!is_write_sql_for_database("GET /mycore/schema/fields", DatabaseType::Solr));
+
+ // Document writes hit the update handlers, including the `/update/...`
+ // variants whose last path segment is not literally `update`.
+ assert!(is_write_sql_for_database(
+ "POST /mycore/update\n{\"add\":{\"doc\":{\"id\":\"1\"}}}",
+ DatabaseType::Solr
+ ));
+ assert!(is_write_sql_for_database("POST /mycore/update/json/docs\n{\"id\":\"1\"}", DatabaseType::Solr));
+ assert!(is_write_sql_for_database("GET /mycore/update?commit=true", DatabaseType::Solr));
+
+ // CoreAdmin actions mutate over GET too; only the read whitelist stays safe.
+ assert_eq!(
+ classify_search_engine_query_risk("GET /admin/cores?action=CREATE&name=x", DatabaseType::Solr),
+ Some(SearchEngineQueryRisk::Dangerous)
+ );
+ assert_eq!(
+ classify_search_engine_query_risk("GET /admin/cores?action=STATUS", DatabaseType::Solr),
+ Some(SearchEngineQueryRisk::ReadOnly)
+ );
+ assert_eq!(
+ classify_search_engine_query_risk("GET /admin/info/system", DatabaseType::Solr),
+ Some(SearchEngineQueryRisk::ReadOnly)
+ );
+
+ // Replication commands mutate over GET too; only the read whitelist stays safe.
+ assert_eq!(
+ classify_search_engine_query_risk("GET /mycore/replication?command=details", DatabaseType::Solr),
+ Some(SearchEngineQueryRisk::ReadOnly)
+ );
+ assert_eq!(
+ classify_search_engine_query_risk("GET /mycore/replication?command=restorestatus", DatabaseType::Solr),
+ Some(SearchEngineQueryRisk::ReadOnly)
+ );
+ assert_eq!(
+ classify_search_engine_query_risk("GET /mycore/replication?command=filelist", DatabaseType::Solr),
+ Some(SearchEngineQueryRisk::ReadOnly)
+ );
+ assert_eq!(
+ classify_search_engine_query_risk("GET /mycore/replication", DatabaseType::Solr),
+ Some(SearchEngineQueryRisk::ReadOnly)
+ );
+ assert_eq!(
+ classify_search_engine_query_risk("GET /mycore/replication?command=disablereplication", DatabaseType::Solr),
+ Some(SearchEngineQueryRisk::Dangerous)
+ );
+ assert_eq!(
+ classify_search_engine_query_risk("GET /mycore/replication?command=enablereplication", DatabaseType::Solr),
+ Some(SearchEngineQueryRisk::Dangerous)
+ );
+ assert_eq!(
+ classify_search_engine_query_risk("GET /mycore/replication?command=fetchindex", DatabaseType::Solr),
+ Some(SearchEngineQueryRisk::Dangerous)
+ );
+
+ // Core/schema/admin operations are dangerous.
+ assert_eq!(
+ classify_search_engine_query_risk("POST /admin/cores?action=CREATE&name=x", DatabaseType::Solr),
+ Some(SearchEngineQueryRisk::Dangerous)
+ );
+ assert_eq!(
+ classify_search_engine_query_risk(
+ "POST /mycore/schema\n{\"add-field\":{\"name\":\"x\",\"type\":\"string\"}}",
+ DatabaseType::Solr
+ ),
+ Some(SearchEngineQueryRisk::Dangerous)
+ );
+
+ // Non-Solr types never take this classifier.
+ assert!(classify_search_engine_query_risk("POST /mycore/update", DatabaseType::Postgres).is_none());
+ }
+
#[test]
fn excludes_victoriametrics_from_sql_query_paths() {
assert!(!supports_sql_query(DatabaseType::VictoriaMetrics));
diff --git a/crates/dbx-sql/src/query_result_sql.rs b/crates/dbx-sql/src/query_result_sql.rs
index a282ef6923..c0f7c5a158 100644
--- a/crates/dbx-sql/src/query_result_sql.rs
+++ b/crates/dbx-sql/src/query_result_sql.rs
@@ -538,7 +538,10 @@ fn err(reason: &str) -> QuerySqlBuildResult {
}
fn unsupported_pagination_type(database_type: Option<DatabaseType>) -> bool {
- matches!(database_type, Some(DatabaseType::Neo4j | DatabaseType::MongoDb | DatabaseType::Redis))
+ matches!(
+ database_type,
+ Some(DatabaseType::Neo4j | DatabaseType::MongoDb | DatabaseType::Redis | DatabaseType::Solr)
+ )
}
fn find_query_result_statement_at_cursor(sql: &str, cursor_pos: usize, database_type: Option<DatabaseType>) -> String {
diff --git a/crates/dbx-sql/src/sql_dialect/ddl_profile.rs b/crates/dbx-sql/src/sql_dialect/ddl_profile.rs
index e7e57652b8..62a430bec0 100644
--- a/crates/dbx-sql/src/sql_dialect/ddl_profile.rs
+++ b/crates/dbx-sql/src/sql_dialect/ddl_profile.rs
@@ -821,7 +821,7 @@ pub fn profile_for(db_type: DatabaseType) -> DdlDialectProfile {
Plugin => conservative_ansi(db_type),
// Non-tabular / not applicable for relational CREATE TABLE
- Redis | MongoDb | DynamoDb | Elasticsearch | Easysearch | Meilisearch | Qdrant | Milvus | Weaviate
+ Redis | MongoDb | DynamoDb | Elasticsearch | Easysearch | Solr | Meilisearch | Qdrant | Milvus | Weaviate
| ChromaDb | Neo4j | Cassandra | Etcd | ZooKeeper | Nacos | Consul | InfluxDb3 | VictoriaMetrics
| MessageQueue | Mqtt | Hbase => conservative_ansi(db_type),
}
diff --git a/crates/dbx-types/src/models/connection.rs b/crates/dbx-types/src/models/connection.rs
index bb23e90613..2b25b27323 100644
--- a/crates/dbx-types/src/models/connection.rs
+++ b/crates/dbx-types/src/models/connection.rs
@@ -1115,6 +1115,7 @@ impl ConnectionConfig {
DatabaseType::Oracle => format!("oracle://{host}:{port}{db_part}"),
DatabaseType::Elasticsearch
| DatabaseType::Easysearch
+ | DatabaseType::Solr
| DatabaseType::Meilisearch
| DatabaseType::Hbase
| DatabaseType::Qdrant
@@ -1299,6 +1300,7 @@ impl ConnectionConfig {
}
DatabaseType::Elasticsearch
| DatabaseType::Easysearch
+ | DatabaseType::Solr
| DatabaseType::Meilisearch
| DatabaseType::Hbase
| DatabaseType::Qdrant
diff --git a/plugins/connection-types/profiles/catalog.yaml b/plugins/connection-types/profiles/catalog.yaml
index 410a27e7f4..5e5c64b13e 100644
--- a/plugins/connection-types/profiles/catalog.yaml
+++ b/plugins/connection-types/profiles/catalog.yaml
@@ -137,6 +137,13 @@ profiles:
port: 9200
user: ""
category: document
+ - id: solr
+ dbType: solr
+ label: Apache Solr
+ icon: solr
+ port: 8983
+ user: ""
+ category: document
- id: meilisearch
dbType: meilisearch
label: Meilisearch
diff --git a/plugins/connection-types/solr.yaml b/plugins/connection-types/solr.yaml
new file mode 100644
index 0000000000..ac76edcdcd
--- /dev/null
+++ b/plugins/connection-types/solr.yaml
@@ -0,0 +1,29 @@
+schemaVersion: 1
+order: 165
+dbType: solr
+rustVariant: Solr
+label: Apache Solr
+runtimeMode: native
+mcpMode: bridge
+singleConnectionPool: false
+metadataConnectionScoped: false
+skipTcpProbe: false
+defaultPort: 8983
+supportLevel: browse
+capabilities:
+ queryExecution: true
+ metadataBrowse: true
+ objectBrowser: false
+ objectSource: false
+ schemaSearch: false
+ diagram: false
+ tableDataEdit: false
+ tableStructureEdit: false
+ tableImport: false
+ dataTransfer: false
+ sqlFileExecution: false
+ databaseCreate: false
+ fieldLineage: false
+ sqlExplain: false
+ userAdmin: false
+ driverManagement: false
diff --git a/src-tauri/src/commands/connection.rs b/src-tauri/src/commands/connection.rs
index f7c5438672..0a8b02cb46 100644
--- a/src-tauri/src/commands/connection.rs
+++ b/src-tauri/src/commands/connection.rs
@@ -1461,6 +1461,23 @@ async fn test_connection_with_info_inner(
.await
.map(|_| "Connection successful".to_string())
}
+ DatabaseType::Solr => {
+ let mut client = db::solr_driver::SolrClient::from_config(
+ &url,
+ Some(&config.username),
+ Some(&config.password),
+ config.ssl,
+ config.url_params.as_deref(),
+ config.external_config.as_ref(),
+ connect_timeout,
+ Some(config.ca_cert_path.as_str()),
+ Some(config.client_cert_path.as_str()),
+ Some(config.client_key_path.as_str()),
+ )?;
+ db::solr_driver::test_connection(&mut client, connect_timeout)
+ .await
+ .map(|_| "Connection successful".to_string())
+ }
DatabaseType::Meilisearch => {
let client = db::meilisearch_driver::MeilisearchClient::new_for_config(
&url,
@@ -1921,6 +1938,22 @@ pub async fn connect_db(
db::easysearch_driver::test_connection(&mut client, connect_timeout).await?;
PoolKind::Easysearch(client)
}
+ DatabaseType::Solr => {
+ let mut client = db::solr_driver::SolrClient::from_config(
+ &url,
+ Some(&db_config.username),
+ Some(&db_config.password),
+ db_config.ssl,
+ db_config.url_params.as_deref(),
+ db_config.external_config.as_ref(),
+ connect_timeout,
+ Some(db_config.ca_cert_path.as_str()),
+ Some(db_config.client_cert_path.as_str()),
+ Some(db_config.client_key_path.as_str()),
+ )?;
+ db::solr_driver::test_connection(&mut client, connect_timeout).await?;
+ PoolKind::Solr(client)
+ }
DatabaseType::Meilisearch => {
let client = db::meilisearch_driver::MeilisearchClient::new_for_config(
&url,