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(objects): add table statistics columns
t8y2d59997c0909c
diff --git a/apps/desktop/src/components/objects/ObjectBrowser.vue b/apps/desktop/src/components/objects/ObjectBrowser.vueindex 119faacac2..b4c02fe760 100644--- a/apps/desktop/src/components/objects/ObjectBrowser.vue+++ b/apps/desktop/src/components/objects/ObjectBrowser.vue@@ -44,7 +44,7 @@ import CustomContextMenu, { type ContextMenuItem } from "@/components/ui/CustomCimport DangerConfirmDialog from "@/components/editor/DangerConfirmDialog.vue";import ProcedureExecutionDialog from "@/components/objects/ProcedureExecutionDialog.vue";import * as api from "@/lib/api";-import type { ConnectionConfig, ForeignKeyInfo, ObjectInfo, ObjectSourceKind } from "@/types/database";+import type { ConnectionConfig, ForeignKeyInfo, ObjectInfo, ObjectSourceKind, ObjectStatistics } from "@/types/database";import { sortTablesByFkDependency, type TableWithFk } from "@/lib/tableDependencySort";import { isSchemaAware } from "@/lib/databaseCapabilities";import { supportsSchemaDiagram, supportsTableImport, supportsTableStructureEditing, supportsTableTruncate } from "@/lib/databaseFeatureSupport";@@ -69,7 +69,18 @@ import DdlViewDialog from "./DdlViewDialog.vue";import type { SqlFormatDialect } from "@/lib/sqlFormatter";import { isCancelSearchShortcut } from "@/lib/keyboardShortcuts";import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog";-import { buildObjectBrowserRows, filterObjectBrowserRows, formatObjectBrowserTimestamp, initialObjectBrowserSortDirection, sortObjectBrowserRows, type ObjectBrowserRow, type ObjectBrowserSortDirection, type ObjectBrowserSortKey } from "@/lib/objectBrowserRows";+import {+ buildObjectBrowserRows,+ filterObjectBrowserRows,+ formatObjectBrowserBytes,+ formatObjectBrowserCount,+ formatObjectBrowserTimestamp,+ initialObjectBrowserSortDirection,+ sortObjectBrowserRows,+ type ObjectBrowserRow,+ type ObjectBrowserSortDirection,+ type ObjectBrowserSortKey,+} from "@/lib/objectBrowserRows";type ObjectFilter = "all" | "tables" | "views" | "procedures" | "functions" | "sequences" | "packages";@@ -189,14 +200,13 @@ const objectFilters = computed<ObjectFilter[]>(() =>.map(([filter]) => filter),);const showObjectFilter = computed(() => objectFilters.value.length > 2);-const hasComments = computed(() => rows.value.some((row) => row.comment?.trim()));const hasCreatedAt = computed(() => rows.value.some((row) => row.created_at?.trim()));const hasUpdatedAt = computed(() => rows.value.some((row) => row.updated_at?.trim()));const gridTemplateColumns = computed(() => {- const columns = ["34px", "minmax(0,1fr)", "120px"];+ const columns = ["34px", "minmax(160px,1fr)", "110px", "110px", "100px"];if (hasCreatedAt.value) columns.push("150px");if (hasUpdatedAt.value) columns.push("150px");- if (hasComments.value) columns.push("minmax(160px,0.7fr)");+ columns.push("minmax(160px,0.7fr)");return columns.join(" ");});const partitionRowsByParentId = computed(() => {@@ -1042,6 +1052,7 @@ async function loadObjects() {const availableTableIds = new Set(rows.value.filter((row) => row.type === "TABLE").map((row) => row.id));setSelectedTableIds(new Set([...selectedTableIds.value].filter((id) => availableTableIds.has(id))));expandedPartitionParentIds.value = new Set([...expandedPartitionParentIds.value].filter((id) => rows.value.some((row) => row.id === id && row.partitionCount)));+ void loadObjectStatistics(id, schema);} catch (e: any) {if (id !== loadId) return;error.value = e?.message || String(e);@@ -1055,6 +1066,39 @@ async function loadObjects() {}}+async function loadObjectStatistics(id: number, schema: string) {+ if (!rows.value.some((row) => row.type === "TABLE")) return;+ try {+ const stats = await api.listObjectStatistics(props.connection.id, props.database, schema);+ if (id !== loadId || stats.length === 0) return;+ mergeObjectStatistics(stats, schema);+ } catch (e) {+ console.debug("[ObjectBrowser] table statistics unavailable", e);+ }+}++function mergeObjectStatistics(stats: ObjectStatistics[], fallbackSchema: string) {+ const statsByKey = new Map(stats.map((stat) => [objectStatisticKey(stat.schema || fallbackSchema, stat.name), stat]));+ rows.value = rows.value.map((row) => {+ if (row.type !== "TABLE") return row;+ const stat = statsByKey.get(objectStatisticKey(row.schema || fallbackSchema, row.name));+ if (!stat) return row;+ return {+ ...row,+ estimatedRows: normalizeStatisticNumber(stat.estimated_rows),+ totalBytes: normalizeStatisticNumber(stat.total_bytes),+ };+ });+}++function objectStatisticKey(schema: string | undefined, name: string) {+ return `${schema || ""}\0${name}`.toLowerCase();+}++function normalizeStatisticNumber(value: number | null | undefined): number | null {+ return typeof value === "number" && Number.isFinite(value) ? value : null;+}+async function reload() {await loadSchemas();await loadObjects();@@ -1310,7 +1354,7 @@ function getObjectBrowserMenuItems(item: ObjectBrowserRow): ContextMenuItem[] {{{ t("objects.empty") }}</div><div v-else class="flex min-h-0 flex-1 flex-col">- <div class="grid h-8 shrink-0 items-center gap-3 border-b bg-muted/40 px-3 text-xs font-medium text-muted-foreground" :style="{ gridTemplateColumns }">+ <div class="grid h-7 shrink-0 items-center gap-3 border-b bg-muted/40 px-3 text-xs font-medium text-muted-foreground" :style="{ gridTemplateColumns }"><button class="flex h-6 w-6 items-center justify-center rounded-sm hover:bg-accent" type="button" :disabled="visibleSelectableRows.length === 0" @click="toggleVisibleTableSelection"><CheckSquare v-if="allVisibleTablesSelected" class="h-3.5 w-3.5 text-primary" /><Square v-else class="h-3.5 w-3.5" />@@ -1323,6 +1367,14 @@ function getObjectBrowserMenuItems(item: ObjectBrowserRow): ContextMenuItem[] {<span class="truncate">{{ t("objects.type") }}</span><component :is="sortIconFor('type')" v-if="sortIconFor('type')" class="h-3 w-3 shrink-0" /></button>+ <button class="flex min-w-0 items-center justify-end gap-1 truncate text-right" type="button" :title="t('objects.statisticsHint')" @click="toggleSort('estimatedRows')">+ <span class="truncate">{{ t("objects.rows") }}</span>+ <component :is="sortIconFor('estimatedRows')" v-if="sortIconFor('estimatedRows')" class="h-3 w-3 shrink-0" />+ </button>+ <button class="flex min-w-0 items-center justify-end gap-1 truncate text-right" type="button" :title="t('objects.statisticsHint')" @click="toggleSort('totalBytes')">+ <span class="truncate">{{ t("objects.size") }}</span>+ <component :is="sortIconFor('totalBytes')" v-if="sortIconFor('totalBytes')" class="h-3 w-3 shrink-0" />+ </button><button v-if="hasCreatedAt" class="flex min-w-0 items-center gap-1 truncate text-left" type="button" @click="toggleSort('created_at')"><span class="truncate">{{ t("objects.createdAt") }}</span><component :is="sortIconFor('created_at')" v-if="sortIconFor('created_at')" class="h-3 w-3 shrink-0" />@@ -1331,16 +1383,16 @@ function getObjectBrowserMenuItems(item: ObjectBrowserRow): ContextMenuItem[] {<span class="truncate">{{ t("objects.updatedAt") }}</span><component :is="sortIconFor('updated_at')" v-if="sortIconFor('updated_at')" class="h-3 w-3 shrink-0" /></button>- <button v-if="hasComments" class="flex min-w-0 items-center gap-1 truncate text-left" type="button" @click="toggleSort('comment')">+ <button class="flex min-w-0 items-center gap-1 truncate text-left" type="button" @click="toggleSort('comment')"><span class="truncate">{{ t("objects.comment") }}</span><component :is="sortIconFor('comment')" v-if="sortIconFor('comment')" class="h-3 w-3 shrink-0" /></button></div>- <RecycleScroller class="object-browser-scroller min-h-0 flex-1" :items="filteredRows" :item-size="38" :buffer="600" :skip-hover="true" key-field="id">+ <RecycleScroller class="object-browser-scroller min-h-0 flex-1" :items="filteredRows" :item-size="34" :buffer="600" :skip-hover="true" key-field="id"><template #default="{ item }"><CustomContextMenu :items="getObjectBrowserMenuItems(item)" v-slot="{ onContextMenu }"><div- class="grid h-[38px] cursor-pointer items-center gap-3 border-b px-3 hover:bg-accent/50"+ class="grid h-[34px] cursor-pointer items-center gap-3 border-b px-3 hover:bg-accent/50":class="{'bg-accent/40': sourceRow?.id === item.id,'bg-primary/5': selectedTableIds.has(item.id),@@ -1372,13 +1424,19 @@ function getObjectBrowserMenuItems(item: ObjectBrowserRow): ContextMenuItem[] {</span></div><div class="truncate text-xs text-muted-foreground">{{ typeLabel(item.type) }}</div>+ <div class="truncate text-right text-xs tabular-nums text-muted-foreground" :title="item.estimatedRows == null ? '' : formatObjectBrowserCount(item.estimatedRows)">+ {{ formatObjectBrowserCount(item.estimatedRows) }}+ </div>+ <div class="truncate text-right text-xs tabular-nums text-muted-foreground" :title="item.totalBytes == null ? '' : formatObjectBrowserCount(item.totalBytes)">+ {{ formatObjectBrowserBytes(item.totalBytes) }}+ </div><div v-if="hasCreatedAt" class="truncate text-xs tabular-nums text-muted-foreground" :title="formatObjectBrowserTimestamp(item.created_at)">{{ formatObjectBrowserTimestamp(item.created_at) }}</div><div v-if="hasUpdatedAt" class="truncate text-xs tabular-nums text-muted-foreground" :title="formatObjectBrowserTimestamp(item.updated_at)">{{ formatObjectBrowserTimestamp(item.updated_at) }}</div>- <div v-if="hasComments" class="truncate text-xs text-muted-foreground" :title="item.comment || ''">+ <div class="truncate text-xs text-muted-foreground" :title="item.comment || ''">{{ item.comment || "" }}</div></div>diff --git a/apps/desktop/src/i18n/locales/en.ts b/apps/desktop/src/i18n/locales/en.tsindex 1102549bb2..db523dab6c 100644--- a/apps/desktop/src/i18n/locales/en.ts+++ b/apps/desktop/src/i18n/locales/en.ts@@ -1326,6 +1326,9 @@ export default {packageBody: "Package Body",name: "Name",type: "Type",+ rows: "Rows",+ size: "Size",+ statisticsHint: "Estimated from database statistics; no COUNT(*) is executed.",createdAt: "Created",updatedAt: "Updated",source: "Source",diff --git a/apps/desktop/src/i18n/locales/es.ts b/apps/desktop/src/i18n/locales/es.tsindex 0f62370516..de1bb18b27 100644--- a/apps/desktop/src/i18n/locales/es.ts+++ b/apps/desktop/src/i18n/locales/es.ts@@ -1096,6 +1096,9 @@ export default {packageBody: "Cuerpo del paquete",name: "Nombre",type: "Tipo",+ rows: "Filas",+ size: "Tamaño",+ statisticsHint: "Estimado desde estadísticas de la base de datos; no se ejecuta COUNT(*).",createdAt: "Creado",updatedAt: "Actualizado",source: "Código fuente",diff --git a/apps/desktop/src/i18n/locales/it.ts b/apps/desktop/src/i18n/locales/it.tsindex bb1896a456..8a089a02c4 100644--- a/apps/desktop/src/i18n/locales/it.ts+++ b/apps/desktop/src/i18n/locales/it.ts@@ -1212,6 +1212,9 @@ export default {packageBody: "Corpo del Pacchetto",name: "Nome",type: "Tipo",+ rows: "Righe",+ size: "Dimensione",+ statisticsHint: "Stimato dalle statistiche del database; COUNT(*) non viene eseguito.",createdAt: "Creato",updatedAt: "Aggiornato",source: "Codice Sorgente",diff --git a/apps/desktop/src/i18n/locales/ja.ts b/apps/desktop/src/i18n/locales/ja.tsindex 1c46e14fe4..2eeda678a0 100644--- a/apps/desktop/src/i18n/locales/ja.ts+++ b/apps/desktop/src/i18n/locales/ja.ts@@ -1311,6 +1311,9 @@ export default {packageBody: "パッケージボディ",name: "名前",type: "タイプ",+ rows: "行数",+ size: "サイズ",+ statisticsHint: "データベース統計からの推定値です。COUNT(*) は実行しません。",createdAt: "作成日時",updatedAt: "更新日時",source: "ソース",diff --git a/apps/desktop/src/i18n/locales/pt-BR.ts b/apps/desktop/src/i18n/locales/pt-BR.tsindex ca5fc6f9b9..4421a64ec5 100644--- a/apps/desktop/src/i18n/locales/pt-BR.ts+++ b/apps/desktop/src/i18n/locales/pt-BR.ts@@ -1212,6 +1212,9 @@ export default {packageBody: "Corpo do pacote",name: "Nome",type: "Tipo",+ rows: "Linhas",+ size: "Tamanho",+ statisticsHint: "Estimado pelas estatísticas do banco de dados; COUNT(*) não é executado.",createdAt: "Criado em",updatedAt: "Atualizado em",source: "Código-fonte",diff --git a/apps/desktop/src/i18n/locales/zh-CN.ts b/apps/desktop/src/i18n/locales/zh-CN.tsindex b6eb599a11..6ad3e66ea6 100644--- a/apps/desktop/src/i18n/locales/zh-CN.ts+++ b/apps/desktop/src/i18n/locales/zh-CN.ts@@ -1325,6 +1325,9 @@ export default {packageBody: "包体",name: "名称",type: "类型",+ rows: "行数",+ size: "大小",+ statisticsHint: "来自数据库统计信息的估算值,不执行 COUNT(*)。",createdAt: "创建时间",updatedAt: "更新时间",source: "源代码",diff --git a/apps/desktop/src/i18n/locales/zh-TW.ts b/apps/desktop/src/i18n/locales/zh-TW.tsindex 5b08b61241..e465c0e30e 100644--- a/apps/desktop/src/i18n/locales/zh-TW.ts+++ b/apps/desktop/src/i18n/locales/zh-TW.ts@@ -1192,6 +1192,9 @@ export default {packageBody: "套件主體",name: "名稱",type: "類型",+ rows: "列數",+ size: "大小",+ statisticsHint: "來自資料庫統計資訊的估算值,不執行 COUNT(*)。",createdAt: "建立時間",updatedAt: "更新時間",source: "原始碼",diff --git a/apps/desktop/src/lib/api.ts b/apps/desktop/src/lib/api.tsindex 3e187e8c31..84546822fd 100644--- a/apps/desktop/src/lib/api.ts+++ b/apps/desktop/src/lib/api.ts@@ -112,6 +112,7 @@ export const deleteSchemaCachePrefix = forward("deleteSchemaCachePrefix");export const listSchemas = forward("listSchemas");export const listTables = forward("listTables");export const listObjects = forward("listObjects");+export const listObjectStatistics = forward("listObjectStatistics");export const listCompletionObjects = forward("listCompletionObjects");export const getObjectSource = forward("getObjectSource");export const getColumns = forward("getColumns");diff --git a/apps/desktop/src/lib/http.ts b/apps/desktop/src/lib/http.tsindex 4f9cf7f294..56bb4b8e46 100644--- a/apps/desktop/src/lib/http.ts+++ b/apps/desktop/src/lib/http.ts@@ -4,6 +4,7 @@LinkedServerInfo,TableInfo,ObjectInfo,+ ObjectStatistics,ObjectSource,ObjectSourceKind,ColumnInfo,@@ -453,6 +454,10 @@ export async function listObjects(connectionId: string, database: string, schema);}+export async function listObjectStatistics(connectionId: string, database: string, schema: string): Promise<ObjectStatistics[]> {+ return get(`/api/schema/object-statistics?${qs({ connection_id: connectionId, database, schema })}`);+}+export async function listCompletionObjects(connectionId: string, database: string, schema: string): Promise<ObjectInfo[]> {return get(`/api/schema/completion-objects?${qs({ connection_id: connectionId, database, schema })}`);}diff --git a/apps/desktop/src/lib/objectBrowserRows.ts b/apps/desktop/src/lib/objectBrowserRows.tsindex c2bb2ad441..0c9899b079 100644--- a/apps/desktop/src/lib/objectBrowserRows.ts+++ b/apps/desktop/src/lib/objectBrowserRows.ts@@ -14,9 +14,11 @@ export type ObjectBrowserRow = {partitionCount?: number;partitionParentSchema?: string;partitionParentName?: string;+ estimatedRows?: number | null;+ totalBytes?: number | null;};-export type ObjectBrowserSortKey = "name" | "type" | "created_at" | "updated_at" | "comment";+export type ObjectBrowserSortKey = "name" | "type" | "estimatedRows" | "totalBytes" | "created_at" | "updated_at" | "comment";export type ObjectBrowserSortDirection = "asc" | "desc";export function normalizeObjectBrowserType(type: string): ObjectBrowserRow["type"] {@@ -115,7 +117,7 @@ export function sortObjectBrowserRows(rows: ObjectBrowserRow[], key: ObjectBrows}export function initialObjectBrowserSortDirection(key: ObjectBrowserSortKey): ObjectBrowserSortDirection {- return key === "created_at" || key === "updated_at" ? "desc" : "asc";+ return key === "created_at" || key === "updated_at" || key === "estimatedRows" || key === "totalBytes" ? "desc" : "asc";}export function formatObjectBrowserTimestamp(value: string | null | undefined): string {@@ -127,7 +129,28 @@ export function formatObjectBrowserTimestamp(value: string | null | undefined):.replace(/(?:Z|[+-]\d{2}(?::?\d{2})?)$/, "");}-function compareObjectBrowserValue(left: string | null | undefined, right: string | null | undefined, key: ObjectBrowserSortKey, direction: ObjectBrowserSortDirection): number {+export function formatObjectBrowserCount(value: number | null | undefined): string {+ if (typeof value !== "number" || !Number.isFinite(value)) return "";+ return new Intl.NumberFormat().format(value);+}++export function formatObjectBrowserBytes(value: number | null | undefined): string {+ if (typeof value !== "number" || !Number.isFinite(value)) return "";+ const units = ["B", "KB", "MB", "GB", "TB", "PB"];+ let size = Math.max(0, value);+ let unitIndex = 0;+ while (size >= 1024 && unitIndex < units.length - 1) {+ size /= 1024;+ unitIndex++;+ }+ const fractionDigits = unitIndex === 0 || size >= 100 ? 0 : size >= 10 ? 1 : 2;+ return `${size.toFixed(fractionDigits)} ${units[unitIndex]}`;+}++function compareObjectBrowserValue(left: string | number | null | undefined, right: string | number | null | undefined, key: ObjectBrowserSortKey, direction: ObjectBrowserSortDirection): number {+ if (key === "estimatedRows" || key === "totalBytes") {+ return compareObjectBrowserNumber(left, right, direction);+ }const leftText = normalizeSortValue(left);const rightText = normalizeSortValue(right);if (!leftText && !rightText) return 0;@@ -137,6 +160,23 @@ function compareObjectBrowserValue(left: string | null | undefined, right: strinreturn leftText.localeCompare(rightText, undefined, { numeric: true, sensitivity: "base" });}-function normalizeSortValue(value: string | null | undefined): string {+function compareObjectBrowserNumber(left: string | number | null | undefined, right: string | number | null | undefined, direction: ObjectBrowserSortDirection): number {+ const leftNumber = normalizeSortNumber(left);+ const rightNumber = normalizeSortNumber(right);+ if (leftNumber === null && rightNumber === null) return 0;+ if (leftNumber === null) return direction === "asc" ? 1 : -1;+ if (rightNumber === null) return direction === "asc" ? -1 : 1;+ return leftNumber - rightNumber;+}++function normalizeSortValue(value: string | number | null | undefined): string {+ if (typeof value === "number") return String(value);return value?.trim() ?? "";}++function normalizeSortNumber(value: string | number | null | undefined): number | null {+ if (typeof value === "number" && Number.isFinite(value)) return value;+ if (typeof value !== "string" || !value.trim()) return null;+ const parsed = Number(value);+ return Number.isFinite(parsed) ? parsed : null;+}diff --git a/apps/desktop/src/lib/tauri.ts b/apps/desktop/src/lib/tauri.tsindex 283850536a..b1b9b0d196 100644--- a/apps/desktop/src/lib/tauri.ts+++ b/apps/desktop/src/lib/tauri.ts@@ -6,6 +6,7 @@ import type {LinkedServerInfo,TableInfo,ObjectInfo,+ ObjectStatistics,ObjectSource,ObjectSourceKind,ColumnInfo,@@ -512,6 +513,10 @@ export async function listObjects(connectionId: string, database: string, schemareturn invoke("list_objects", { connectionId, database, schema, objectTypes });}+export async function listObjectStatistics(connectionId: string, database: string, schema: string): Promise<ObjectStatistics[]> {+ return invoke("list_object_statistics", { connectionId, database, schema });+}+export async function listCompletionObjects(connectionId: string, database: string, schema: string): Promise<ObjectInfo[]> {return invoke("list_completion_objects", { connectionId, database, schema });}diff --git a/apps/desktop/src/types/database.ts b/apps/desktop/src/types/database.tsindex a17b0ece0f..7659dbddf5 100644--- a/apps/desktop/src/types/database.ts+++ b/apps/desktop/src/types/database.ts@@ -237,6 +237,13 @@ export interface ObjectInfo {parent_name?: string | null;}+export interface ObjectStatistics {+ name: string;+ schema?: string | null;+ estimated_rows?: number | null;+ total_bytes?: number | null;+}+export type ObjectSourceKind = "VIEW" | "MATERIALIZED_VIEW" | "PROCEDURE" | "FUNCTION" | "SEQUENCE" | "PACKAGE" | "PACKAGE_BODY";export interface ObjectSource {diff --git a/crates/dbx-core/src/db/mysql.rs b/crates/dbx-core/src/db/mysql.rsindex 74e2fc9122..c3a255105c 100644--- a/crates/dbx-core/src/db/mysql.rs+++ b/crates/dbx-core/src/db/mysql.rs@@ -13,7 +13,8 @@ use std::time::Instant;use crate::models::connection::DatabaseType;use crate::sql::starts_with_executable_sql_keyword;use crate::types::{- ColumnInfo, DatabaseInfo, ForeignKeyInfo, IndexInfo, ObjectInfo, QueryResult, TableInfo, TriggerInfo,+ ColumnInfo, DatabaseInfo, ForeignKeyInfo, IndexInfo, ObjectInfo, ObjectStatistics, QueryResult, TableInfo,+ TriggerInfo,};use super::file_validator::validate_file_path;@@ -103,6 +104,17 @@ fn get_opt_i32(row: &mysql_async::Row, name: &str) -> Option<i32> {})}+fn get_opt_i64(row: &mysql_async::Row, name: &str) -> Option<i64> {+ row_get::<i64, _>(row, name)+ .or_else(|| row_get::<u64, _>(row, name).and_then(|value| i64::try_from(value).ok()))+ .or_else(|| row_get::<String, _>(row, name).and_then(|value| value.parse::<i64>().ok()))+ .or_else(|| {+ row_get::<Vec<u8>, _>(row, name)+ .and_then(|b| String::from_utf8(b).ok())+ .and_then(|value| value.parse::<i64>().ok())+ })+}+#[cfg(test)]fn mysql_datetime_to_string(value: NaiveDateTime) -> String {value.to_string()@@ -1195,6 +1207,31 @@ pub async fn list_objects(pool: &MySqlPool, database: &str) -> Result<Vec<ObjectOk(objects)}+pub async fn list_object_statistics(pool: &MySqlPool, database: &str) -> Result<Vec<ObjectStatistics>, String> {+ let sql = format!(+ "SELECT TABLE_NAME, TABLE_ROWS, COALESCE(DATA_LENGTH, 0) + COALESCE(INDEX_LENGTH, 0) AS TOTAL_BYTES \+ FROM information_schema.TABLES \+ WHERE TABLE_SCHEMA = {} AND TABLE_TYPE <> 'VIEW' \+ ORDER BY TABLE_NAME",+ quote_value(database),+ );+ let mut conn = pool.get_conn().await.map_err(|e| e.to_string())?;+ let result = conn.query_iter(&sql).await.map_err(|e| e.to_string())?;+ let rows: Vec<mysql_async::Row> = result.collect_and_drop().await.map_err(|e| e.to_string())?;+ Ok(rows+ .iter()+ .filter_map(|row| {+ let name = get_str_by_name(row, "TABLE_NAME").trim().to_string();+ (!name.is_empty()).then_some(ObjectStatistics {+ name,+ schema: Some(database.to_string()),+ estimated_rows: get_opt_i64(row, "TABLE_ROWS"),+ total_bytes: get_opt_i64(row, "TOTAL_BYTES"),+ })+ })+ .collect())+}+pub async fn list_table_objects_show(pool: &MySqlPool, database: &str) -> Result<Vec<ObjectInfo>, String> {let (tables, routines) =tokio::join!(list_tables_show_with_status(pool, database), list_routine_objects(pool, database));diff --git a/crates/dbx-core/src/db/postgres.rs b/crates/dbx-core/src/db/postgres.rsindex c4d51f18cd..bb4076b0d0 100644--- a/crates/dbx-core/src/db/postgres.rs+++ b/crates/dbx-core/src/db/postgres.rs@@ -20,8 +20,8 @@ use tokio_postgres::{Row, SimpleQueryMessage};use super::file_validator::validate_file_path;use crate::sql::starts_with_executable_sql_keyword;use crate::types::{- ColumnInfo, DatabaseInfo, ForeignKeyInfo, FunctionInfo, IndexInfo, ObjectInfo, OwnerInfo, QueryResult, RuleInfo,- SequenceInfo, TableInfo, TriggerInfo,+ ColumnInfo, DatabaseInfo, ForeignKeyInfo, FunctionInfo, IndexInfo, ObjectInfo, ObjectStatistics, OwnerInfo,+ QueryResult, RuleInfo, SequenceInfo, TableInfo, TriggerInfo,};fn pg_temporal_to_json_value(row: &Row, idx: usize) -> Option<serde_json::Value> {@@ -1102,6 +1102,33 @@ pub async fn list_objects(pool: &Pool, schema: &str) -> Result<Vec<ObjectInfo>,.collect())}+pub async fn list_object_statistics(pool: &Pool, schema: &str) -> Result<Vec<ObjectStatistics>, String> {+ let schema = if schema.is_empty() { "public" } else { schema };+ let client = pool.get().await.map_err(|e| e.to_string())?;+ let stmt = client+ .prepare_cached(+ "SELECT c.relname, \+ GREATEST(c.reltuples, 0)::bigint AS estimated_rows, \+ pg_catalog.pg_total_relation_size(c.oid)::bigint AS total_bytes \+ FROM pg_catalog.pg_class c \+ JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace \+ WHERE n.nspname = $1 AND c.relkind IN ('r','m','f','p') \+ ORDER BY c.relname",+ )+ .await+ .map_err(|e| e.to_string())?;+ let rows = client.query(&stmt, &[&schema]).await.map_err(|e| e.to_string())?;+ Ok(rows+ .iter()+ .map(|row| ObjectStatistics {+ name: row.get::<_, String>(0),+ schema: Some(schema.to_string()),+ estimated_rows: row.try_get::<_, i64>(1).ok(),+ total_bytes: row.try_get::<_, i64>(2).ok(),+ })+ .collect())+}+pub async fn list_schemas(pool: &Pool) -> Result<Vec<String>, String> {let client = pool.get().await.map_err(|e| e.to_string())?;let stmt = clientdiff --git a/crates/dbx-core/src/db/sqlserver.rs b/crates/dbx-core/src/db/sqlserver.rsindex f2229e0f3a..bec8d2de1b 100644--- a/crates/dbx-core/src/db/sqlserver.rs+++ b/crates/dbx-core/src/db/sqlserver.rs@@ -1,7 +1,8 @@use crate::query::MAX_ROWS;use crate::sql::starts_with_executable_sql_keyword;use crate::types::{- ColumnInfo, DatabaseInfo, ForeignKeyInfo, IndexInfo, LinkedServerInfo, QueryResult, TableInfo, TriggerInfo,+ ColumnInfo, DatabaseInfo, ForeignKeyInfo, IndexInfo, LinkedServerInfo, ObjectStatistics, QueryResult, TableInfo,+ TriggerInfo,};use futures::{FutureExt, TryStreamExt};use rust_decimal::Decimal;@@ -929,6 +930,44 @@ fn sqlserver_list_objects_sql(schema: &str) -> String {)}+pub async fn list_object_statistics(+ client: &mut SqlServerClient,+ schema: &str,+) -> Result<Vec<ObjectStatistics>, String> {+ let s = schema.replace('\'', "''");+ let sql = format!(+ "SELECT o.name, \+ SUM(CASE WHEN ps.index_id IN (0, 1) THEN ps.row_count ELSE 0 END) AS estimated_rows, \+ SUM(ps.reserved_page_count) * 8192 AS total_bytes \+ FROM sys.objects o \+ JOIN sys.schemas s ON s.schema_id = o.schema_id \+ JOIN sys.dm_db_partition_stats ps ON ps.object_id = o.object_id \+ WHERE s.name = '{s}' AND o.type = 'U' AND o.is_ms_shipped = 0 \+ GROUP BY o.object_id, o.name \+ ORDER BY o.name"+ );+ 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+ .iter()+ .map(|row| ObjectStatistics {+ name: row.get::<&str, _>(0).unwrap_or("").to_string(),+ schema: Some(schema.to_string()),+ estimated_rows: row+ .try_get::<i64, _>(1)+ .ok()+ .flatten()+ .or_else(|| row.try_get::<i32, _>(1).ok().flatten().map(i64::from)),+ total_bytes: row+ .try_get::<i64, _>(2)+ .ok()+ .flatten()+ .or_else(|| row.try_get::<i32, _>(2).ok().flatten().map(i64::from)),+ })+ .filter(|stat| !stat.name.is_empty())+ .collect())+}+pub async fn get_columns(client: &mut SqlServerClient, schema: &str, table: &str) -> Result<Vec<ColumnInfo>, String> {let sql = sqlserver_columns_sql(schema, table);let stream = client.query(&*sql, &[]).await.map_err(|e| e.to_string())?;diff --git a/crates/dbx-core/src/schema.rs b/crates/dbx-core/src/schema.rsindex 69100a1d6d..91621e9b50 100644--- a/crates/dbx-core/src/schema.rs+++ b/crates/dbx-core/src/schema.rs@@ -1004,6 +1004,18 @@ pub async fn list_objects_core(.await}+pub async fn list_object_statistics_core(+ state: &AppState,+ connection_id: &str,+ database: &str,+ schema: &str,+) -> Result<Vec<db::ObjectStatistics>, String> {+ retry_metadata_connection(state, connection_id, Some(database), || {+ list_object_statistics_once(state, connection_id, database, schema)+ })+ .await+}+pub async fn list_completion_objects_core(state: &AppState,connection_id: &str,@@ -1016,6 +1028,31 @@ pub async fn list_completion_objects_core(.await}+async fn list_object_statistics_once(+ state: &AppState,+ connection_id: &str,+ database: &str,+ schema: &str,+) -> Result<Vec<db::ObjectStatistics>, String> {+ let pool_key = state.get_or_create_pool(connection_id, Some(database)).await?;+ let db_config = connection_config(state, connection_id).await;+ let connections = state.connections.read().await;+ try_sqlserver!(connections, &pool_key, list_object_statistics, schema);+ let pool = connections.get(&pool_key).ok_or("Pool not found")?;+ match pool {+ PoolKind::Mysql(p, mode) => {+ if *mode == MysqlMode::OceanBaseOracle || db_config.as_ref().is_some_and(is_manticoresearch_config) {+ Ok(vec![])+ } else {+ db::mysql::list_object_statistics(p, database).await+ }+ }+ PoolKind::Postgres(p) if db_config.as_ref().is_some_and(is_questdb_config) => Ok(vec![]),+ PoolKind::Postgres(p) => db::postgres::list_object_statistics(p, schema).await,+ _ => Ok(vec![]),+ }+}+async fn list_objects_once(state: &AppState,connection_id: &str,diff --git a/crates/dbx-core/src/types.rs b/crates/dbx-core/src/types.rsindex 9704877e4c..b56b74403d 100644--- a/crates/dbx-core/src/types.rs+++ b/crates/dbx-core/src/types.rs@@ -34,6 +34,14 @@ pub struct ObjectInfo {pub parent_name: Option<String>,}+#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct ObjectStatistics {+ pub name: String,+ pub schema: Option<String>,+ pub estimated_rows: Option<i64>,+ pub total_bytes: Option<i64>,+}+#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]#[serde(rename_all = "SCREAMING_SNAKE_CASE")]pub enum ObjectSourceKind {diff --git a/crates/dbx-web/src/main.rs b/crates/dbx-web/src/main.rsindex f2d7733f24..9b7e713cce 100644--- a/crates/dbx-web/src/main.rs+++ b/crates/dbx-web/src/main.rs@@ -200,6 +200,7 @@ async fn main() {.route("/schema/schemas", get(routes::schema::list_schemas)).route("/schema/tables", get(routes::schema::list_tables)).route("/schema/objects", get(routes::schema::list_objects))+ .route("/schema/object-statistics", get(routes::schema::list_object_statistics)).route("/schema/completion-objects", get(routes::schema::list_completion_objects)).route("/schema/object-source", get(routes::schema::get_object_source)).route("/schema/columns", get(routes::schema::list_columns))diff --git a/crates/dbx-web/src/routes/schema.rs b/crates/dbx-web/src/routes/schema.rsindex 0df039f63c..d2a0db4f10 100644--- a/crates/dbx-web/src/routes/schema.rs+++ b/crates/dbx-web/src/routes/schema.rs@@ -129,6 +129,18 @@ pub async fn list_objects(Ok(Json(serde_json::to_value(result).map_err(|e| AppError(e.to_string()))?))}+pub async fn list_object_statistics(+ State(state): State<Arc<WebState>>,+ Query(q): Query<SchemaQuery>,+) -> Result<Json<serde_json::Value>, AppError> {+ let database = q.database.as_deref().unwrap_or("");+ let schema = q.schema.as_deref().unwrap_or("");+ let result = dbx_core::schema::list_object_statistics_core(&state.app, &q.connection_id, database, schema)+ .await+ .map_err(AppError)?;+ Ok(Json(serde_json::to_value(result).map_err(|e| AppError(e.to_string()))?))+}+pub async fn list_completion_objects(State(state): State<Arc<WebState>>,Query(q): Query<SchemaQuery>,diff --git a/packages/app-tests/objectBrowserRows.test.ts b/packages/app-tests/objectBrowserRows.test.tsindex f9a754ae4d..4266379c2d 100644--- a/packages/app-tests/objectBrowserRows.test.ts+++ b/packages/app-tests/objectBrowserRows.test.ts@@ -1,6 +1,6 @@import { strict as assert } from "node:assert";import { test } from "vitest";-import { buildObjectBrowserRows, filterObjectBrowserRows, formatObjectBrowserTimestamp, sortObjectBrowserRows } from "../../apps/desktop/src/lib/objectBrowserRows.ts";+import { buildObjectBrowserRows, filterObjectBrowserRows, formatObjectBrowserBytes, formatObjectBrowserCount, formatObjectBrowserTimestamp, sortObjectBrowserRows } from "../../apps/desktop/src/lib/objectBrowserRows.ts";test("builds unique row ids for overloaded routines with the same visible name", () => {const rows = buildObjectBrowserRows({@@ -121,6 +121,38 @@ test("object browser rows preserve table timestamps and sort recent updates firsassert.equal(formatObjectBrowserTimestamp(rows[0].created_at), "2026-05-20 09:30:00");});+test("object browser rows sort estimated rows and table size with empty values last", () => {+ const rows = buildObjectBrowserRows({+ objects: [+ { name: "empty_stats", object_type: "TABLE", schema: "public" },+ { name: "small_table", object_type: "TABLE", schema: "public" },+ { name: "large_table", object_type: "TABLE", schema: "public" },+ ],+ database: "app",+ fallbackSchema: "public",+ needsSchema: true,+ });+ rows.find((row) => row.name === "small_table")!.estimatedRows = 12;+ rows.find((row) => row.name === "large_table")!.estimatedRows = 1200;+ rows.find((row) => row.name === "small_table")!.totalBytes = 4096;+ rows.find((row) => row.name === "large_table")!.totalBytes = 8192;++ assert.deepEqual(+ sortObjectBrowserRows(rows, "estimatedRows", "desc").map((row) => row.name),+ ["large_table", "small_table", "empty_stats"],+ );+ assert.deepEqual(+ sortObjectBrowserRows(rows, "totalBytes", "asc").map((row) => row.name),+ ["small_table", "large_table", "empty_stats"],+ );+});++test("object browser formats statistics for compact table cells", () => {+ assert.equal(formatObjectBrowserCount(1234567), "1,234,567");+ assert.equal(formatObjectBrowserBytes(1536), "1.50 KB");+ assert.equal(formatObjectBrowserBytes(null), "");+});+test("object browser name sort keeps base-prefixed tables before prefixed variants", () => {const rows = buildObjectBrowserRows({objects: [diff --git a/src-tauri/src/commands/schema.rs b/src-tauri/src/commands/schema.rsindex 85503217ba..6264845099 100644--- a/src-tauri/src/commands/schema.rs+++ b/src-tauri/src/commands/schema.rs@@ -106,6 +106,16 @@ pub async fn list_objects(dbx_core::schema::list_objects_core(&state, &connection_id, &database, &schema).await}+#[tauri::command]+pub async fn list_object_statistics(+ state: State<'_, Arc<AppState>>,+ connection_id: String,+ database: String,+ schema: String,+) -> Result<Vec<db::ObjectStatistics>, String> {+ dbx_core::schema::list_object_statistics_core(&state, &connection_id, &database, &schema).await+}+#[tauri::command]pub async fn list_completion_objects(state: State<'_, Arc<AppState>>,diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rsindex f36090c00e..061704b4c0 100644--- a/src-tauri/src/lib.rs+++ b/src-tauri/src/lib.rs@@ -380,6 +380,7 @@ pub fn run() {commands::schema::list_sqlserver_linked_server_tables,commands::schema::list_tables,commands::schema::list_objects,+ commands::schema::list_object_statistics,commands::schema::list_completion_objects,commands::schema::get_object_source,commands::schema::list_schemas,