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。

fix(clickhouse): load table index metadata

t8y2521a3021c4c2
diff --git a/apps/desktop/src/components/grid/DataGrid.vue b/apps/desktop/src/components/grid/DataGrid.vue
index 2d0b980386..887520c85e 100644
--- a/apps/desktop/src/components/grid/DataGrid.vue
+++ b/apps/desktop/src/components/grid/DataGrid.vue
@@ -133,6 +133,7 @@ import { useCellDetailEditor, type UseCellDetailEditorReturn } from "@/composabl
import { useTheme } from "@/composables/useTheme";
import { useSettingsStore } from "@/stores/settingsStore";
import { nextDataGridSortState, type DataGridSortDirection } from "@/lib/dataGridSort";
+import { getTableMetadataCapabilities } from "@/lib/tableMetadataCapabilities";
const SqlPreviewPanel = defineAsyncComponent(() => import("@/components/editor/SqlPreviewPanel.vue"));
@@ -5175,6 +5176,7 @@ async function prefetchCopyStatements() {
const sqlOneLiner = computed(() => props.sql?.replace(/\s+/g, " ").trim() || "");
type TableInfoTab = "columns" | "indexes" | "foreignKeys" | "triggers" | "ddl";
+type TableInfoTabItem = { id: TableInfoTab; label: string; icon: Component; count?: number };
const TABLE_INFO_DRAWER_MIN_WIDTH = 240;
const CELL_DETAIL_PANEL_MIN_HEIGHT = 180;
@@ -5268,26 +5270,34 @@ function toggleCellDetailPanelLayout() {
});
}
-const tableInfoTabs = computed(
- () =>
- [
- {
- id: "columns" as const,
- label: t("grid.tableInfoColumns"),
- icon: ListTree,
- count: props.tableMeta?.columns.length,
- },
- { id: "indexes" as const, label: t("grid.tableInfoIndexes"), icon: KeyRound, count: indexes.value.length },
- {
- id: "foreignKeys" as const,
- label: t("grid.tableInfoForeignKeys"),
- icon: Link2,
- count: foreignKeys.value.length,
- },
- { id: "triggers" as const, label: t("grid.tableInfoTriggers"), icon: RotateCcw, count: triggers.value.length },
- { id: "ddl" as const, label: "DDL", icon: Code2 },
- ] satisfies Array<{ id: TableInfoTab; label: string; icon: Component; count?: number }>,
-);
+const tableMetadataCapabilities = computed(() => getTableMetadataCapabilities(props.databaseType));
+const tableInfoTabs = computed(() => {
+ const tabs: TableInfoTabItem[] = [
+ {
+ id: "columns",
+ label: t("grid.tableInfoColumns"),
+ icon: ListTree,
+ count: props.tableMeta?.columns.length,
+ },
+ { id: "indexes", label: t("grid.tableInfoIndexes"), icon: KeyRound, count: indexes.value.length },
+ ];
+ if (tableMetadataCapabilities.value.foreignKeys) {
+ tabs.push({
+ id: "foreignKeys",
+ label: t("grid.tableInfoForeignKeys"),
+ icon: Link2,
+ count: foreignKeys.value.length,
+ });
+ }
+ if (tableMetadataCapabilities.value.triggers) {
+ tabs.push({ id: "triggers", label: t("grid.tableInfoTriggers"), icon: RotateCcw, count: triggers.value.length });
+ }
+ tabs.push({ id: "ddl", label: "DDL", icon: Code2 });
+ return tabs;
+});
+const tableInfoTabListStyle = computed(() => ({
+ gridTemplateColumns: `repeat(${tableInfoTabs.value.length}, minmax(0, 1fr))`,
+}));
async function toggleTableInfo(tab: TableInfoTab = activeTableInfoTab.value) {
if (showTableInfo.value && activeTableInfoTab.value === tab) {
@@ -5299,11 +5309,12 @@ async function toggleTableInfo(tab: TableInfoTab = activeTableInfoTab.value) {
}
async function selectTableInfoTab(tab: TableInfoTab) {
- activeTableInfoTab.value = tab;
- if (tab === "ddl") await fetchDdl();
- else if (tab === "indexes") await fetchIndexes();
- else if (tab === "foreignKeys") await fetchForeignKeys();
- else if (tab === "triggers") await fetchTriggers();
+ const nextTab = tableInfoTabs.value.some((item) => item.id === tab) ? tab : "columns";
+ activeTableInfoTab.value = nextTab;
+ if (nextTab === "ddl") await fetchDdl();
+ else if (nextTab === "indexes") await fetchIndexes();
+ else if (nextTab === "foreignKeys") await fetchForeignKeys();
+ else if (nextTab === "triggers") await fetchTriggers();
}
async function fetchDdl() {
@@ -6882,7 +6893,7 @@ const gridContextMenuItems = computed<ContextMenuItem[]>(() => {
<X class="w-3 h-3" />
</Button>
</div>
- <div class="grid grid-cols-5 border-b bg-background shrink-0">
+ <div class="grid border-b bg-background shrink-0" :style="tableInfoTabListStyle">
<button
v-for="tab in tableInfoTabs"
:key="tab.id"
diff --git a/apps/desktop/src/components/structure/TableStructureEditor.vue b/apps/desktop/src/components/structure/TableStructureEditor.vue
index 8ca80dfadf..48f836442c 100644
--- a/apps/desktop/src/components/structure/TableStructureEditor.vue
+++ b/apps/desktop/src/components/structure/TableStructureEditor.vue
@@ -22,6 +22,7 @@ import { type SqlHighlighter, createShikiSqlHighlighter } from "@/lib/sqlHighlig
import { copyToClipboard } from "@/lib/clipboard";
import { queryTimeoutSecsForConnection } from "@/lib/queryTimeout";
import { type EditableStructureColumn, type EditableStructureIndex } from "@/lib/tableStructureEditorSql";
+import { getTableMetadataCapabilities } from "@/lib/tableMetadataCapabilities";
import { getTableStructureCapabilities } from "@/lib/tableStructureCapabilities";
import { connectionObjectTreeQuerySchema, effectiveDatabaseTypeForConnection } from "@/lib/jdbcDialect";
import { buildStructureTargetLabel, combineDataTypeForDatabase, createColumnDrafts, createIndexDrafts, getDataTypeOptions, getDefaultLengthForType, splitDataType, toColumnNames } from "@/lib/tableStructureEditorState";
@@ -268,6 +269,7 @@ function onIndexColResize(e: MouseEvent, col: number) {
const connection = computed(() => (props.connectionId ? store.getConfig(props.connectionId) : undefined));
const databaseType = computed(() => effectiveDatabaseTypeForConnection(connection.value));
const structureCapabilities = computed(() => getTableStructureCapabilities(databaseType.value));
+const tableMetadataCapabilities = computed(() => getTableMetadataCapabilities(databaseType.value));
const structureDialect = computed(() => structureCapabilities.value.dialect);
const isTableCommentDisabled = computed(() => !structureCapabilities.value.comment);
const dataTypeOptions = computed(() => getDataTypeOptions(databaseType.value));
@@ -372,8 +374,8 @@ async function loadStructure(silent = false) {
const nextColumns = await api.getColumns(props.connectionId, props.database, metadataSchema.value, props.tableName);
const [nextIndexes, nextForeignKeys, nextTriggers] = await Promise.all([
api.listIndexes(props.connectionId, props.database, metadataSchema.value, props.tableName).catch(() => []),
- api.listForeignKeys(props.connectionId, props.database, metadataSchema.value, props.tableName).catch(() => []),
- api.listTriggers(props.connectionId, props.database, metadataSchema.value, props.tableName).catch(() => []),
+ tableMetadataCapabilities.value.foreignKeys ? api.listForeignKeys(props.connectionId, props.database, metadataSchema.value, props.tableName).catch(() => []) : Promise.resolve([]),
+ tableMetadataCapabilities.value.triggers ? api.listTriggers(props.connectionId, props.database, metadataSchema.value, props.tableName).catch(() => []) : Promise.resolve([]),
]);
columns.value = createColumnDrafts(nextColumns, databaseType.value);
indexes.value = createIndexDrafts(nextIndexes);
@@ -670,6 +672,11 @@ onBeforeUnmount(() => {
unregisterStructureEditorShortcuts();
});
+watch(tableMetadataCapabilities, (capabilities) => {
+ if (activeTab.value === "foreignKeys" && !capabilities.foreignKeys) activeTab.value = "columns";
+ if (activeTab.value === "triggers" && !capabilities.triggers) activeTab.value = "columns";
+});
+
watch(
[isCreateMode, databaseType, () => props.schema, () => props.tableName, newTableName, tableComment, columns, indexes],
() => {
@@ -730,8 +737,8 @@ watch(activeTab, (tab) => {
<TabsList>
<TabsTrigger value="columns">{{ t("structureEditor.columns") }}</TabsTrigger>
<TabsTrigger value="indexes">{{ t("structureEditor.indexes") }}</TabsTrigger>
- <TabsTrigger value="foreignKeys">{{ t("structureEditor.foreignKeys") }}</TabsTrigger>
- <TabsTrigger value="triggers">{{ t("structureEditor.triggers") }}</TabsTrigger>
+ <TabsTrigger v-if="tableMetadataCapabilities.foreignKeys" value="foreignKeys">{{ t("structureEditor.foreignKeys") }}</TabsTrigger>
+ <TabsTrigger v-if="tableMetadataCapabilities.triggers" value="triggers">{{ t("structureEditor.triggers") }}</TabsTrigger>
<TabsTrigger value="ddl" v-if="!isCreateMode">DDL</TabsTrigger>
</TabsList>
<div class="flex shrink-0 items-center gap-1.5">
@@ -1077,7 +1084,7 @@ watch(activeTab, (tab) => {
</table>
</TabsContent>
- <TabsContent value="foreignKeys" class="m-0 min-h-0 flex-1 overflow-auto p-[var(--structure-cell-px)]">
+ <TabsContent v-if="tableMetadataCapabilities.foreignKeys" value="foreignKeys" class="m-0 min-h-0 flex-1 overflow-auto p-[var(--structure-cell-px)]">
<div v-if="foreignKeys.length === 0" class="py-10 text-center text-muted-foreground">
{{ t("structureEditor.emptyReadonly") }}
</div>
@@ -1089,7 +1096,7 @@ watch(activeTab, (tab) => {
</div>
</TabsContent>
- <TabsContent value="triggers" class="m-0 min-h-0 flex-1 overflow-auto p-[var(--structure-cell-px)]">
+ <TabsContent v-if="tableMetadataCapabilities.triggers" value="triggers" class="m-0 min-h-0 flex-1 overflow-auto p-[var(--structure-cell-px)]">
<div v-if="triggers.length === 0" class="py-10 text-center text-muted-foreground">
{{ t("structureEditor.emptyReadonly") }}
</div>
diff --git a/apps/desktop/src/lib/tableMetadataCapabilities.ts b/apps/desktop/src/lib/tableMetadataCapabilities.ts
new file mode 100644
index 0000000000..35ea8dece1
--- /dev/null
+++ b/apps/desktop/src/lib/tableMetadataCapabilities.ts
@@ -0,0 +1,33 @@
+import type { DatabaseType } from "@/types/database";
+
+export interface TableMetadataCapabilities {
+ columns: boolean;
+ indexes: boolean;
+ foreignKeys: boolean;
+ triggers: boolean;
+ ddl: boolean;
+}
+
+const defaultCapabilities: TableMetadataCapabilities = {
+ columns: true,
+ indexes: true,
+ foreignKeys: true,
+ triggers: true,
+ ddl: true,
+};
+
+const capabilityByType: Partial<Record<DatabaseType, Partial<TableMetadataCapabilities>>> = {
+ clickhouse: {
+ foreignKeys: false,
+ triggers: false,
+ },
+ influxdb: {
+ indexes: false,
+ foreignKeys: false,
+ triggers: false,
+ },
+};
+
+export function getTableMetadataCapabilities(dbType?: DatabaseType): TableMetadataCapabilities {
+ return { ...defaultCapabilities, ...(dbType ? capabilityByType[dbType] : undefined) };
+}
diff --git a/apps/desktop/src/stores/connectionStore.ts b/apps/desktop/src/stores/connectionStore.ts
index 82502973f2..de7b4f2fd7 100644
--- a/apps/desktop/src/stores/connectionStore.ts
+++ b/apps/desktop/src/stores/connectionStore.ts
@@ -45,6 +45,7 @@ import { decodeSchemaTreeCache, encodeSchemaTreeCache } from "@/lib/schemaTreeCa
import { sortSidebarTreeChildrenForParent } from "@/lib/sidebarNodeOrdering";
import { prunePinnedTreeNodeIdsForConnection } from "@/lib/pinnedTreeNodeIds";
import { supportsDatabaseUserAdmin } from "@/lib/databaseUserAdmin";
+import { getTableMetadataCapabilities } from "@/lib/tableMetadataCapabilities";
import { useSettingsStore } from "@/stores/settingsStore";
const PINNED_TREE_NODES_STORAGE_KEY = "dbx-pinned-tree-nodes";
@@ -1203,9 +1204,10 @@ export const useConnectionStore = defineStore("connection", () => {
];
const config = getConfig(connectionId);
- if (node.type === "table" && config?.db_type !== "influxdb") {
- children.push(
- {
+ const metadataCapabilities = getTableMetadataCapabilities(effectiveDatabaseTypeForConnection(config));
+ if (node.type === "table") {
+ if (metadataCapabilities.indexes) {
+ children.push({
id: `${parentId}:__indexes`,
label: "tree.indexes",
type: "group-indexes",
@@ -1215,8 +1217,10 @@ export const useConnectionStore = defineStore("connection", () => {
tableName: table,
isExpanded: false,
children: [],
- },
- {
+ });
+ }
+ if (metadataCapabilities.foreignKeys) {
+ children.push({
id: `${parentId}:__fkeys`,
label: "tree.foreignKeys",
type: "group-fkeys",
@@ -1226,8 +1230,10 @@ export const useConnectionStore = defineStore("connection", () => {
tableName: table,
isExpanded: false,
children: [],
- },
- {
+ });
+ }
+ if (metadataCapabilities.triggers) {
+ children.push({
id: `${parentId}:__triggers`,
label: "tree.triggers",
type: "group-triggers",
@@ -1237,8 +1243,8 @@ export const useConnectionStore = defineStore("connection", () => {
tableName: table,
isExpanded: false,
children: [],
- },
- );
+ });
+ }
}
setChildren(node, children);
@@ -1283,6 +1289,12 @@ export const useConnectionStore = defineStore("connection", () => {
node.isLoading = true;
try {
+ const metadataCapabilities = getTableMetadataCapabilities(effectiveDatabaseTypeForConnection(getConfig(connectionId)));
+ if (!metadataCapabilities.indexes) {
+ setChildren(node, []);
+ node.isExpanded = true;
+ return;
+ }
const querySchema = metadataQuerySchema(connectionId, database, schema);
const indexes = await api.listIndexes(connectionId, database, querySchema, table);
setChildren(
@@ -1314,6 +1326,12 @@ export const useConnectionStore = defineStore("connection", () => {
node.isLoading = true;
try {
+ const metadataCapabilities = getTableMetadataCapabilities(effectiveDatabaseTypeForConnection(getConfig(connectionId)));
+ if (!metadataCapabilities.foreignKeys) {
+ setChildren(node, []);
+ node.isExpanded = true;
+ return;
+ }
const querySchema = metadataQuerySchema(connectionId, database, schema);
const fkeys = await api.listForeignKeys(connectionId, database, querySchema, table);
setChildren(
@@ -1345,6 +1363,12 @@ export const useConnectionStore = defineStore("connection", () => {
node.isLoading = true;
try {
+ const metadataCapabilities = getTableMetadataCapabilities(effectiveDatabaseTypeForConnection(getConfig(connectionId)));
+ if (!metadataCapabilities.triggers) {
+ setChildren(node, []);
+ node.isExpanded = true;
+ return;
+ }
const querySchema = metadataQuerySchema(connectionId, database, schema);
const triggers = await api.listTriggers(connectionId, database, querySchema, table);
setChildren(
diff --git a/crates/dbx-core/src/db/clickhouse_driver.rs b/crates/dbx-core/src/db/clickhouse_driver.rs
index 210c825dd4..f28adea877 100644
--- a/crates/dbx-core/src/db/clickhouse_driver.rs
+++ b/crates/dbx-core/src/db/clickhouse_driver.rs
@@ -6,7 +6,7 @@ use std::time::{Duration, Instant};
use super::{http_client_builder, with_connection_timeout};
use crate::query::MAX_ROWS;
use crate::sql::starts_with_executable_sql_keyword;
-use crate::types::{ColumnInfo, DatabaseInfo, QueryResult, TableInfo};
+use crate::types::{ColumnInfo, DatabaseInfo, IndexInfo, QueryResult, TableInfo};
pub struct ChClient {
http: HttpClient,
@@ -146,6 +146,79 @@ fn query_result_row_limit(max_rows: Option<usize>) -> usize {
max_rows.unwrap_or(MAX_ROWS).max(1)
}
+fn clickhouse_literal(value: &str) -> String {
+ value.replace('\\', "\\\\").replace('\'', "\\'")
+}
+
+fn json_value_as_u64(value: Option<&serde_json::Value>) -> Option<u64> {
+ value.and_then(|value| value.as_u64().or_else(|| value.as_str().and_then(|text| text.parse::<u64>().ok())))
+}
+
+fn split_clickhouse_expression_list(value: &str) -> Vec<String> {
+ let trimmed = value.trim();
+ if trimmed.is_empty() {
+ return Vec::new();
+ }
+
+ let inner = trimmed.strip_prefix("tuple(").and_then(|rest| rest.strip_suffix(')')).unwrap_or(trimmed);
+ let mut items = Vec::new();
+ let mut start = 0;
+ let mut depth = 0i32;
+ let mut quote: Option<char> = None;
+ let mut escaped = false;
+
+ for (idx, ch) in inner.char_indices() {
+ if let Some(q) = quote {
+ if escaped {
+ escaped = false;
+ } else if ch == '\\' {
+ escaped = true;
+ } else if ch == q {
+ quote = None;
+ }
+ continue;
+ }
+
+ match ch {
+ '\'' | '"' | '`' => quote = Some(ch),
+ '(' | '[' | '{' => depth += 1,
+ ')' | ']' | '}' => depth = (depth - 1).max(0),
+ ',' if depth == 0 => {
+ let item = inner[start..idx].trim();
+ if !item.is_empty() {
+ items.push(item.to_string());
+ }
+ start = idx + ch.len_utf8();
+ }
+ _ => {}
+ }
+ }
+
+ let item = inner[start..].trim();
+ if !item.is_empty() {
+ items.push(item.to_string());
+ }
+ items
+}
+
+fn clickhouse_index_from_skipping_row(row: &[serde_json::Value]) -> IndexInfo {
+ let index_type = row.get(2).and_then(|v| v.as_str()).unwrap_or("").to_string();
+ let granularity = json_value_as_u64(row.get(3));
+ IndexInfo {
+ name: row.first().and_then(|v| v.as_str()).unwrap_or("").to_string(),
+ columns: split_clickhouse_expression_list(row.get(1).and_then(|v| v.as_str()).unwrap_or("")),
+ is_unique: false,
+ is_primary: false,
+ filter: None,
+ index_type: Some(match granularity {
+ Some(value) => format!("{index_type} GRANULARITY {value}"),
+ None => index_type,
+ }),
+ included_columns: None,
+ comment: None,
+ }
+}
+
fn limited_query_result(result: ChJsonResult, execution_time_ms: u128, max_rows: Option<usize>) -> QueryResult {
let columns: Vec<String> = result.meta.iter().map(|c| c.name.clone()).collect();
let column_types: Vec<String> = result.meta.iter().map(|c| c._type.clone()).collect();
@@ -244,6 +317,45 @@ pub async fn get_columns(client: &ChClient, database: &str, table: &str) -> Resu
.collect())
}
+pub async fn list_indexes(client: &ChClient, database: &str, table: &str) -> Result<Vec<IndexInfo>, String> {
+ let database_lit = clickhouse_literal(database);
+ let table_lit = clickhouse_literal(table);
+ let primary_sql = format!(
+ "SELECT primary_key FROM system.tables WHERE database = '{database_lit}' AND name = '{table_lit}' LIMIT 1"
+ );
+ let skipping_sql = format!(
+ "SELECT name, expr, type, granularity \
+ FROM system.data_skipping_indices \
+ WHERE database = '{database_lit}' AND table = '{table_lit}' \
+ ORDER BY name"
+ );
+
+ let mut indexes = Vec::new();
+ let primary_result = ch_query(client, &primary_sql, Some(database)).await?;
+ if let Some(primary_key) = primary_result
+ .data
+ .first()
+ .and_then(|row| row.first())
+ .and_then(|value| value.as_str())
+ .filter(|value| !value.trim().is_empty())
+ {
+ indexes.push(IndexInfo {
+ name: "PRIMARY".to_string(),
+ columns: split_clickhouse_expression_list(primary_key),
+ is_unique: false,
+ is_primary: true,
+ filter: None,
+ index_type: Some("primary".to_string()),
+ included_columns: None,
+ comment: None,
+ });
+ }
+
+ let skipping_result = ch_query(client, &skipping_sql, Some(database)).await?;
+ indexes.extend(skipping_result.data.iter().map(|row| clickhouse_index_from_skipping_row(row)));
+ Ok(indexes)
+}
+
pub async fn execute_query(client: &ChClient, database: &str, sql: &str) -> Result<QueryResult, String> {
execute_query_with_max_rows(client, database, sql, None).await
}
@@ -315,4 +427,31 @@ mod tests {
assert_eq!(result.execution_time_ms, 12);
assert!(result.truncated);
}
+
+ #[test]
+ fn splits_clickhouse_expression_lists_without_splitting_function_args() {
+ assert_eq!(split_clickhouse_expression_list("user_id, cityHash64(email, status), event_time"), {
+ vec!["user_id".to_string(), "cityHash64(email, status)".to_string(), "event_time".to_string()]
+ });
+ assert_eq!(split_clickhouse_expression_list("tuple(user_id, event_time)"), {
+ vec!["user_id".to_string(), "event_time".to_string()]
+ });
+ }
+
+ #[test]
+ fn maps_clickhouse_data_skipping_index_row() {
+ let row = vec![
+ serde_json::Value::String("idx_email".to_string()),
+ serde_json::Value::String("lower(email)".to_string()),
+ serde_json::Value::String("bloom_filter".to_string()),
+ serde_json::Value::String("4".to_string()),
+ ];
+
+ let index = clickhouse_index_from_skipping_row(&row);
+
+ assert_eq!(index.name, "idx_email");
+ assert_eq!(index.columns, vec!["lower(email)"]);
+ assert_eq!(index.index_type.as_deref(), Some("bloom_filter GRANULARITY 4"));
+ assert!(!index.is_primary);
+ }
}
diff --git a/crates/dbx-core/src/schema/providers/native.rs b/crates/dbx-core/src/schema/providers/native.rs
index a302207ac8..816e6cb27a 100644
--- a/crates/dbx-core/src/schema/providers/native.rs
+++ b/crates/dbx-core/src/schema/providers/native.rs
@@ -127,6 +127,9 @@ pub(in crate::schema) async fn list_indexes(
PoolKind::Rqlite(client) => db::rqlite_driver::list_indexes(client, schema, table).await,
PoolKind::Turso(client) => db::turso_driver::list_indexes(client, schema, table).await,
PoolKind::MongoDb(client) => db::mongo_driver::list_indexes(client, database, table).await,
+ PoolKind::ClickHouse(client) => {
+ db::clickhouse_driver::list_indexes(client, clickhouse_metadata_database(database, schema), table).await
+ }
_ => Ok(vec![]),
}
}
@@ -239,6 +242,14 @@ fn collection_names_to_tables(names: Vec<String>, table_type: &str) -> Vec<db::T
.collect()
}
+fn clickhouse_metadata_database<'a>(database: &'a str, schema: &'a str) -> &'a str {
+ if database.is_empty() {
+ schema
+ } else {
+ database
+ }
+}
+
fn is_opengauss_family_config(config: &ConnectionConfig) -> bool {
matches!(config.db_type, DatabaseType::OpenGauss | DatabaseType::Gaussdb)
|| matches!(config.driver_profile.as_deref(), Some("opengauss" | "gaussdb"))