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。

11.5 KB
Raw Blame
import { resolveDefaultDatabase } from "@/lib/database/defaultDatabase";
import { normalizeSqliteNamespace } from "@/lib/database/sqliteNamespace";
import type { SqlFormatterCase } from "@/lib/sql/sqlFormatterConfig";
import { metricRangeQuery, qualifiedTableName } from "@/lib/table/tableSelectSql";
import type { ConnectionConfig, DatabaseType, QueryTab, TreeNode } from "@/types/database";

export interface NewQueryTarget {
  connectionId: string;
  database: string;
  schema?: string;
  /** 该 schema 是否由用户显式选择,可参与 SQL Server 的未限定表名改写。 */
  schemaQualifiesSql?: boolean;
  catalog?: string;
  shouldRefreshDefaultDatabase: boolean;
}

export type NewQueryContextSource = "tab" | "sidebar";

interface ResolveNewQueryTargetInput {
  activeTab?: Pick<QueryTab, "connectionId" | "database" | "schema" | "catalog" | "objectBrowser" | "tableMeta">;
  selectedTreeNode?: Pick<TreeNode, "connectionId" | "database" | "schema" | "catalog"> | null;
  activeConnectionId?: string | null;
  connections: Pick<ConnectionConfig, "id" | "host" | "database" | "default_schema" | "db_type">[];
  preferredSource?: NewQueryContextSource;
  /** Ids of currently online SQL connections, used only when there is exactly one. */
  connectedSqlConnectionIds?: ReadonlySet<string>;
}

export function findTreeNodeById(nodes: TreeNode[], id: string | null | undefined): TreeNode | null {
  if (!id) return null;
  for (const node of nodes) {
    if (node.id === id) return node;
    const found = findTreeNodeById(node.children || [], id);
    if (found) return found;
  }
  return null;
}

export function resolveNewQueryTarget(input: ResolveNewQueryTargetInput): NewQueryTarget | null {
  const primaryContext = input.preferredSource === "sidebar" ? input.selectedTreeNode || undefined : input.activeTab;
  const secondaryContext = input.preferredSource === "sidebar" ? input.activeTab : input.selectedTreeNode || undefined;
  const primaryKind: NewQueryContextSource = input.preferredSource === "sidebar" ? "sidebar" : "tab";
  const secondaryKind: NewQueryContextSource = primaryKind === "sidebar" ? "tab" : "sidebar";
  const primaryTarget = targetFromContext(primaryContext, input.connections, primaryKind);
  if (primaryTarget) return primaryTarget;
  const secondaryTarget = targetFromContext(secondaryContext, input.connections, secondaryKind);
  if (secondaryTarget) return secondaryTarget;

  const activeConnection = input.activeConnectionId ? input.connections.find((connection) => connection.id === input.activeConnectionId) : undefined;
  // Preserve an explicit active connection, then use the only online SQL
  // connection. A sole configured connection remains a safe legacy fallback;
  // when several choices remain, return null so the caller can leave selection
  // to the user instead of silently taking connections[0].
  const fallbackConnection = activeConnection ?? singleOnlineSqlConnection(input.connections, input.connectedSqlConnectionIds) ?? (input.connections.length === 1 ? input.connections[0] : undefined);
  return fallbackConnection
    ? {
        connectionId: fallbackConnection.id,
        database: resolveDefaultDatabase(fallbackConnection, []),
        schema: fallbackConnection.default_schema,
        shouldRefreshDefaultDatabase: true,
      }
    : null;
}

/**
 * The one online SQL connection, when there is exactly one. An ambiguous or
 * empty online set must not be resolved by connection-list order.
 */
function singleOnlineSqlConnection(connections: ResolveNewQueryTargetInput["connections"], connectedSqlConnectionIds?: ReadonlySet<string>): ResolveNewQueryTargetInput["connections"][number] | undefined {
  if (!connectedSqlConnectionIds || connectedSqlConnectionIds.size !== 1) return undefined;
  const [onlyOnlineId] = connectedSqlConnectionIds;
  return connections.find((connection) => connection.id === onlyOnlineId);
}

function targetFromContext(
  context: Pick<QueryTab, "connectionId" | "database" | "schema" | "catalog" | "objectBrowser" | "tableMeta" | "schemaQualifiesSql"> | Pick<TreeNode, "connectionId" | "database" | "schema" | "catalog"> | undefined,
  connections: Pick<ConnectionConfig, "id" | "host" | "database" | "default_schema" | "db_type">[],
  contextKind: NewQueryContextSource,
): NewQueryTarget | null {
  if (!context?.connectionId) return null;
  const connection = connections.find((item) => item.id === context.connectionId);
  if (!connection) return null;
  const contextDatabase = context.database || resolveDefaultDatabase(connection, []);
  const database = connection.db_type === "sqlite" ? normalizeSqliteNamespace(contextDatabase, connection) : contextDatabase;
  const objectBrowser = "objectBrowser" in context ? context.objectBrowser : undefined;
  const tableMeta = "tableMeta" in context ? context.tableMeta : undefined;
  const schema = context.schema ?? objectBrowser?.schema ?? tableMeta?.schema ?? connection.default_schema;
  // 侧栏节点自身的 schema 都是用户点出来的;连接/库节点回落到 default_schema
  // 时不算显式。页签只有显式选择(或来自更具体的对象上下文)才算显式,
  // 避免把默认/恢复的 schema 带进执行。
  const schemaQualifiesSql =
    schema === undefined ? false : contextKind === "sidebar" ? context.schema !== undefined : ("schemaQualifiesSql" in context && context.schemaQualifiesSql === true) || (!!objectBrowser?.schema && schema === objectBrowser.schema) || (!!tableMeta?.schema && schema === tableMeta.schema);
  return {
    connectionId: context.connectionId,
    database,
    schema,
    ...(schemaQualifiesSql ? { schemaQualifiesSql: true } : {}),
    catalog: context.catalog ?? objectBrowser?.catalog ?? tableMeta?.catalog,
    shouldRefreshDefaultDatabase: !context.database,
  };
}

export interface NewQueryTable {
  connectionId: string;
  database: string;
  schema?: string;
  catalog?: string;
  tableName: string;
}

export interface ResolveNewQueryTableInput {
  activeTab?: Pick<QueryTab, "mode" | "connectionId" | "database" | "schema" | "catalog" | "tableMeta" | "structureTableName" | "title"> | null;
  selectedTreeNode?: Pick<TreeNode, "type" | "connectionId" | "database" | "schema" | "catalog" | "tableName" | "label"> | null;
  preferredSource?: NewQueryContextSource;
}

export interface ResolveNewQueryInitialSqlInput extends ResolveNewQueryTableInput {
  prefillEnabled: boolean;
  targetConnectionId: string;
  targetDatabase: string;
  databaseType?: DatabaseType;
  driverProfile?: string;
  identifierQuote?: string;
  includeDatabaseName?: boolean;
  quoteIdentifiers?: boolean;
  keywordCase?: SqlFormatterCase;
}

// Database types whose "table" view does not use standard SQL `SELECT * FROM <table>`
// (e.g. Neo4j uses Cypher). The new-query prefill is skipped for these.
const NEW_QUERY_PREFILL_DISABLED_TYPES: ReadonlySet<DatabaseType | undefined> = new Set<DatabaseType | undefined>(["neo4j", "nebula"]);

export function isNewQueryPrefillSupported(databaseType: DatabaseType | undefined): boolean {
  return !NEW_QUERY_PREFILL_DISABLED_TYPES.has(databaseType);
}

function tableFromTab(tab: ResolveNewQueryTableInput["activeTab"]): NewQueryTable | null {
  if (!tab?.connectionId) return null;
  if (tab.mode === "data") {
    // Require the loaded tableMeta: a data tab's title is schema/catalog-qualified
    // (e.g. "public.users"), so using it as a bare table name while tableMeta is
    // still loading or errored would yield an invalid double-qualified reference.
    const meta = tab.tableMeta;
    const tableName = meta?.tableName?.trim();
    if (!tableName) return null;
    return { connectionId: tab.connectionId, database: tab.database, schema: meta?.schema ?? tab.schema, catalog: meta?.catalog, tableName };
  }
  if (tab.mode === "structure") {
    const tableName = (tab.structureTableName || "").trim();
    if (!tableName) return null;
    return { connectionId: tab.connectionId, database: tab.database, schema: tab.schema, catalog: tab.catalog, tableName };
  }
  return null;
}

function tableFromNode(node: ResolveNewQueryTableInput["selectedTreeNode"]): NewQueryTable | null {
  if (!node?.connectionId) return null;
  if (node.type !== "table" && node.type !== "view" && node.type !== "materialized_view") return null;
  const tableName = (node.tableName || node.label || "").trim();
  if (!tableName) return null;
  return { connectionId: node.connectionId, database: node.database || "", schema: node.schema, catalog: node.catalog, tableName };
}

/**
 * Resolves the "focused table" for a new query, mirroring the primary/secondary
 * selection of {@link resolveNewQueryTarget}: when `preferredSource` is `"sidebar"`
 * the selected tree node wins, otherwise the active tab wins; the other is the
 * fallback. Returns null when no table context is available.
 */
export function resolveNewQueryTable(input: ResolveNewQueryTableInput): NewQueryTable | null {
  const tabFirst = input.preferredSource !== "sidebar";
  const primary = tabFirst ? tableFromTab(input.activeTab) : tableFromNode(input.selectedTreeNode);
  if (primary) return primary;
  return tabFirst ? tableFromNode(input.selectedTreeNode) : tableFromTab(input.activeTab);
}

/**
 * Builds a `SELECT * FROM <table>` statement for the new-query prefill, reusing
 * the same per-dialect identifier quoting and schema/catalog qualification used
 * by the table-data view.
 *
 * Time-series engines get the same rolling-window scoping the sidebar
 * quick-open uses (see `default_time_series_predicate` in
 * `crates/dbx-sql-dialect/src/sql_dialect/table_select.rs`). Without a `time`
 * predicate InfluxDB scans every shard (v1/v2) or every Parquet file
 * (v3), which turns "let me draft a query against this table" into a
 * full-history scan the moment the user hits Run. VictoriaMetrics
 * already has its own metric range template above.
 */
export function buildSelectAllSql(
  databaseType: DatabaseType | undefined,
  table: Pick<NewQueryTable, "schema" | "catalog" | "tableName"> & Partial<Pick<NewQueryTable, "database">>,
  identifierQuote?: string,
  driverProfile?: string,
  includeDatabaseName = false,
  quoteIdentifiers = true,
  keywordCase?: SqlFormatterCase,
): string {
  if (databaseType === "victoriametrics") return metricRangeQuery(table.tableName);
  const ref = qualifiedTableName({ databaseType, driverProfile, identifierQuote, database: table.database, schema: table.schema, catalog: table.catalog, tableName: table.tableName, includeDatabaseName, quoteIdentifiers });
  const keywords = (sql: string) => (keywordCase === "lower" ? sql.toLowerCase() : sql);
  if (databaseType === "influxdb") {
    return `${keywords("SELECT * FROM")} ${ref} ${keywords("WHERE time > now() - 5m ORDER BY time DESC LIMIT 100")}`;
  }
  if (databaseType === "influxdb3") {
    return `${keywords("SELECT * FROM")} ${ref} ${keywords("WHERE time > now() - INTERVAL '5 minutes' ORDER BY time DESC LIMIT 100")}`;
  }
  return `${keywords("SELECT * FROM")} ${ref}`;
}

/**
 * Resolves the optional initial SQL for a new query tab. A table from another
 * connection or database is intentionally ignored because it cannot safely run
 * in the execution context selected for the new tab.
 */
export function resolveNewQueryInitialSql(input: ResolveNewQueryInitialSqlInput): string | undefined {
  if (!input.prefillEnabled || !isNewQueryPrefillSupported(input.databaseType)) return undefined;

  const table = resolveNewQueryTable(input);
  if (!table || table.connectionId !== input.targetConnectionId || table.database !== input.targetDatabase) return undefined;

  return buildSelectAllSql(input.databaseType, table, input.identifierQuote, input.driverProfile, input.includeDatabaseName, input.quoteIdentifiers, input.keywordCase);
}