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。
TypeScript aicliclickhousedatabasedatabase-clientdatabase-managementdockerguimcpmongodbmysqlpostgresqlredisrustsql-serversqlitetaurivue
feat(structure): search and paginate source table picker for copy columns
二丫讲梵ff4667b93f75
diff --git a/apps/desktop/src/components/structure/TableStructureEditor.vue b/apps/desktop/src/components/structure/TableStructureEditor.vueindex a5ce8285ef..aacb729736 100644--- a/apps/desktop/src/components/structure/TableStructureEditor.vue+++ b/apps/desktop/src/components/structure/TableStructureEditor.vue@@ -7,7 +7,7 @@ import { Input } from "@/components/ui/input";import { Badge } from "@/components/ui/badge";import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog";-import { AlertTriangle, Check, ChevronDown, ChevronUp, Copy, Database, Info, KeyRound, ListChevronsUpDown, Loader2, Maximize2, Plus, RefreshCw, Save, Search, Settings, SlidersHorizontal, Trash2, UserRound, X } from "@lucide/vue";+import { AlertTriangle, Check, ChevronDown, ChevronLeft, ChevronRight, ChevronUp, Copy, Database, Info, KeyRound, ListChevronsUpDown, Loader2, Maximize2, Plus, RefreshCw, Save, Search, Settings, SlidersHorizontal, Trash2, UserRound, X } from "@lucide/vue";import { DropdownMenu, DropdownMenuCheckboxItem, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from "@/components/ui/dropdown-menu";import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";@@ -205,13 +205,21 @@ const columns = ref<EditableStructureColumn[]>([]);const copyColumnsDialogOpen = ref(false);const copySourceTables = ref<TableInfo[]>([]);const copySourceTableName = ref("");+const copySourceTableSearch = ref("");const copySourceColumns = ref<ColumnInfo[]>([]);const copySourceColumnSearch = ref("");const selectedCopySourceColumnNames = ref<string[]>([]);const copySourceTablesLoading = ref(false);+const copySourceTablesOffset = ref(0);+const copySourceTablesHasMore = ref(false);const copySourceColumnsLoading = ref(false);const copySourceError = ref("");+const COPY_SOURCE_TABLE_PAGE_SIZE = 100;+const COPY_SOURCE_TABLE_PAGE_PROBE_SIZE = COPY_SOURCE_TABLE_PAGE_SIZE + 2;+const COPY_SOURCE_TABLE_SEARCH_DEBOUNCE_MS = 250;+let copySourceTablesRequestId = 0;let copySourceColumnsRequestId = 0;+let copySourceTableSearchTimer: ReturnType<typeof setTimeout> | undefined;const indexes = ref<EditableStructureIndex[]>([]);/** PostgreSQL partitioned parent (`relkind = 'p'`): `CREATE INDEX CONCURRENTLY`* is rejected by the server on such tables, so the option is disabled here and@@ -1907,35 +1915,88 @@ const selectedCopySourceColumns = computed(() => {return copyableSourceColumns.value.filter(({ column, alreadyExists }) => !alreadyExists && selected.has(column.name)).map(({ column }) => column);});const allCopyableSourceColumnsSelected = computed(() => copyableSourceColumnNames.value.length > 0 && copyableSourceColumnNames.value.every((name) => selectedCopySourceColumnNames.value.includes(name)));+const copySourceTablesHasPreviousPage = computed(() => copySourceTablesOffset.value > 0);-async function openCopyColumnsDialog() {- if (!canAddColumn.value || !props.connectionId || !props.database) return;- copyColumnsDialogOpen.value = true;+function clearCopySourceTableSearchTimer() {+ if (copySourceTableSearchTimer === undefined) return;+ clearTimeout(copySourceTableSearchTimer);+ copySourceTableSearchTimer = undefined;+}++function isCopySourceTable(table: TableInfo): boolean {+ const databaseInfo = connection.value?.database_info;+ return isCreateMode.value || tableStructureIdentifierComparisonKey(table.name, databaseType.value, databaseInfo) !== tableStructureIdentifierComparisonKey(props.tableName, databaseType.value, databaseInfo);+}++function clearCopySourceTableSelection() {copySourceTableName.value = "";copySourceColumns.value = [];copySourceColumnSearch.value = "";selectedCopySourceColumnNames.value = [];- copySourceError.value = "";copySourceColumnsRequestId++;copySourceColumnsLoading.value = false;- copySourceTables.value = [];+}++async function loadCopySourceTables(offset = 0) {+ if (!props.connectionId || !props.database) return;+ clearCopySourceTableSelection();+ const requestId = ++copySourceTablesRequestId;copySourceTablesLoading.value = true;+ copySourceError.value = "";try {await store.ensureConnected(props.connectionId);- const databaseInfo = connection.value?.database_info;- const currentTableIdentifierKey = tableStructureIdentifierComparisonKey(props.tableName, databaseType.value, databaseInfo);- copySourceTables.value = (await api.listTables(props.connectionId, props.database, metadataSchema.value, undefined, undefined, undefined, undefined, props.catalog)).filter((table) => {- const tableType = table.table_type.toUpperCase();- return tableType !== "VIEW" && tableType !== "MATERIALIZED_VIEW" && (isCreateMode.value || tableStructureIdentifierComparisonKey(table.name, databaseType.value, databaseInfo) !== currentTableIdentifierKey);- });+ const tables = await api.listTables(props.connectionId, props.database, metadataSchema.value, copySourceTableSearch.value.trim() || undefined, COPY_SOURCE_TABLE_PAGE_PROBE_SIZE, offset, ["TABLE"], props.catalog);+ if (requestId !== copySourceTablesRequestId) return;+ copySourceTables.value = tables.slice(0, COPY_SOURCE_TABLE_PAGE_SIZE).filter(isCopySourceTable);+ copySourceTablesOffset.value = offset;+ // The current table is excluded locally. Probe the next two rows so its+ // presence immediately after a full page does not create an empty next page.+ copySourceTablesHasMore.value = tables.slice(COPY_SOURCE_TABLE_PAGE_SIZE).some(isCopySourceTable);} catch (error: any) {+ if (requestId !== copySourceTablesRequestId) return;copySourceTables.value = [];+ copySourceTablesHasMore.value = false;copySourceError.value = error?.message || String(error);} finally {- copySourceTablesLoading.value = false;+ if (requestId === copySourceTablesRequestId) copySourceTablesLoading.value = false;}}+function updateCopySourceTableSearch(value: string | number) {+ copySourceTableSearch.value = String(value);+ clearCopySourceTableSelection();+ clearCopySourceTableSearchTimer();+ copySourceTableSearchTimer = setTimeout(() => {+ copySourceTableSearchTimer = undefined;+ void loadCopySourceTables();+ }, COPY_SOURCE_TABLE_SEARCH_DEBOUNCE_MS);+}++watch(copyColumnsDialogOpen, (open) => {+ if (open) return;+ clearCopySourceTableSearchTimer();+ copySourceTablesRequestId++;+ copySourceColumnsRequestId++;+});++async function openCopyColumnsDialog() {+ if (!canAddColumn.value || !props.connectionId || !props.database) return;+ copyColumnsDialogOpen.value = true;+ copySourceTableName.value = "";+ copySourceTableSearch.value = "";+ copySourceColumns.value = [];+ copySourceColumnSearch.value = "";+ selectedCopySourceColumnNames.value = [];+ copySourceError.value = "";+ copySourceColumnsRequestId++;+ copySourceColumnsLoading.value = false;+ copySourceTables.value = [];+ copySourceTablesOffset.value = 0;+ copySourceTablesHasMore.value = false;+ clearCopySourceTableSearchTimer();+ await loadCopySourceTables();+}+async function loadCopySourceColumns(tableName: string) {copySourceTableName.value = tableName;copySourceColumns.value = [];@@ -3265,6 +3326,7 @@ onDeactivated(() => {stopStructureHorizontalScrollbarDrag();});onBeforeUnmount(() => {+ clearCopySourceTableSearchTimer();stopColumnDragTracking();stopStructureHorizontalScrollbarDrag();structureHorizontalScrollbarObserverGeneration += 1;@@ -4335,18 +4397,10 @@ watch([activeTab, ddlLoading], ([tab, loading]) => {</DialogHeader><div class="space-y-3 overflow-hidden">- <label class="grid gap-1.5 text-sm font-medium">- {{ t("structureEditor.copyColumnsSourceTable") }}- <select- :value="copySourceTableName"- class="h-9 w-full rounded-md border border-input bg-background px-3 text-sm outline-none focus-visible:border-ring focus-visible:ring-2 focus-visible:ring-ring/30 disabled:cursor-not-allowed disabled:opacity-50"- :disabled="copySourceTablesLoading || copySourceTables.length === 0"- @change="loadCopySourceColumns(($event.target as HTMLSelectElement).value)"- >- <option value="" disabled>{{ t("structureEditor.copyColumnsSelectSourceTable") }}</option>- <option v-for="table in copySourceTables" :key="table.name" :value="table.name">{{ table.name }}</option>- </select>- </label>+ <div class="grid gap-1.5 text-sm font-medium">+ <label for="copy-source-table-search">{{ t("structureEditor.copyColumnsSourceTable") }}</label>+ <Input id="copy-source-table-search" :model-value="copySourceTableSearch" :placeholder="t('structureEditor.copyColumnsSearchSourceTables')" @update:model-value="updateCopySourceTableSearch" />+ </div><div v-if="copySourceTablesLoading" class="flex items-center gap-2 py-5 text-sm text-muted-foreground"><Loader2 class="h-4 w-4 animate-spin" />@@ -4356,9 +4410,47 @@ watch([activeTab, ddlLoading], ([tab, loading]) => {{{ copySourceError }}</div><div v-else-if="copySourceTables.length === 0" class="rounded-md border border-dashed px-3 py-5 text-center text-sm text-muted-foreground">- {{ t("structureEditor.copyColumnsNoSourceTables") }}+ {{ copySourceTableSearch ? t("structureEditor.copyColumnsNoMatchingSourceTables") : t("structureEditor.copyColumnsNoSourceTables") }}</div>- <template v-else-if="copySourceTableName">+ <template v-else>+ <div class="max-h-52 overflow-y-auto rounded-md border" :aria-label="t('structureEditor.copyColumnsSourceTable')">+ <button+ v-for="table in copySourceTables"+ :key="table.name"+ type="button"+ :aria-pressed="table.name === copySourceTableName"+ :class="['flex h-9 w-full items-center px-3 text-left font-mono text-sm hover:bg-muted/50 focus-visible:bg-muted focus-visible:outline-none', table.name === copySourceTableName ? 'bg-muted' : '']"+ @click="loadCopySourceColumns(table.name)"+ >+ <span class="truncate" :title="table.name">{{ table.name }}</span>+ </button>+ </div>+ <div v-if="copySourceTablesHasPreviousPage || copySourceTablesHasMore" class="flex items-center justify-end gap-1">+ <Button+ variant="ghost"+ size="icon"+ class="h-7 w-7"+ :disabled="copySourceTablesLoading || !copySourceTablesHasPreviousPage"+ :title="t('structureEditor.copyColumnsPreviousSourceTablePage')"+ :aria-label="t('structureEditor.copyColumnsPreviousSourceTablePage')"+ @click="loadCopySourceTables(Math.max(0, copySourceTablesOffset - COPY_SOURCE_TABLE_PAGE_SIZE))"+ >+ <ChevronLeft class="h-4 w-4" />+ </Button>+ <Button+ variant="ghost"+ size="icon"+ class="h-7 w-7"+ :disabled="copySourceTablesLoading || !copySourceTablesHasMore"+ :title="t('structureEditor.copyColumnsNextSourceTablePage')"+ :aria-label="t('structureEditor.copyColumnsNextSourceTablePage')"+ @click="loadCopySourceTables(copySourceTablesOffset + COPY_SOURCE_TABLE_PAGE_SIZE)"+ >+ <ChevronRight class="h-4 w-4" />+ </Button>+ </div>+ </template>+ <template v-if="copySourceTableName"><div class="flex items-center justify-between gap-2"><span class="text-sm font-medium">{{ t("structureEditor.copyColumnsSelectFields") }}</span><Button variant="ghost" size="sm" class="h-7 px-2 text-xs" :disabled="copySourceColumnsLoading || copyableSourceColumnNames.length === 0" @click="toggleCopySourceColumns">diff --git a/apps/desktop/src/i18n/locales/en.ts b/apps/desktop/src/i18n/locales/en.tsindex 2049385e12..cefffc0d42 100644--- a/apps/desktop/src/i18n/locales/en.ts+++ b/apps/desktop/src/i18n/locales/en.ts@@ -3671,12 +3671,15 @@ export default {copyColumn: "Copy Column",copyColumnsTitle: "Copy Columns from Another Table",copyColumnsSourceTable: "Source table",- copyColumnsSelectSourceTable: "Select a source table",+ copyColumnsSearchSourceTables: "Search source tables",copyColumnsSelectFields: "Select fields",copyColumnsSearchFields: "Search fields or types",copyColumnsSelectAll: "Select all",copyColumnsClearSelection: "Clear selection",copyColumnsNoSourceTables: "No other tables are available in this schema.",+ copyColumnsNoMatchingSourceTables: "No source tables match the search.",+ copyColumnsPreviousSourceTablePage: "Previous source table page",+ copyColumnsNextSourceTablePage: "Next source table page",copyColumnsNoFields: "The selected table has no fields.",copyColumnsNoMatchingFields: "No fields match the search.",copyColumnsAlreadyExists: "Already exists",diff --git a/apps/desktop/src/i18n/locales/es.ts b/apps/desktop/src/i18n/locales/es.tsindex 50f524bb20..72d021627a 100644--- a/apps/desktop/src/i18n/locales/es.ts+++ b/apps/desktop/src/i18n/locales/es.ts@@ -3592,12 +3592,15 @@ export default withEnglishFallback({copyColumn: "Copiar columna",copyColumnsTitle: "Copiar columnas de otra tabla",copyColumnsSourceTable: "Tabla de origen",- copyColumnsSelectSourceTable: "Selecciona una tabla de origen",+ copyColumnsSearchSourceTables: "Buscar tablas de origen",copyColumnsSelectFields: "Selecciona campos",copyColumnsSearchFields: "Buscar campos o tipos",copyColumnsSelectAll: "Seleccionar todo",copyColumnsClearSelection: "Borrar selección",copyColumnsNoSourceTables: "No hay otras tablas disponibles en este esquema.",+ copyColumnsNoMatchingSourceTables: "Ninguna tabla de origen coincide con la búsqueda.",+ copyColumnsPreviousSourceTablePage: "Página anterior de tablas de origen",+ copyColumnsNextSourceTablePage: "Página siguiente de tablas de origen",copyColumnsNoFields: "La tabla seleccionada no tiene campos.",copyColumnsNoMatchingFields: "Ningún campo coincide con la búsqueda.",copyColumnsAlreadyExists: "Ya existe",diff --git a/apps/desktop/src/i18n/locales/it.ts b/apps/desktop/src/i18n/locales/it.tsindex 39082f5481..68167b6b7f 100644--- a/apps/desktop/src/i18n/locales/it.ts+++ b/apps/desktop/src/i18n/locales/it.ts@@ -3590,12 +3590,15 @@ export default withEnglishFallback({copyColumn: "Copia colonna",copyColumnsTitle: "Copia colonne da un'altra tabella",copyColumnsSourceTable: "Tabella di origine",- copyColumnsSelectSourceTable: "Seleziona una tabella di origine",+ copyColumnsSearchSourceTables: "Cerca tabelle di origine",copyColumnsSelectFields: "Seleziona campi",copyColumnsSearchFields: "Cerca campi o tipi",copyColumnsSelectAll: "Seleziona tutto",copyColumnsClearSelection: "Cancella selezione",copyColumnsNoSourceTables: "Non sono disponibili altre tabelle in questo schema.",+ copyColumnsNoMatchingSourceTables: "Nessuna tabella di origine corrisponde alla ricerca.",+ copyColumnsPreviousSourceTablePage: "Pagina precedente delle tabelle di origine",+ copyColumnsNextSourceTablePage: "Pagina successiva delle tabelle di origine",copyColumnsNoFields: "La tabella selezionata non ha campi.",copyColumnsNoMatchingFields: "Nessun campo corrisponde alla ricerca.",copyColumnsAlreadyExists: "Già esistente",diff --git a/apps/desktop/src/i18n/locales/ja.ts b/apps/desktop/src/i18n/locales/ja.tsindex 832d0d80ab..476af7fa04 100644--- a/apps/desktop/src/i18n/locales/ja.ts+++ b/apps/desktop/src/i18n/locales/ja.ts@@ -3652,12 +3652,15 @@ export default withEnglishFallback({copyColumn: "列をコピー",copyColumnsTitle: "別のテーブルから列をコピー",copyColumnsSourceTable: "コピー元テーブル",- copyColumnsSelectSourceTable: "コピー元テーブルを選択",+ copyColumnsSearchSourceTables: "コピー元テーブルを検索",copyColumnsSelectFields: "フィールドを選択",copyColumnsSearchFields: "フィールドまたは型を検索",copyColumnsSelectAll: "すべて選択",copyColumnsClearSelection: "選択を解除",copyColumnsNoSourceTables: "このスキーマには他に選択可能なテーブルがありません。",+ copyColumnsNoMatchingSourceTables: "検索に一致するコピー元テーブルはありません。",+ copyColumnsPreviousSourceTablePage: "コピー元テーブルの前のページ",+ copyColumnsNextSourceTablePage: "コピー元テーブルの次のページ",copyColumnsNoFields: "選択したテーブルにはフィールドがありません。",copyColumnsNoMatchingFields: "検索に一致するフィールドはありません。",copyColumnsAlreadyExists: "既に存在します",diff --git a/apps/desktop/src/i18n/locales/ko.ts b/apps/desktop/src/i18n/locales/ko.tsindex e0cc7e36d6..afd1410a97 100644--- a/apps/desktop/src/i18n/locales/ko.ts+++ b/apps/desktop/src/i18n/locales/ko.ts@@ -3441,12 +3441,15 @@ export default withEnglishFallback({copyColumn: "컬럼 복사",copyColumnsTitle: "다른 테이블에서 컬럼 복사",copyColumnsSourceTable: "원본 테이블",- copyColumnsSelectSourceTable: "원본 테이블 선택",+ copyColumnsSearchSourceTables: "원본 테이블 검색",copyColumnsSelectFields: "필드 선택",copyColumnsSearchFields: "필드 또는 유형 검색",copyColumnsSelectAll: "모두 선택",copyColumnsClearSelection: "선택 해제",copyColumnsNoSourceTables: "이 스키마에 선택할 수 있는 다른 테이블이 없습니다.",+ copyColumnsNoMatchingSourceTables: "검색과 일치하는 원본 테이블이 없습니다.",+ copyColumnsPreviousSourceTablePage: "원본 테이블 이전 페이지",+ copyColumnsNextSourceTablePage: "원본 테이블 다음 페이지",copyColumnsNoFields: "선택한 테이블에 필드가 없습니다.",copyColumnsNoMatchingFields: "검색과 일치하는 필드가 없습니다.",copyColumnsAlreadyExists: "이미 존재함",diff --git a/apps/desktop/src/i18n/locales/pt-BR.ts b/apps/desktop/src/i18n/locales/pt-BR.tsindex a5a08b1c15..d58716087f 100644--- a/apps/desktop/src/i18n/locales/pt-BR.ts+++ b/apps/desktop/src/i18n/locales/pt-BR.ts@@ -3592,12 +3592,15 @@ export default withEnglishFallback({copyColumn: "Copiar coluna",copyColumnsTitle: "Copiar colunas de outra tabela",copyColumnsSourceTable: "Tabela de origem",- copyColumnsSelectSourceTable: "Selecione uma tabela de origem",+ copyColumnsSearchSourceTables: "Pesquisar tabelas de origem",copyColumnsSelectFields: "Selecione campos",copyColumnsSearchFields: "Pesquisar campos ou tipos",copyColumnsSelectAll: "Selecionar tudo",copyColumnsClearSelection: "Limpar seleção",copyColumnsNoSourceTables: "Não há outras tabelas disponíveis neste esquema.",+ copyColumnsNoMatchingSourceTables: "Nenhuma tabela de origem corresponde à pesquisa.",+ copyColumnsPreviousSourceTablePage: "Página anterior de tabelas de origem",+ copyColumnsNextSourceTablePage: "Próxima página de tabelas de origem",copyColumnsNoFields: "A tabela selecionada não tem campos.",copyColumnsNoMatchingFields: "Nenhum campo corresponde à pesquisa.",copyColumnsAlreadyExists: "Já existe",diff --git a/apps/desktop/src/i18n/locales/zh-CN.ts b/apps/desktop/src/i18n/locales/zh-CN.tsindex b52a8fc808..6d9d098168 100644--- a/apps/desktop/src/i18n/locales/zh-CN.ts+++ b/apps/desktop/src/i18n/locales/zh-CN.ts@@ -3657,12 +3657,15 @@ export default withEnglishFallback({copyColumn: "复制字段",copyColumnsTitle: "从其他表复制字段",copyColumnsSourceTable: "源表",- copyColumnsSelectSourceTable: "请选择源表",+ copyColumnsSearchSourceTables: "搜索源表",copyColumnsSelectFields: "选择字段",copyColumnsSearchFields: "搜索字段或类型",copyColumnsSelectAll: "全选",copyColumnsClearSelection: "取消全选",copyColumnsNoSourceTables: "当前模式下没有其他可选表。",+ copyColumnsNoMatchingSourceTables: "没有匹配的源表。",+ copyColumnsPreviousSourceTablePage: "上一页源表",+ copyColumnsNextSourceTablePage: "下一页源表",copyColumnsNoFields: "所选表没有字段。",copyColumnsNoMatchingFields: "没有匹配的字段。",copyColumnsAlreadyExists: "已存在",diff --git a/apps/desktop/src/i18n/locales/zh-TW.ts b/apps/desktop/src/i18n/locales/zh-TW.tsindex 8222de52a7..7515e9c254 100644--- a/apps/desktop/src/i18n/locales/zh-TW.ts+++ b/apps/desktop/src/i18n/locales/zh-TW.ts@@ -3337,12 +3337,15 @@ export default withEnglishFallback({copyColumn: "複製欄位",copyColumnsTitle: "從其他資料表複製欄位",copyColumnsSourceTable: "來源資料表",- copyColumnsSelectSourceTable: "請選擇來源資料表",+ copyColumnsSearchSourceTables: "搜尋來源資料表",copyColumnsSelectFields: "選擇欄位",copyColumnsSearchFields: "搜尋欄位或類型",copyColumnsSelectAll: "全選",copyColumnsClearSelection: "取消全選",copyColumnsNoSourceTables: "目前結構描述中沒有其他可選資料表。",+ copyColumnsNoMatchingSourceTables: "沒有符合搜尋的來源資料表。",+ copyColumnsPreviousSourceTablePage: "上一頁來源資料表",+ copyColumnsNextSourceTablePage: "下一頁來源資料表",copyColumnsNoFields: "所選資料表沒有欄位。",copyColumnsNoMatchingFields: "沒有符合搜尋的欄位。",copyColumnsAlreadyExists: "已存在",diff --git a/crates/dbx-core/src/db/clickhouse_driver.rs b/crates/dbx-core/src/db/clickhouse_driver.rsindex 69324a0890..7f15078233 100644--- a/crates/dbx-core/src/db/clickhouse_driver.rs+++ b/crates/dbx-core/src/db/clickhouse_driver.rs@@ -616,20 +616,101 @@ pub async fn list_databases(client: &ChClient) -> Result<Vec<DatabaseInfo>, Stri}pub async fn list_tables(client: &ChClient, database: &str) -> Result<Vec<TableInfo>, String> {- let database_lit = clickhouse_literal(database);- let sql_with_comment =- format!("SELECT name, engine, comment FROM system.tables WHERE database = '{database_lit}' ORDER BY name");+ list_tables_by_kind(client, database, None, None, None, false).await+}++/// Lists physical tables with server-side name filtering and pagination.+pub async fn list_table_objects_filtered(+ client: &ChClient,+ database: &str,+ filter: Option<&str>,+ limit: Option<usize>,+ offset: Option<usize>,+) -> Result<Vec<TableInfo>, String> {+ list_tables_by_kind(client, database, filter, limit, offset, true).await+}++async fn list_tables_by_kind(+ client: &ChClient,+ database: &str,+ filter: Option<&str>,+ limit: Option<usize>,+ offset: Option<usize>,+ table_objects_only: bool,+) -> Result<Vec<TableInfo>, String> {+ let sql_with_comment = clickhouse_tables_sql(database, filter, limit, offset, table_objects_only, true);let result = match ch_query(client, &sql_with_comment, Some(database)).await {Ok(result) => result,Err(error) => {log::debug!("Falling back to ClickHouse table list without comments: {error}");- let sql = format!("SELECT name, engine FROM system.tables WHERE database = '{database_lit}' ORDER BY name");+ let sql = clickhouse_tables_sql(database, filter, limit, offset, table_objects_only, false);ch_query(client, &sql, Some(database)).await?}};Ok(result.data.iter().map(|row| clickhouse_table_info_from_row(row)).collect())}+fn clickhouse_tables_sql(+ database: &str,+ filter: Option<&str>,+ limit: Option<usize>,+ offset: Option<usize>,+ table_objects_only: bool,+ include_comment: bool,+) -> String {+ let columns = if include_comment { "name, engine, comment" } else { "name, engine" };+ let database_lit = clickhouse_literal(database);+ let table_kind_filter = if table_objects_only { " AND position(engine, 'View') = 0" } else { "" };+ let name_filter = clickhouse_table_name_filter_sql(filter, include_comment);+ let pagination = limit.map(|limit| format!(" LIMIT {limit} OFFSET {}", offset.unwrap_or(0))).unwrap_or_default();++ format!(+ "SELECT {columns} FROM system.tables WHERE database = '{database_lit}'{table_kind_filter}{name_filter} ORDER BY name{pagination}"+ )+}++fn clickhouse_table_name_filter_sql(filter: Option<&str>, include_comment: bool) -> String {+ let filter = filter.unwrap_or("").trim();+ if filter.is_empty() {+ return String::new();+ }++ let mut patterns = vec![clickhouse_like_contains_pattern(filter)];+ if crate::sql::fuzzy_filter_enabled(filter) {+ patterns.push(crate::sql::fuzzy_like_pattern_with_escape(filter, clickhouse_escape_like_literal));+ }+ let predicates = patterns+ .into_iter()+ .map(|pattern| {+ // Keep comment-based search parity with the name predicate; the comment+ // column is absent from the no-comment fallback query, so the extra+ // predicate must be gated on include_comment.+ let name_predicate = format!("lowerUTF8(name) LIKE '{}'", clickhouse_literal(&pattern));+ if include_comment {+ format!("{name_predicate} OR lowerUTF8(coalesce(comment, '')) LIKE '{}'", clickhouse_literal(&pattern))+ } else {+ name_predicate+ }+ })+ .collect::<Vec<_>>();+ format!(" AND ({})", predicates.join(" OR "))+}++fn clickhouse_like_contains_pattern(value: &str) -> String {+ format!("%{}%", clickhouse_escape_like_literal(value))+}++fn clickhouse_escape_like_literal(value: &str) -> String {+ let mut escaped = String::with_capacity(value.len() + 1);+ for ch in value.chars().flat_map(char::to_lowercase) {+ if ch == '\\' || ch == '%' || ch == '_' {+ escaped.push('\\');+ }+ escaped.push(ch);+ }+ escaped+}+pub async fn list_object_statistics(client: &ChClient, database: &str) -> Result<Vec<ObjectStatistics>, String> {let database_lit = clickhouse_literal(database);let sql = format!(@@ -1128,4 +1209,36 @@ mod tests {assert_eq!(table.table_type, "VIEW");assert_eq!(table.comment, None);}++ #[test]+ fn table_object_query_filters_before_pagination() {+ let sql = clickhouse_tables_sql("analytics", Some("orders"), Some(102), Some(100), true, true);++ assert!(sql.contains("SELECT name, engine, comment FROM system.tables"));+ assert!(sql.contains("database = 'analytics'"));+ assert!(sql.contains("position(engine, 'View') = 0"));+ assert!(sql.contains("lowerUTF8(name) LIKE '%orders%'"));+ assert!(sql.contains("lowerUTF8(coalesce(comment, '')) LIKE '%orders%'"));+ assert!(sql.contains("ORDER BY name LIMIT 102 OFFSET 100"));+ assert!(sql.find("position(engine, 'View') = 0").unwrap() < sql.find("ORDER BY name").unwrap());+ assert!(sql.find("lowerUTF8(name) LIKE '%orders%'").unwrap() < sql.find("ORDER BY name").unwrap());+ }++ #[test]+ fn table_object_query_supports_fuzzy_name_filtering() {+ let sql = clickhouse_tables_sql("analytics", Some("ord"), Some(100), None, true, false);++ assert!(sql.contains("lowerUTF8(name) LIKE '%ord%'"));+ assert!(sql.contains("lowerUTF8(name) LIKE '%o%r%d%'"));+ assert!(!sql.contains("comment"));+ assert!(sql.ends_with("ORDER BY name LIMIT 100 OFFSET 0"));+ }++ #[test]+ fn table_object_query_matches_fuzzy_filter_against_comments() {+ let sql = clickhouse_tables_sql("analytics", Some("ord"), Some(100), None, true, true);++ assert!(sql.contains("lowerUTF8(coalesce(comment, '')) LIKE '%ord%'"));+ assert!(sql.contains("lowerUTF8(coalesce(comment, '')) LIKE '%o%r%d%'"));+ }}diff --git a/crates/dbx-core/src/db/postgres.rs b/crates/dbx-core/src/db/postgres.rsindex 9e5cb18194..26530c8d8a 100644--- a/crates/dbx-core/src/db/postgres.rs+++ b/crates/dbx-core/src/db/postgres.rs@@ -2831,6 +2831,29 @@ pub async fn list_tables_filtered(filter: Option<&str>,limit: Option<usize>,offset: Option<usize>,+) -> Result<Vec<TableInfo>, String> {+ list_tables_filtered_by_kind(pool, schema, filter, limit, offset, false).await+}++/// Lists only table-like relations, excluding views and materialized views while+/// retaining server-side filtering and pagination.+pub async fn list_table_objects_filtered(+ pool: &Pool,+ schema: &str,+ filter: Option<&str>,+ limit: Option<usize>,+ offset: Option<usize>,+) -> Result<Vec<TableInfo>, String> {+ list_tables_filtered_by_kind(pool, schema, filter, limit, offset, true).await+}++async fn list_tables_filtered_by_kind(+ pool: &Pool,+ schema: &str,+ filter: Option<&str>,+ limit: Option<usize>,+ offset: Option<usize>,+ table_objects_only: bool,) -> Result<Vec<TableInfo>, String> {let schema = if schema.is_empty() { "public" } else { schema };let filter = filter.unwrap_or("").trim();@@ -2840,7 +2863,11 @@ pub async fn list_tables_filtered(let limit_param = limit.and_then(|value| i64::try_from(value).ok());let offset_param = offset.and_then(|value| i64::try_from(value).ok()).unwrap_or(0);let client = checkout_postgres_client(pool, None, super::connection_timeout()).await?;- let sql = postgres_tables_sql(limit_param, offset_param);+ let sql = if table_objects_only {+ postgres_table_objects_sql(limit_param, offset_param)+ } else {+ postgres_tables_sql(limit_param, offset_param)+ };let params: &[(&(dyn tokio_postgres::types::ToSql + Sync), Type)] =&[(&schema, Type::VARCHAR), (&filter_pattern, Type::VARCHAR), (&fuzzy_filter_pattern, Type::VARCHAR)];// The pagination literals make this SQL vary by page. Use an unnamed typed@@ -4030,6 +4057,14 @@ fn postgres_table_comment_sql() -> &'static str {}fn postgres_tables_sql(limit: Option<i64>, offset: i64) -> String {+ postgres_tables_sql_with_kind(limit, offset, false)+}++fn postgres_table_objects_sql(limit: Option<i64>, offset: i64) -> String {+ postgres_tables_sql_with_kind(limit, offset, true)+}++fn postgres_tables_sql_with_kind(limit: Option<i64>, offset: i64, table_objects_only: bool) -> String {// PostgreSQL-compatible servers do not agree on the inferred wire types// or accepted expression grammar for LIMIT/OFFSET parameters. These values// originate as usize and are converted to non-negative i64 literals.@@ -4039,6 +4074,7 @@ fn postgres_tables_sql(limit: Option<i64>, offset: i64) -> String {Some(limit) => format!("LIMIT {limit} OFFSET {offset}"),None => format!("OFFSET {offset}"),};+ let relation_kinds = if table_objects_only { "'r','f','p'" } else { "'r','v','m','f','p'" };format!("SELECT c.relname AS table_name, \CASE c.relkind WHEN 'r' THEN 'BASE TABLE' WHEN 'v' THEN 'VIEW' \@@ -4052,7 +4088,7 @@ fn postgres_tables_sql(limit: Option<i64>, offset: i64) -> String {LEFT JOIN pg_catalog.pg_inherits i ON i.inhrelid = c.oid \LEFT JOIN pg_catalog.pg_class pc ON pc.oid = i.inhparent \LEFT JOIN pg_catalog.pg_namespace pn ON pn.oid = pc.relnamespace \- WHERE n.nspname = $1 AND c.relkind IN ('r','v','m','f','p') \+ WHERE n.nspname = $1 AND c.relkind IN ({relation_kinds}) \AND ($2 = '%%' OR c.relname ILIKE $2 OR ($3 <> '' AND c.relname ILIKE $3)) \ORDER BY CASE WHEN pc.relkind = 'p' THEN 1 ELSE 0 END, c.relname \{pagination}"@@ -9831,6 +9867,14 @@ mod tests {assert!(sql.contains("FOREIGN TABLE"));}+ #[test]+ fn postgres_table_objects_sql_excludes_views_before_pagination() {+ let sql = postgres_table_objects_sql(Some(101), 100);++ assert!(sql.contains("c.relkind IN ('r','f','p')"));+ assert!(sql.contains("LIMIT 101 OFFSET 100"));+ }+#[test]fn postgres_table_comment_sql_targets_single_table() {let sql = postgres_table_comment_sql();diff --git a/crates/dbx-core/src/db/sqlserver.rs b/crates/dbx-core/src/db/sqlserver.rsindex c0f922da96..f567c76241 100644--- a/crates/dbx-core/src/db/sqlserver.rs+++ b/crates/dbx-core/src/db/sqlserver.rs@@ -2066,7 +2066,33 @@ pub async fn list_tables(limit: Option<usize>,offset: Option<usize>,) -> Result<Vec<TableInfo>, String> {- let sql = sqlserver_list_tables_sql(schema, filter, limit, offset);+ list_tables_by_kind(client, schema, filter, limit, offset, false).await+}++/// Lists user tables only, preserving server-side filtering and pagination.+pub async fn list_table_objects(+ client: &mut SqlServerClient,+ schema: &str,+ filter: Option<&str>,+ limit: Option<usize>,+ offset: Option<usize>,+) -> Result<Vec<TableInfo>, String> {+ list_tables_by_kind(client, schema, filter, limit, offset, true).await+}++async fn list_tables_by_kind(+ client: &mut SqlServerClient,+ schema: &str,+ filter: Option<&str>,+ limit: Option<usize>,+ offset: Option<usize>,+ table_objects_only: bool,+) -> Result<Vec<TableInfo>, String> {+ let sql = if table_objects_only {+ sqlserver_table_objects_sql(schema, filter, limit, offset)+ } else {+ sqlserver_list_tables_sql(schema, filter, limit, offset)+ };let stream = client.query(&*sql, &[]).await.map_err(|e| e.to_string())?;let rows = stream.into_first_result().await.map_err(|e| e.to_string())?;Ok(rows@@ -2284,6 +2310,25 @@ fn sqlserver_list_tables_sql(filter: Option<&str>,limit: Option<usize>,offset: Option<usize>,+) -> String {+ sqlserver_list_tables_sql_with_kind(schema, filter, limit, offset, false)+}++fn sqlserver_table_objects_sql(+ schema: &str,+ filter: Option<&str>,+ limit: Option<usize>,+ offset: Option<usize>,+) -> String {+ sqlserver_list_tables_sql_with_kind(schema, filter, limit, offset, true)+}++fn sqlserver_list_tables_sql_with_kind(+ schema: &str,+ filter: Option<&str>,+ limit: Option<usize>,+ offset: Option<usize>,+ table_objects_only: bool,) -> String {let filter_clause = filter.filter(|value| !value.trim().is_empty())@@ -2307,7 +2352,9 @@ fn sqlserver_list_tables_sql(WHERE ep.major_id = o.object_id AND ep.minor_id = 0 AND ep.name = N'MS_Description') ep";let object_visibility = sqlserver_visible_object_predicate();let schema_filter = sqlserver_schema_name_predicate(schema, "s.name");- let base_where = format!("WHERE {schema_filter} AND o.type IN ('U','V') AND {object_visibility} {filter_clause}");+ let object_type_predicate = if table_objects_only { "o.type = 'U'" } else { "o.type IN ('U','V')" };+ let base_where =+ format!("WHERE {schema_filter} AND {object_type_predicate} AND {object_visibility} {filter_clause}");let order_by = "ORDER BY o.name";// Use SELECT TOP for broad SQL Server version compatibility.@@ -3317,10 +3364,10 @@ mod tests {sqlserver_legacy_wildcard_metadata_query, sqlserver_list_objects_sql, sqlserver_list_schemas_sql,sqlserver_list_tables_sql, sqlserver_probe_explicit_alias, sqlserver_query_messages,sqlserver_schema_name_predicate, sqlserver_spatial_marker, sqlserver_supports_session_database_switch,- sqlserver_table_comment_sql, sqlserver_triggers_sql, sqlserver_visible_object_predicate,- strip_dbx_sqlserver_row_number_column, SqlServerDescribedColumn, SqlServerProbeOutputNameOverride,- SqlServerRestoredColumn, SqlServerResultSet, SqlServerSpatialColumn, SqlServerTdsEvent,- SQLSERVER_COMPLETION_CONTEXT_SQL, SQLSERVER_RESULT_TYPE_PROBE_SQL,+ sqlserver_table_comment_sql, sqlserver_table_objects_sql, sqlserver_triggers_sql,+ sqlserver_visible_object_predicate, strip_dbx_sqlserver_row_number_column, SqlServerDescribedColumn,+ SqlServerProbeOutputNameOverride, SqlServerRestoredColumn, SqlServerResultSet, SqlServerSpatialColumn,+ SqlServerTdsEvent, SQLSERVER_COMPLETION_CONTEXT_SQL, SQLSERVER_RESULT_TYPE_PROBE_SQL,};use crate::types::{CompletionAssistantMatchMode, CompletionAssistantObjectKind, CompletionAssistantRequest, QueryResult,@@ -4175,6 +4222,16 @@ mod tests {assert!(sql.contains("SELECT TOP (200)"));}+ #[test]+ fn sqlserver_table_objects_sql_excludes_views_before_pagination() {+ let sql = sqlserver_table_objects_sql("dbo", Some("orders"), Some(101), Some(100));++ assert!(sql.contains("o.type = 'U'"));+ assert!(!sql.contains("o.type IN ('U','V')"));+ assert!(sql.contains("ROW_NUMBER() OVER (ORDER BY o.name)"));+ assert!(sql.contains("__dbx_rn > 100 AND __dbx_rn <= 201"));+ }+#[test]fn sqlserver_list_tables_filter_escapes_like_literals() {let sql = sqlserver_list_tables_sql("dbo", Some("Temp_Table[%]"), Some(200), None);diff --git a/crates/dbx-core/src/schema.rs b/crates/dbx-core/src/schema.rsindex 8a6f1ae8cb..d40a83b8ab 100644--- a/crates/dbx-core/src/schema.rs+++ b/crates/dbx-core/src/schema.rs@@ -2186,7 +2186,8 @@ async fn list_tables_once({let connections = state.connections.read().await;- if let Some(PoolKind::ExternalDriver { config, session, .. }) = connections.get(&pool_key) {+ if let Some(PoolKind::ExternalDriver { driver_id, config, session }) = connections.get(&pool_key) {+ let driver_id = driver_id.clone();let config = config.clone();let session = session.clone();drop(connections);@@ -2212,6 +2213,12 @@ async fn list_tables_once(if let Some(object_types) = object_types {params["object_types"] = serde_json::json!(object_types);}+ if let Some(limit) = limit {+ params["limit"] = serde_json::json!(limit);+ }+ if let Some(offset) = offset {+ params["offset"] = serde_json::json!(offset);+ }return session.invoke_with_timeout::<Vec<db::TableInfo>>("listTables",@@ -2219,7 +2226,14 @@ async fn list_tables_once(agent_metadata_timeout(Some(config.as_ref())),).await- .map(|tables| filter_table_infos(tables, filter, limit, offset, object_types, table_name_filter));+ .map(|tables| {+ let final_offset = if external_driver_paging_likely_applied(&driver_id, limit, tables.len()) {+ Some(0)+ } else {+ offset+ };+ filter_table_infos(tables, filter, limit, final_offset, object_types, table_name_filter)+ });}#[cfg(feature = "duckdb-sidecar")]if let Some(client) = extract_pool!(&connections, &pool_key, DuckDbWorker) {@@ -2233,6 +2247,17 @@ async fn list_tables_once(}if let Some(client) = extract_pool!(&connections, &pool_key, ClickHouse) {drop(connections);+ if requests_table_objects_only(object_types) && table_name_filter.is_none_or(TableNameFilter::is_empty) {+ return db::clickhouse_driver::list_table_objects_filtered(+ &client,+ clickhouse_metadata_database(database, schema),+ filter,+ limit,+ offset,+ )+ .await+ .map(|tables| filter_table_infos(tables, None, None, None, object_types, None));+ }return db::clickhouse_driver::list_tables(&client, clickhouse_metadata_database(database, schema)).await.map(|tables| filter_table_infos(tables, filter, limit, offset, object_types, table_name_filter));@@ -2266,6 +2291,13 @@ async fn list_tables_once(.map(|tables| filter_table_infos(tables, filter, limit, offset, object_types, table_name_filter));}}+ if requests_table_objects_only(object_types) && table_name_filter.is_none_or(TableNameFilter::is_empty) {+ if let Some(client) = extract_pool!(&connections, &pool_key, SqlServer) {+ drop(connections);+ let mut client = lock_sqlserver_metadata_client(&client).await?;+ return db::sqlserver::list_table_objects(&mut client, schema, filter, limit, offset).await;+ }+ }if object_types.is_some() || table_name_filter.is_some_and(|filter| !filter.is_empty()) {if let Some(client) = extract_pool!(&connections, &pool_key, SqlServer) {drop(connections);@@ -2513,7 +2545,9 @@ async fn list_tables_once(}}PoolKind::Postgres(p) => {- if object_types.is_some() || table_name_filter.is_some_and(|filter| !filter.is_empty()) {+ if requests_table_objects_only(object_types) && table_name_filter.is_none_or(TableNameFilter::is_empty) {+ db::postgres::list_table_objects_filtered(p, schema, filter, limit, offset).await+ } else if object_types.is_some() || table_name_filter.is_some_and(|filter| !filter.is_empty()) {db::postgres::list_tables_filtered(p, schema, filter, None, None).await.map(|tables| filter_table_infos(tables, filter, limit, offset, object_types, table_name_filter))@@ -2694,6 +2728,10 @@ fn normalize_table_info_object_type(value: &str) -> String {"TABLE".to_string()}+fn requests_table_objects_only(object_types: Option<&[String]>) -> bool {+ object_types.is_some_and(|types| types.len() == 1 && normalize_table_info_object_type(&types[0]) == "TABLE")+}+fn uses_presto_like_information_schema_tables(db_type: &DatabaseType) -> bool {matches!(db_type, DatabaseType::PrestoSql | DatabaseType::Trino)}@@ -3993,6 +4031,15 @@ for line in sys.stdin:assert!(!super::agent_paging_likely_applied(true, None, 120));}+ #[test]+ fn external_driver_paging_detection_avoids_double_offset_for_jdbc_only() {+ assert!(super::external_driver_paging_likely_applied("jdbc", Some(500), 500));+ assert!(super::external_driver_paging_likely_applied("jdbc", Some(500), 120));+ assert!(!super::external_driver_paging_likely_applied("jdbc", Some(500), 501));+ assert!(!super::external_driver_paging_likely_applied("jdbc", None, 120));+ assert!(!super::external_driver_paging_likely_applied("other", Some(500), 120));+ }+#[test]fn filter_visible_schema_names_preserves_database_order() {let schemas = vec!["APP".to_string(), "SYS".to_string(), "REPORTING".to_string()];@@ -7592,6 +7639,10 @@ fn agent_paging_likely_applied(enabled: bool, limit: Option<usize>, returned_lenenabled && limit.is_some_and(|limit| returned_len <= limit)}+fn external_driver_paging_likely_applied(driver_id: &str, limit: Option<usize>, returned_len: usize) -> bool {+ driver_id == "jdbc" && limit.is_some_and(|limit| returned_len <= limit)+}+fn mysql_show_metadata_database_for_config<'a>(config: Option<&ConnectionConfig>, database: &'a str) -> &'a str {if config.is_some_and(db::manticoresearch::is_config) {""diff --git a/plugins/jdbc/src/main/java/app/dbx/jdbc/DbxJdbcPlugin.java b/plugins/jdbc/src/main/java/app/dbx/jdbc/DbxJdbcPlugin.javaindex 13cf36a779..5b5dd9c6e6 100644--- a/plugins/jdbc/src/main/java/app/dbx/jdbc/DbxJdbcPlugin.java+++ b/plugins/jdbc/src/main/java/app/dbx/jdbc/DbxJdbcPlugin.java@@ -1935,11 +1935,11 @@ public final class DbxJdbcPlugin {}String catalog = metadataCatalog(database, quirks);String schemaPattern = resolveSchemaPattern(meta, database, schema, quirks);- appendTables(result, meta, catalog, schemaPattern, types);- if (result.isEmpty() && catalog != null) {- appendTables(result, meta, null, schemaPattern, types);+ boolean catalogHadTables = appendTables(result, meta, catalog, schemaPattern, types, filter, limit, offset);+ if (!catalogHadTables && catalog != null) {+ appendTables(result, meta, null, schemaPattern, types, filter, limit, offset);}- return filterMetadataNodes(result, filter, limit, offset, objectTypes, "table_type", true);+ return result;}private static JsonNode listObjects(@@ -2200,22 +2200,41 @@ public final class DbxJdbcPlugin {}}- private static void appendTables(+ private static boolean appendTables(ArrayNode result,DatabaseMetaData meta,String catalog,String schema,- String[] types+ String[] types,+ String filter,+ int limit,+ int offset) throws SQLException {+ String normalizedFilter = filter == null ? "" : filter.trim().toLowerCase(Locale.ROOT);+ int skipped = 0;+ int max = limit <= 0 ? Integer.MAX_VALUE : limit;+ boolean found = false;try (ResultSet rs = meta.getTables(catalog, schema, "%", types)) {while (rs.next()) {+ found = true;+ String name = rs.getString("TABLE_NAME");+ if (!metadataNameMatches(name, normalizedFilter)) {+ continue;+ }+ if (skipped++ < Math.max(0, offset)) {+ continue;+ }ObjectNode item = MAPPER.createObjectNode();- item.put("name", rs.getString("TABLE_NAME"));+ item.put("name", name);item.put("table_type", rs.getString("TABLE_TYPE"));putNullable(item, "comment", rs.getString("REMARKS"));result.add(item);+ if (result.size() >= max) {+ break;+ }}}+ return found;}static String[] jdbcTableTypes(DatabaseMetaData meta) throws SQLException {