refactor(desktop): organize lib modules by domain

This commit is contained in:
t8y2 committed 2026-07-04 13:53:52 +08:00
1 parent 90f0594e93
commit 7e7c4944e9
700 files changed
+1292 -1264

No files matched your search

@@ -0,0 +1,38 @@
export const DEFAULT_REPEATED_ACTIVATION_WINDOW_MS = 500;
export interface ActionActivationGuard {
lastActivatedAt?: number;
running?: boolean;
}
function nowMs(): number {
if (typeof performance !== "undefined" && typeof performance.now === "function") {
return performance.now();
}
return Date.now();
}
export function shouldSuppressRepeatedActivation(guard: ActionActivationGuard, now = nowMs(), windowMs = DEFAULT_REPEATED_ACTIVATION_WINDOW_MS): boolean {
if (guard.lastActivatedAt !== undefined && now - guard.lastActivatedAt < windowMs) {
return true;
}
guard.lastActivatedAt = now;
return false;
}
export function suppressEvent(event: Event) {
event.preventDefault();
event.stopPropagation();
event.stopImmediatePropagation?.();
}
export function tryStartExclusiveActivation(guard: ActionActivationGuard): (() => void) | null {
if (guard.running) return null;
guard.running = true;
let finished = false;
return () => {
if (finished) return;
finished = true;
guard.running = false;
};
}
@@ -0,0 +1,35 @@
import type { DatabaseType } from "@/types/database";
import { supportsDriverManagement } from "@/lib/database/databaseCapabilities";
export interface AgentDriverInstallState {
db_type: string;
installed: boolean;
update_available?: boolean;
}
export function agentDriverInstallKey(dbType: DatabaseType | undefined, driverProfile?: string): string | undefined {
if (dbType === "oracle") return "oracle";
if (dbType === "mongodb") return "mongodb";
if (dbType === "dameng") return "dameng";
if (dbType === "mq") return driverProfile === "kafka" ? "kafka" : undefined;
return driverProfile && driverProfile !== dbType ? driverProfile : dbType;
}
export function showAgentDriverInstallHint(dbType: DatabaseType | undefined, drivers: readonly AgentDriverInstallState[], driverProfile?: string): boolean {
if (!supportsDriverManagement(dbType)) return false;
const driverKey = agentDriverInstallKey(dbType, driverProfile);
if (!driverKey) return false;
return drivers.find((driver) => driver.db_type === driverKey)?.installed !== true;
}
export function hasAgentDriverUpdate(dbType: DatabaseType | undefined, drivers: readonly AgentDriverInstallState[], driverProfile?: string): boolean {
if (!supportsDriverManagement(dbType)) return false;
const driverKey = agentDriverInstallKey(dbType, driverProfile);
return drivers.find((driver) => driver.db_type === driverKey)?.update_available === true;
}
export function appendAgentDriverUpdateHint(message: string, hint: string): string {
if (!message.trim()) return hint;
if (message.includes(hint)) return message;
return `${message}\n\n${hint}`;
}
@@ -0,0 +1,15 @@
export interface AgentDriverUpdateBadgeState {
update_available: boolean;
}
export function countAvailableAgentDriverUpdates(drivers: readonly AgentDriverUpdateBadgeState[]): number {
return drivers.filter((driver) => driver.update_available).length;
}
export interface JdbcPluginUpdateBadgeState {
update_available?: boolean | null;
}
export function countAvailableDriverUpdates(drivers: readonly AgentDriverUpdateBadgeState[], jdbcPlugin?: JdbcPluginUpdateBadgeState | null): number {
return countAvailableAgentDriverUpdates(drivers) + (jdbcPlugin?.update_available ? 1 : 0);
}
@@ -0,0 +1,74 @@
import type { ConnectionConfig, DatabaseType } from "@/types/database";
export const CONNECTION_ATTEMPT_TIMEOUT_BUFFER_MS = 2_000;
export const MONGO_LEGACY_FALLBACK_TIMEOUT_BUFFER_MS = 30_000;
export const AGENT_DRIVER_MIN_CONNECT_TIMEOUT_SECS = 30;
export const ACCESS_AGENT_MIN_CONNECT_TIMEOUT_SECS = 30;
const DEFAULT_CONNECT_TIMEOUT_SECS = 10;
const DRIVER_STARTUP_FLOOR_TYPES = new Set<DatabaseType>([
"dameng",
"kingbase",
"highgo",
"vastbase",
"goldendb",
"yashandb",
"databricks",
"saphana",
"teradata",
"vertica",
"firebird",
"exasol",
"oceanbase-oracle",
"gbase",
"access",
"oracle",
"h2",
"snowflake",
"trino",
"prestosql",
"jdbc",
"hive",
"db2",
"informix",
"neo4j",
"cassandra",
"bigquery",
"kylin",
"sundb",
"oscar",
"tdengine",
"xugu",
"iotdb",
"etcd",
"zookeeper",
"iris",
]);
function positiveSeconds(value: unknown, fallback: number): number {
return typeof value === "number" && Number.isFinite(value) && value > 0 ? value : fallback;
}
export function connectionAttemptTimeoutMs(config: Pick<ConnectionConfig, "connect_timeout_secs" | "transport_layers"> & Partial<Pick<ConnectionConfig, "db_type">>): number {
const baseTimeoutSecs = positiveSeconds(config.connect_timeout_secs, DEFAULT_CONNECT_TIMEOUT_SECS);
const agentMinTimeoutSecs = config.db_type === "access" ? ACCESS_AGENT_MIN_CONNECT_TIMEOUT_SECS : AGENT_DRIVER_MIN_CONNECT_TIMEOUT_SECS;
const timeouts = [DRIVER_STARTUP_FLOOR_TYPES.has(config.db_type as DatabaseType) ? Math.max(baseTimeoutSecs, agentMinTimeoutSecs) : baseTimeoutSecs];
for (const layer of config.transport_layers ?? []) {
if (layer.enabled === false) continue;
if (layer.type === "ssh" || layer.type === "http_tunnel") {
timeouts.push(positiveSeconds(layer.connect_timeout_secs, DEFAULT_CONNECT_TIMEOUT_SECS));
}
}
const fallbackBuffer = config.db_type === "mongodb" ? MONGO_LEGACY_FALLBACK_TIMEOUT_BUFFER_MS : 0;
return Math.ceil(Math.max(...timeouts) * 1000 + CONNECTION_ATTEMPT_TIMEOUT_BUFFER_MS + fallbackBuffer);
}
export function connectionAttemptTimeoutMessage(timeoutMs: number): string {
return `Connection attempt timed out after ${Math.ceil(timeoutMs / 1000)}s. Please check the network or VPN and try again.`;
}
export function connectionAttemptOriginalErrorMessage(timeoutMessage: string, originalMessage: string): string {
const message = originalMessage.trim();
if (!message || message === timeoutMessage) return timeoutMessage;
return `${timeoutMessage}\n\nOriginal database error returned after the UI timeout:\n${message}`;
}
@@ -0,0 +1,110 @@
import type { DatabaseType } from "@/types/database";
import { connectionProfileForScheme, parseConnectionUrl } from "@/lib/connection/connectionUrl";
export interface ConnectionDeepLinkDraft {
name?: string;
dbType: DatabaseType;
driverProfile: string;
driverLabel: string;
host?: string;
port?: number;
username?: string;
password?: string;
database?: string;
urlParams?: string;
ssl?: boolean;
connectionString?: string;
oracleConnectionType?: "service_name" | "sid";
useMongoUrl?: boolean;
oneTime?: boolean;
}
const CONNECTION_DEEP_LINK_TARGET = "connection/new";
function normalizePath(url: URL): string {
return [url.hostname, url.pathname.replace(/^\/+/, "")].filter(Boolean).join("/").replace(/\/+$/, "");
}
function optionalParam(params: URLSearchParams, ...keys: string[]): string | undefined {
for (const key of keys) {
const value = params.get(key)?.trim();
if (value) return value;
}
return undefined;
}
function optionalNumberParam(params: URLSearchParams, ...keys: string[]): number | undefined {
const value = optionalParam(params, ...keys);
if (!value) return undefined;
const numberValue = Number(value);
return Number.isFinite(numberValue) && numberValue > 0 ? numberValue : undefined;
}
function optionalBooleanParam(params: URLSearchParams, ...keys: string[]): boolean {
const value = optionalParam(params, ...keys)?.toLowerCase();
return value === "true" || value === "1" || value === "yes" || value === "on";
}
function draftFromConnectionUrl(value: string, preferredProfile?: string): ConnectionDeepLinkDraft {
const parsed = parseConnectionUrl(value, preferredProfile);
return {
name: parsed.name,
dbType: parsed.dbType,
driverProfile: parsed.driverProfile,
driverLabel: parsed.driverLabel,
host: parsed.host,
port: parsed.port,
username: parsed.username,
password: parsed.password,
database: parsed.database,
urlParams: parsed.urlParams,
ssl: parsed.ssl,
connectionString: parsed.connectionString,
oracleConnectionType: parsed.oracleConnectionType,
useMongoUrl: parsed.useMongoUrl,
};
}
export function parseConnectionDeepLink(value: string): ConnectionDeepLinkDraft | null {
let url: URL;
try {
url = new URL(value);
} catch {
return null;
}
if (url.protocol !== "dbx:") return null;
if (normalizePath(url) !== CONNECTION_DEEP_LINK_TARGET) return null;
const params = url.searchParams;
const preferredProfile = optionalParam(params, "type");
const rawConnectionUrl = optionalParam(params, "url");
const draft: ConnectionDeepLinkDraft = rawConnectionUrl
? draftFromConnectionUrl(rawConnectionUrl, preferredProfile)
: (() => {
const profile = connectionProfileForScheme(preferredProfile || "mysql");
if (!profile) throw new Error(`Unsupported connection type: ${preferredProfile}`);
return {
dbType: profile.type,
driverProfile: profile.profile,
driverLabel: profile.label,
port: profile.defaultPort,
ssl: false,
};
})();
const oneTime = optionalBooleanParam(params, "one_time");
return {
...draft,
name: optionalParam(params, "name") ?? draft.name,
host: optionalParam(params, "host") ?? draft.host,
port: optionalNumberParam(params, "port") ?? draft.port,
username: optionalParam(params, "user") ?? draft.username,
password: optionalParam(params, "password") ?? draft.password,
database: optionalParam(params, "database") ?? draft.database,
urlParams: optionalParam(params, "url_params") ?? draft.urlParams,
ssl: optionalBooleanParam(params, "ssl") ? true : draft.ssl,
...(oneTime ? { oneTime: true } : {}),
};
}
@@ -0,0 +1,76 @@
import type { ConnectionConfig, DatabaseType } from "@/types/database";
import { h2FilePathFromJdbcUrl } from "@/lib/database/h2Connection";
/**
* Whether the database type is one that (potentially) backs onto a local file.
* This is a type-level check only — it does not verify that a valid path is
* configured. Use this to decide whether to show file-path UI; use
* `isLocalFileDb` / `connectionFilePath` to decide whether a reveal action is
* available.
*/
export function isLocalFileTypeDb(dbType: DatabaseType | string): boolean {
return dbType === "sqlite" || dbType === "duckdb" || dbType === "access" || dbType === "h2";
}
/**
* Extract the on-disk file path of a connection if (and only if) the
* connection backs onto a single local file.
*
* - SQLite / DuckDB / Access: `host` holds the file path.
* - H2 file mode: path is parsed out of the JDBC URL via `h2FilePathFromJdbcUrl`.
* H2 stores its data in `<base>.mv.db` (default) or `<base>.h2.db`; we hand
* back the base path the user actually configured so the Tauri side can try
* reasonable variants when the literal path isn't a file.
*
* Returns `null` for in-memory (`:memory:`), empty paths, H2 server/mem mode,
* and any DB type that isn't local-file.
*/
export function connectionFilePath(config: Pick<ConnectionConfig, "db_type" | "host" | "connection_string">): string | null {
const dbType = config.db_type;
if (dbType === "sqlite" || dbType === "duckdb" || dbType === "access") {
const host = (config.host ?? "").trim();
if (!host || host === ":memory:") return null;
return host;
}
if (dbType === "h2") {
const fromUrl = h2FilePathFromJdbcUrl(config.connection_string);
const trimmed = (fromUrl ?? "").trim();
if (!trimmed) return null;
return trimmed;
}
return null;
}
/**
* Whether the connection has a meaningful local file path that can be revealed
* in the OS file manager. True iff `connectionFilePath` returns non-null.
*/
export function isLocalFileDb(config: Pick<ConnectionConfig, "db_type" | "host" | "connection_string">): boolean {
return connectionFilePath(config) !== null;
}
export function isMemorySqlitePath(path: string | undefined | null): boolean {
return (path ?? "").trim().toLowerCase() === ":memory:";
}
export function sqliteBackupSourcePath(config: Pick<ConnectionConfig, "db_type" | "host">): string | null {
if (config.db_type !== "sqlite") return null;
const host = (config.host ?? "").trim();
return host || null;
}
export function defaultSqliteBackupFileName(config: Pick<ConnectionConfig, "host" | "name">): string {
const source = (config.host || config.name || "database").trim();
const rawFileName = isMemorySqlitePath(source) ? "memory.db" : source.split(/[\\/]/).filter(Boolean).pop() || "database.db";
const fileName = sanitizeFileName(rawFileName) || "database.db";
const dotIndex = fileName.lastIndexOf(".");
if (dotIndex <= 0) return `${fileName}.backup.db`;
return `${fileName.slice(0, dotIndex)}.backup${fileName.slice(dotIndex)}`;
}
function sanitizeFileName(fileName: string): string {
return fileName
.replace(/[<>:"/\\|?*\u0000-\u001f]/g, "_")
.trim()
.replace(/[. ]+$/g, "");
}
@@ -0,0 +1,45 @@
const CONNECTION_ERROR_PATTERNS = [
"connection reset",
"connection refused",
"connection timed out",
"connection closed",
"connection lost",
"connection not found",
"connection config not found",
"not connected",
"closed the connection",
"broken pipe",
"reset by peer",
"socket closed",
"unexpected eof",
"end-of-file",
"end-of-file on communication channel",
"server closed session",
"communicating with the server",
"exceeded maximum idle time",
"agent stdin not available",
"agent stdout not available",
"failed to write to agent stdin",
"failed to flush agent stdin",
"input/output error",
"关闭的连接",
"连接已关闭",
"i/o error",
"no route to host",
];
export function staleConnectionMessage(error: unknown): string {
if (error instanceof Error) return error.message;
return String(error);
}
export function shouldMarkDisconnected(error: unknown): boolean {
const message = staleConnectionMessage(error).toLowerCase();
return CONNECTION_ERROR_PATTERNS.some((pattern) => message.includes(pattern)) || hasConnectionOsError(message);
}
function hasConnectionOsError(message: string): boolean {
const osErrorCodes = new Set(["65", "10053", "10054", "10057", "10058", "10060", "10061"]);
const match = message.match(/os error\s+(\d+)/);
return !!match && osErrorCodes.has(match[1]);
}
@@ -0,0 +1,217 @@
import { splitSqlStatementRanges } from "@/lib/sql/sqlStatementRanges";
import { supportsCreateDatabaseCharset } from "@/lib/database/createDatabaseSql";
import type { ConnectionConfig, DatabaseType } from "@/types/database";
const MYSQL_BOOTSTRAP_EXTRA_PROFILES = new Set(["selectdb", "goldendb"]);
type BootstrapConnection = Pick<ConnectionConfig, "db_type" | "driver_profile">;
type ParsedIdentifier = { identifier: string; rest: string };
function splitBootstrapStatements(sql: string, dbType?: DatabaseType): string[] {
return splitSqlStatementRanges(sql, dbType)
.map((statement) => statement.sql.trim())
.filter(Boolean);
}
function parseMysqlIdentifier(input: string): ParsedIdentifier | null {
const first = input[0];
if (!first) return null;
if (first === "`" || first === '"') {
return parseDoubledDelimitedIdentifier(input, first);
}
if (first === "[") {
return parseBracketIdentifier(input);
}
const end = input.search(/[\s;]/);
const identifier = (end === -1 ? input : input.slice(0, end)).trim();
if (!identifier) return null;
return { identifier, rest: end === -1 ? "" : input.slice(end) };
}
function parseDoubledDelimitedIdentifier(input: string, quote: "`" | '"'): ParsedIdentifier | null {
let index = 1;
let segmentStart = 1;
let identifier = "";
while (index < input.length) {
if (input[index] === quote) {
identifier += input.slice(segmentStart, index);
if (input[index + 1] === quote) {
identifier += quote;
index += 2;
segmentStart = index;
continue;
}
return { identifier, rest: input.slice(index + 1) };
}
index += 1;
}
return null;
}
function parseBracketIdentifier(input: string): ParsedIdentifier | null {
let index = 1;
let segmentStart = 1;
let identifier = "";
while (index < input.length) {
if (input[index] === "]") {
identifier += input.slice(segmentStart, index);
if (input[index + 1] === "]") {
identifier += "]";
index += 2;
segmentStart = index;
continue;
}
return { identifier, rest: input.slice(index + 1) };
}
index += 1;
}
return null;
}
function stripLeadingSqlComments(sql: string): string {
let rest = sql;
for (;;) {
rest = rest.trimStart();
if (!rest) return rest;
if (rest.startsWith("--")) {
const index = rest.indexOf("\n");
if (index === -1) return "";
rest = rest.slice(index + 1);
continue;
}
if (rest.startsWith("#")) {
const index = rest.indexOf("\n");
if (index === -1) return "";
rest = rest.slice(index + 1);
continue;
}
if (rest.startsWith("/*")) {
const index = rest.indexOf("*/");
if (index === -1) return "";
rest = rest.slice(index + 2);
continue;
}
return rest;
}
}
function leadingSqlKeyword(statement: string): [keyword: string, rest: string] | null {
const trimmed = statement.trimStart();
const match = trimmed.match(/^[A-Za-z_][A-Za-z0-9_]*/);
if (!match) return null;
return [match[0], trimmed.slice(match[0].length)];
}
function sqlRemainderIsCommentOnly(remainder: string): boolean {
let rest = remainder;
for (;;) {
rest = rest.trimStart();
if (!rest) return true;
if (rest.startsWith(";")) {
rest = rest.slice(1);
continue;
}
if (rest.startsWith("--") || rest.startsWith("#")) {
return true;
}
if (rest.startsWith("/*")) {
const index = rest.indexOf("*/");
if (index === -1) return false;
rest = rest.slice(index + 2);
continue;
}
return false;
}
}
function parseMysqlUseDatabaseTarget(statement: string): string | null {
const stripped = stripLeadingSqlComments(statement);
const match = stripped.match(/^USE\b/i);
if (!match) return null;
const parsed = parseMysqlIdentifier(stripped.slice(match[0].length).trimStart());
if (!parsed) return null;
return sqlRemainderIsCommentOnly(parsed.rest) ? parsed.identifier : null;
}
function isDatabaseKeyword(keyword: string): boolean {
const normalized = keyword.toUpperCase();
return normalized === "DATABASE" || normalized === "SCHEMA";
}
function isAllowedBootstrapPrelude(statement: string): boolean {
const stripped = stripLeadingSqlComments(statement);
const leading = leadingSqlKeyword(stripped);
if (!leading) return false;
const [keyword, rest] = leading;
const normalized = keyword.toUpperCase();
if (normalized === "SET") {
return true;
}
if (normalized !== "CREATE" && normalized !== "DROP") {
return false;
}
const next = leadingSqlKeyword(rest);
return !!next && isDatabaseKeyword(next[0]);
}
export function supportsConnectionLevelDatabaseBootstrap(connection: BootstrapConnection | undefined): boolean {
if (!connection) return false;
if (supportsCreateDatabaseCharset(connection.db_type, connection.driver_profile)) return true;
return !!connection.driver_profile && MYSQL_BOOTSTRAP_EXTRA_PROFILES.has(connection.driver_profile.toLowerCase());
}
export function canExecuteWithoutSelectedDatabase(connection: BootstrapConnection | undefined, sql: string): boolean {
if (!supportsConnectionLevelDatabaseBootstrap(connection)) return false;
const statements = splitBootstrapStatements(sql, connection?.db_type);
if (statements.length === 0) return false;
let sawStatement = false;
let hasDatabaseContext = false;
for (const statement of statements) {
const stripped = stripLeadingSqlComments(statement);
if (!stripped) continue;
sawStatement = true;
if (isAllowedBootstrapPrelude(stripped)) {
continue;
}
if (parseMysqlUseDatabaseTarget(stripped)) {
hasDatabaseContext = true;
continue;
}
if (!hasDatabaseContext) {
return false;
}
}
return sawStatement;
}
export function requiresSqlFileTargetDatabaseSelection(connection: BootstrapConnection | undefined, sqlCanExecuteWithoutSelectedDatabase = false): boolean {
if (!supportsConnectionLevelDatabaseBootstrap(connection)) return true;
return !sqlCanExecuteWithoutSelectedDatabase;
}
@@ -0,0 +1,14 @@
import type { ConnectionConfig } from "@/types/database";
import { resolveDefaultDatabase } from "@/lib/database/defaultDatabase";
export type QuickConnectionOpenTarget = { kind: "mq-admin" } | { kind: "nacos-admin" } | { kind: "query"; database: string };
export function quickConnectionOpenTarget(connection: Pick<ConnectionConfig, "db_type" | "database">, databaseOptions: string[] = []): QuickConnectionOpenTarget {
if (connection.db_type === "mq") {
return { kind: "mq-admin" };
}
if (connection.db_type === "nacos") {
return { kind: "nacos-admin" };
}
return { kind: "query", database: resolveDefaultDatabase(connection, databaseOptions) };
}
@@ -0,0 +1,177 @@
import type { ConnectionConfig, DatabaseType } from "@/types/database";
type ConnectionPresentationConfig = Pick<ConnectionConfig, "db_type" | "driver_profile" | "driver_label" | "host" | "port" | "database">;
type ConnectionNamePresentationConfig = ConnectionPresentationConfig & Pick<ConnectionConfig, "name">;
const LOCAL_DATABASE_TYPES = new Set(["sqlite", "duckdb", "access"]);
const REDACTED_HOST_SEGMENT = "***";
const REDACTED_PORT = "****";
export function connectionIconType(connection?: Pick<ConnectionConfig, "db_type" | "driver_profile">): string {
return connection?.driver_profile || connection?.db_type || "postgres";
}
export function connectionDriverLabel(connection?: Pick<ConnectionConfig, "db_type" | "driver_label">): string {
return connection?.driver_label || connection?.db_type.toUpperCase() || "";
}
export function connectionEndpointLabel(connection?: ConnectionPresentationConfig): string {
if (!connection) return "";
if (LOCAL_DATABASE_TYPES.has(connection.db_type) || (connection.db_type === "h2" && connection.port === 0)) {
return connection.host || connection.database || "local";
}
if (connection.host && connection.port) return `${connection.host}:${connection.port}`;
return connection.host || connection.database || "";
}
function redactConnectionHost(host: string): string {
const normalizedHost = host.trim();
if (!normalizedHost) return "";
const unwrappedHost = normalizedHost.startsWith("[") && normalizedHost.endsWith("]") ? normalizedHost.slice(1, -1) : normalizedHost;
const separator = unwrappedHost.includes(":") ? ":" : ".";
const segments = unwrappedHost.split(separator).filter(Boolean);
if (segments.length >= 3) {
return [segments[0], ...segments.slice(1, -1).map(() => REDACTED_HOST_SEGMENT), segments[segments.length - 1]].join(separator);
}
if (segments.length === 2) {
return [segments[0], REDACTED_HOST_SEGMENT].join(separator);
}
return REDACTED_HOST_SEGMENT;
}
export function connectionRedactedEndpointLabel(connection?: ConnectionPresentationConfig): string {
if (!connection) return "";
if (LOCAL_DATABASE_TYPES.has(connection.db_type) || (connection.db_type === "h2" && connection.port === 0)) {
return connectionEndpointLabel(connection);
}
const redactedHost = connection.host ? redactConnectionHost(connection.host) : "";
if (redactedHost && connection.port) {
const endpointHost = redactedHost.includes(":") ? `[${redactedHost}]` : redactedHost;
return `${endpointHost}:${REDACTED_PORT}`;
}
return redactedHost || connection.database || "";
}
export function connectionRedactedNameLabel(connection?: ConnectionNamePresentationConfig): string {
const name = connection?.name.trim() || "";
if (!connection || !name || LOCAL_DATABASE_TYPES.has(connection.db_type) || (connection.db_type === "h2" && connection.port === 0)) return name;
const host = connection.host.trim();
if (!host) return name;
const unwrappedHost = host.startsWith("[") && host.endsWith("]") ? host.slice(1, -1) : host;
const hostNames = new Set([host, unwrappedHost]);
if (connection.port) {
hostNames.add(`${host}:${connection.port}`);
if (unwrappedHost.includes(":")) {
hostNames.add(`[${unwrappedHost}]:${connection.port}`);
}
}
return hostNames.has(name) ? connectionRedactedEndpointLabel(connection) : name;
}
export function connectionUrlPlaceholder(dbType: DatabaseType): string {
switch (dbType) {
case "mysql":
case "doris":
case "starrocks":
case "manticoresearch":
return "mysql://user:password@host:port/database";
case "postgres":
case "gaussdb":
case "kwdb":
case "yashandb":
case "redshift":
case "questdb":
return "postgresql://user:password@host:port/database";
case "redis":
return "redis://:password@host:port/0";
case "etcd":
return "etcd://host:2379";
case "zookeeper":
return "zookeeper://host:2181";
case "sqlite":
return "sqlite:///absolute/path/to/database.db";
case "rqlite":
return "http://user:password@host:4001";
case "turso":
return "https://[your-db]-[org].turso.io";
case "duckdb":
return "duckdb:///absolute/path/to/database.duckdb";
case "access":
return "jdbc:ucanaccess:///absolute/path/to/database.accdb";
case "mongodb":
return "mongodb://user:password@host:port/database";
case "clickhouse":
return "clickhouse://user:password@host:port/database";
case "sqlserver":
return "mssql://user:password@host:port/database";
case "oracle":
return "oracle://user:password@host:port/service_name";
case "elasticsearch":
case "qdrant":
case "milvus":
case "weaviate":
case "chromadb":
return "http://user:password@host:port";
case "dameng":
return "dm://user:password@host:port";
case "tdengine":
return "tdengine://user:password@host:6041/database";
case "oscar":
return "oscar://user:password@host:2003/database";
case "xugu":
return "xugu://user:password@host:5138/database";
case "iotdb":
return "iotdb://user:password@host:6667/root.test";
case "bigquery":
return "bigquery://https://www.googleapis.com/bigquery/v2:443/project-id";
case "iris":
return "iris://user:password@host:port/namespace";
case "influxdb":
return "influxdb://user:password@host:port/database";
case "jdbc":
return "jdbc:mysql://host:3306/database";
default:
return "postgresql://user:password@host:port/database";
}
}
export function connectionOptionSubtitle(connection?: ConnectionPresentationConfig): string {
return [connectionDriverLabel(connection), connectionEndpointLabel(connection)].filter(Boolean).join(" · ");
}
export function connectionRedactedOptionSubtitle(connection?: ConnectionPresentationConfig): string {
return [connectionDriverLabel(connection), connectionRedactedEndpointLabel(connection)].filter(Boolean).join(" · ");
}
@@ -0,0 +1,618 @@
import type { ConnectionConfig, DatabaseType } from "@/types/database";
import { h2JdbcUrlHasPasswordParam, h2JdbcUrlHasUserParam, parseH2JdbcUrl } from "@/lib/database/h2Connection";
export interface ParsedConnectionUrl {
name?: string;
dbType: DatabaseType;
driverProfile: string;
driverLabel: string;
host: string;
port: number;
username: string;
password: string;
database?: string;
urlParams: string;
ssl: boolean;
connectionString?: string;
oracleConnectionType?: "service_name" | "sid";
useMongoUrl?: boolean;
}
export type ConnectionProfile = {
type: DatabaseType;
profile: string;
label: string;
defaultPort: number;
};
const SCHEME_PROFILES: Record<string, ConnectionProfile> = {
mysql: { type: "mysql", profile: "mysql", label: "MySQL", defaultPort: 3306 },
mariadb: { type: "mysql", profile: "mariadb", label: "MariaDB", defaultPort: 3306 },
postgres: { type: "postgres", profile: "postgres", label: "PostgreSQL", defaultPort: 5432 },
postgresql: { type: "postgres", profile: "postgres", label: "PostgreSQL", defaultPort: 5432 },
redshift: { type: "redshift", profile: "redshift", label: "Redshift", defaultPort: 5439 },
redis: { type: "redis", profile: "redis", label: "Redis", defaultPort: 6379 },
rediss: { type: "redis", profile: "redis", label: "Redis", defaultPort: 6379 },
etcd: { type: "etcd", profile: "etcd", label: "etcd", defaultPort: 2379 },
zookeeper: { type: "zookeeper", profile: "zookeeper", label: "Apache ZooKeeper", defaultPort: 2181 },
mongodb: { type: "mongodb", profile: "mongodb", label: "MongoDB", defaultPort: 27017 },
"mongodb+srv": { type: "mongodb", profile: "mongodb", label: "MongoDB", defaultPort: 27017 },
clickhouse: { type: "clickhouse", profile: "clickhouse", label: "ClickHouse", defaultPort: 8123 },
sqlserver: { type: "sqlserver", profile: "sqlserver", label: "SQL Server", defaultPort: 1433 },
mssql: { type: "sqlserver", profile: "sqlserver", label: "SQL Server", defaultPort: 1433 },
oracle: { type: "oracle", profile: "oracle", label: "Oracle", defaultPort: 1521 },
elasticsearch: { type: "elasticsearch", profile: "elasticsearch", label: "Elasticsearch", defaultPort: 9200 },
qdrant: { type: "qdrant", profile: "qdrant", label: "Qdrant", defaultPort: 6333 },
milvus: { type: "milvus", profile: "milvus", label: "Milvus", defaultPort: 19530 },
weaviate: { type: "weaviate", profile: "weaviate", label: "Weaviate", defaultPort: 8080 },
chromadb: { type: "chromadb", profile: "chromadb", label: "ChromaDB", defaultPort: 8000 },
dm: { type: "dameng", profile: "dm", label: "DM (Dameng)", defaultPort: 5236 },
dameng: { type: "dameng", profile: "dm", label: "DM (Dameng)", defaultPort: 5236 },
gaussdb: { type: "gaussdb", profile: "gaussdb", label: "GaussDB", defaultPort: 5432 },
kwdb: { type: "kwdb", profile: "kwdb", label: "KWDB", defaultPort: 26257 },
gbase: { type: "gbase", profile: "gbase", label: "GBase", defaultPort: 5258 },
"gbasedbt-sqli": { type: "gbase", profile: "gbase8s", label: "GBase 8s", defaultPort: 9088 },
"informix-sqli": { type: "informix", profile: "informix", label: "Informix", defaultPort: 9088 },
yashandb: { type: "yashandb", profile: "yashandb", label: "YashanDB", defaultPort: 1688 },
opengauss: { type: "gaussdb", profile: "opengauss", label: "openGauss", defaultPort: 5432 },
questdb: { type: "questdb", profile: "questdb", label: "QuestDB", defaultPort: 8812 },
tdengine: { type: "tdengine", profile: "tdengine", label: "TDengine", defaultPort: 6041 },
"taos-ws": { type: "tdengine", profile: "tdengine", label: "TDengine", defaultPort: 6041 },
oscar: { type: "oscar", profile: "oscar", label: "神通 OSCAR", defaultPort: 2003 },
xugu: { type: "xugu", profile: "xugu", label: "XuguDB", defaultPort: 5138 },
iotdb: { type: "iotdb", profile: "iotdb", label: "Apache IoTDB", defaultPort: 6667 },
iris: { type: "iris", profile: "iris", label: "IRIS", defaultPort: 1972 },
};
const HTTP_SELECTED_PROFILES: Record<string, ConnectionProfile> = {
clickhouse: SCHEME_PROFILES.clickhouse,
elasticsearch: SCHEME_PROFILES.elasticsearch,
qdrant: SCHEME_PROFILES.qdrant,
milvus: SCHEME_PROFILES.milvus,
weaviate: SCHEME_PROFILES.weaviate,
chromadb: SCHEME_PROFILES.chromadb,
};
function decodeUrlPart(value: string): string {
try {
return decodeURIComponent(value);
} catch {
return value;
}
}
function decodePercentEscapes(value: string): string {
return value.replace(/%([0-9a-fA-F]{2})/g, (_, hex: string) => String.fromCharCode(Number.parseInt(hex, 16)));
}
function encodeMongoUserInfoPart(value: string): string {
return encodeURIComponent(decodePercentEscapes(value));
}
export function normalizeMongoConnectionString(value: string): string {
const input = value.trim();
if (!input) return input;
const mongoMatch = input.match(/^(mongodb(?:\+srv)?):\/\/(?:(.+)@)?/i);
if (!mongoMatch) return input;
const userinfo = mongoMatch[2];
if (!userinfo) return input;
const [username, ...passwordParts] = userinfo.split(":");
const password = passwordParts.join(":");
const encodedUsername = encodeMongoUserInfoPart(username);
const encodedPassword = password ? `:${encodeMongoUserInfoPart(password)}` : "";
return input.replace(/^(mongodb(?:\+srv)?:\/\/)(?:(.+)@)?/i, `$1${encodedUsername}${encodedPassword}@`);
}
function parseMongoUrl(source: string): ParsedConnectionUrl | null {
const match = source.match(/^(mongodb(?:\+srv)?):\/\/(?:(.+)@)?([^/]+)(\/[^?]*)?(\?.*)?$/);
if (!match) return null;
const scheme = match[1].toLowerCase();
const userinfo = match[2] || "";
const hosts = match[3] || "";
const pathname = match[4] || "";
const search = match[5] || "";
const profile = SCHEME_PROFILES[scheme];
if (!profile) return null;
const [username, ...passwordParts] = decodeUrlPart(userinfo).split(":");
const password = passwordParts.join(":");
const firstHost = hosts.split(",")[0];
let host: string;
let port: number;
if (firstHost.startsWith("[")) {
const bracketEnd = firstHost.indexOf("]");
host = firstHost.substring(1, bracketEnd);
port = firstHost.substring(bracketEnd + 1).startsWith(":") ? Number(firstHost.substring(bracketEnd + 2)) || profile.defaultPort : profile.defaultPort;
} else if (firstHost.includes(":")) {
const colonIdx = firstHost.lastIndexOf(":");
host = firstHost.substring(0, colonIdx);
port = Number(firstHost.substring(colonIdx + 1)) || profile.defaultPort;
} else {
host = firstHost;
port = profile.defaultPort;
}
const database = databaseFromPath(pathname);
const urlParams = search.replace(/^\?/, "");
return {
dbType: profile.type,
driverProfile: profile.profile,
driverLabel: profile.label,
host,
port,
username,
password,
database,
urlParams,
ssl: scheme === "mongodb+srv",
connectionString: normalizeMongoConnectionString(source),
useMongoUrl: true,
};
}
function databaseFromPath(pathname: string): string | undefined {
const value = pathname.replace(/^\/+/, "");
if (!value) return undefined;
return decodeUrlPart(value.split("/")[0]);
}
function queryParamValue(params: string, key: string): string | undefined {
for (const part of params.split(/[&;]/)) {
if (!part) continue;
const [rawKey, ...rest] = part.split("=");
if (decodeUrlPart(rawKey).toLowerCase() === key.toLowerCase()) {
return decodeUrlPart(rest.join("=")).trim();
}
}
return undefined;
}
function connectionNameParam(parsed: URL): string | undefined {
for (const [key, value] of parsed.searchParams) {
if (key.toLowerCase() === "name") {
const name = value.trim();
if (name) return name;
}
}
return undefined;
}
function stripConnectionNameParam(params: string): string {
if (!params) return params;
return params
.split("&")
.filter((part) => {
if (!part) return true;
const [rawKey] = part.split("=");
return decodeUrlPart(rawKey).trim().toLowerCase() !== "name";
})
.join("&");
}
function extractMysqlCredentialParams(params: string): { username?: string; password?: string; urlParams: string } {
let username: string | undefined;
let password: string | undefined;
let foundCredentialParam = false;
const urlParams: string[] = [];
for (const part of params.split(/[&;]/)) {
if (!part) continue;
const [rawKey, ...rest] = part.split("=");
const key = decodeUrlPart(rawKey).trim().toLowerCase();
if (key === "user") {
username = decodeUrlPart(rest.join("=")).trim();
foundCredentialParam = true;
} else if (key === "password") {
password = decodeUrlPart(rest.join("=")).trim();
foundCredentialParam = true;
} else {
urlParams.push(part);
}
}
return { username, password, urlParams: foundCredentialParam ? urlParams.join("&") : params };
}
function urlParamsRequireTls(dbType: DatabaseType, params: string): boolean {
if (dbType === "mysql") {
const requireSsl = queryParamValue(params, "require_ssl")?.toLowerCase();
if (requireSsl === "true" || requireSsl === "1" || requireSsl === "yes") return true;
const sslMode = (queryParamValue(params, "ssl-mode") || queryParamValue(params, "sslmode") || "").toLowerCase().replace("-", "_");
return sslMode === "required" || sslMode === "require" || sslMode === "verify_ca" || sslMode === "verify_identity";
}
if (dbType === "postgres" || dbType === "redshift" || dbType === "kwdb") {
const sslMode = (queryParamValue(params, "sslmode") || "").toLowerCase();
return sslMode === "require" || sslMode === "verify-ca" || sslMode === "verify-full";
}
return false;
}
function isTidbCloudHost(host: string): boolean {
return host.toLowerCase().endsWith(".tidbcloud.com");
}
export function connectionProfileForScheme(scheme: string, preferredProfile?: string): ConnectionProfile | undefined {
if ((scheme === "http" || scheme === "https") && preferredProfile) {
return HTTP_SELECTED_PROFILES[preferredProfile];
}
return SCHEME_PROFILES[scheme];
}
function parseJdbcSqlServerUrl(source: string): ParsedConnectionUrl | null {
const match = source.match(/^jdbc:sqlserver:\/\/([^;:/]+)(?::(\d+))?(?:;(.*))?$/i);
if (!match) return null;
const profile = SCHEME_PROFILES.sqlserver;
const props = new Map<string, string>();
const urlParams: string[] = [];
for (const part of (match[3] || "").split(";")) {
if (!part) continue;
const [rawKey, ...rest] = part.split("=");
const key = rawKey.trim();
const value = rest.join("=");
const normalizedKey = key.toLowerCase();
if (normalizedKey === "databasename" || normalizedKey === "database" || normalizedKey === "user") {
props.set(normalizedKey, value);
} else if (normalizedKey === "password") {
props.set(normalizedKey, value);
} else {
urlParams.push(part);
}
}
return {
dbType: profile.type,
driverProfile: profile.profile,
driverLabel: profile.label,
host: match[1],
port: match[2] ? Number(match[2]) : profile.defaultPort,
username: decodeUrlPart(props.get("user") || ""),
password: decodeUrlPart(props.get("password") || ""),
database: decodeUrlPart(props.get("databasename") || props.get("database") || "") || undefined,
urlParams: urlParams.join(";"),
ssl: false,
};
}
function parseJdbcOracleUrl(source: string): ParsedConnectionUrl | null {
const descriptorMatch = source.match(/^jdbc:oracle:thin:@\s*\((.+)\)\s*$/i);
if (descriptorMatch) {
const profile = SCHEME_PROFILES.oracle;
const host = oracleDescriptorValue(source, "HOST");
const port = oracleDescriptorValue(source, "PORT");
const serviceName = oracleDescriptorValue(source, "SERVICE_NAME");
const sid = oracleDescriptorValue(source, "SID");
if (!host) return null;
return {
dbType: profile.type,
driverProfile: profile.profile,
driverLabel: profile.label,
host,
port: port ? Number(port) : profile.defaultPort,
username: "",
password: "",
database: serviceName || sid || undefined,
urlParams: "",
ssl: false,
connectionString: source,
oracleConnectionType: sid && !serviceName ? "sid" : "service_name",
};
}
const serviceMatch = source.match(/^jdbc:oracle:thin:@\/\/([^:/?#]+)(?::(\d+))?\/([^?]+)(?:\?(.*))?$/i);
if (serviceMatch) {
const profile = SCHEME_PROFILES.oracle;
return {
dbType: profile.type,
driverProfile: profile.profile,
driverLabel: profile.label,
host: serviceMatch[1],
port: serviceMatch[2] ? Number(serviceMatch[2]) : profile.defaultPort,
username: "",
password: "",
database: decodeUrlPart(serviceMatch[3]),
urlParams: serviceMatch[4] || "",
ssl: false,
oracleConnectionType: "service_name",
};
}
const sidMatch = source.match(/^jdbc:oracle:thin:@([^:/?#]+)(?::(\d+))?:([^?]+)(?:\?(.*))?$/i);
if (sidMatch) {
const profile = SCHEME_PROFILES.oracle;
return {
dbType: profile.type,
driverProfile: profile.profile,
driverLabel: profile.label,
host: sidMatch[1],
port: sidMatch[2] ? Number(sidMatch[2]) : profile.defaultPort,
username: "",
password: "",
database: decodeUrlPart(sidMatch[3]),
urlParams: sidMatch[4] || "",
ssl: false,
oracleConnectionType: "sid",
};
}
return null;
}
function oracleDescriptorValue(source: string, key: string): string | undefined {
const match = new RegExp(`\\(${key}\\s*=\\s*([^\\)]+)\\)`, "i").exec(source);
return match?.[1]?.trim();
}
function parseJdbcUCanAccessUrl(source: string): ParsedConnectionUrl | null {
const match = source.match(/^jdbc:ucanaccess:\/\/(.+?)(?:;.*)?$/i);
if (!match) return null;
const filePath = decodeUrlPart(match[1]);
const normalizedPath = filePath.startsWith("/") || /^[A-Za-z]:[\\/]/.test(filePath) ? filePath : `/${filePath}`;
const database = normalizedPath.split(/[\\/]/).filter(Boolean).pop();
return {
dbType: "access",
driverProfile: "access",
driverLabel: "Microsoft Access",
host: normalizedPath,
port: 0,
username: "",
password: "",
database,
urlParams: "",
ssl: false,
connectionString: source,
};
}
function parseJdbcGbase8sUrl(source: string): ParsedConnectionUrl | null {
const match = /^jdbc:gbasedbt-sqli:\/\/(?:(?<userinfo>[^@/?#]*)@)?(?<host>\[[^\]]+\]|[^:/?#]+)(?::(?<port>\d+))?\/(?<database>[^:?#]*)(?::(?<params>[^?#]*))?/i.exec(source);
if (!match?.groups) return null;
const rawUserInfo = match.groups.userinfo || "";
const [rawUser = "", ...passwordParts] = rawUserInfo.split(":");
const host = match.groups.host.replace(/^\[/, "").replace(/\]$/, "");
return {
dbType: "gbase",
driverProfile: "gbase8s",
driverLabel: "GBase 8s",
host,
port: match.groups.port ? Number(match.groups.port) : 9088,
username: decodeUrlPart(rawUser),
password: decodeUrlPart(passwordParts.join(":")),
database: decodeUrlPart(match.groups.database || ""),
urlParams: match.groups.params || "",
ssl: false,
};
}
function parseJdbcInformixUrl(source: string): ParsedConnectionUrl | null {
const match = /^jdbc:informix-sqli:\/\/(?:(?<userinfo>[^@/?#]*)@)?(?<host>\[[^\]]+\]|[^:/?#]+)(?::(?<port>\d+))?\/(?<database>[^:?#]*)(?::(?<params>[^?#]*))?/i.exec(source);
if (!match?.groups) return null;
const rawUserInfo = match.groups.userinfo || "";
const [rawUser = "", ...passwordParts] = rawUserInfo.split(":");
const host = match.groups.host.replace(/^\[/, "").replace(/\]$/, "");
return {
dbType: "informix",
driverProfile: "informix",
driverLabel: "Informix",
host,
port: match.groups.port ? Number(match.groups.port) : 9088,
username: decodeUrlPart(rawUser),
password: decodeUrlPart(passwordParts.join(":")),
database: decodeUrlPart(match.groups.database || ""),
urlParams: match.groups.params || "",
ssl: false,
};
}
function parseJdbcDremioUrl(source: string): ParsedConnectionUrl | null {
const match = /^jdbc:dremio:(?<mode>direct|zk)=(?<host>\[[^\]]+\]|[^:;]+)(?::(?<port>\d+))?(?:;(?<params>.*))?$/i.exec(source);
if (!match?.groups) return null;
const props = new Map<string, string>();
const urlParams: string[] = [];
for (const part of (match.groups.params || "").split(";")) {
if (!part) continue;
const [rawKey, ...rest] = part.split("=");
const key = rawKey.trim();
const value = rest.join("=");
const normalizedKey = key.toLowerCase();
if (normalizedKey === "schema" || normalizedKey === "user" || normalizedKey === "password") {
props.set(normalizedKey, value);
} else {
urlParams.push(part);
}
}
return {
dbType: "jdbc",
driverProfile: "dremio",
driverLabel: "Dremio",
host: match.groups.host.replace(/^\[/, "").replace(/\]$/, ""),
port: match.groups.port ? Number(match.groups.port) : match.groups.mode.toLowerCase() === "zk" ? 2181 : 31010,
username: decodeUrlPart(props.get("user") || ""),
password: decodeUrlPart(props.get("password") || ""),
database: decodeUrlPart(props.get("schema") || "") || undefined,
urlParams: urlParams.join(";"),
ssl: false,
connectionString: source,
};
}
function parseJdbcDremioArrowFlightSqlUrl(source: string): ParsedConnectionUrl | null {
if (!/^jdbc:arrow-flight-sql:\/\//i.test(source)) return null;
let parsed: URL;
try {
parsed = new URL(source.replace(/^jdbc:/i, ""));
} catch {
return null;
}
const urlParams = parsed.search.replace(/^\?/, "");
return {
dbType: "jdbc",
driverProfile: "dremio",
driverLabel: "Dremio",
host: parsed.hostname.replace(/^\[(.*)]$/, "$1"),
port: parsed.port ? Number(parsed.port) : 32010,
username: decodeUrlPart(parsed.username),
password: decodeUrlPart(parsed.password),
database: queryParamValue(urlParams, "schema") || undefined,
urlParams,
ssl: queryParamValue(urlParams, "useEncryption")?.toLowerCase() !== "false",
connectionString: source,
};
}
export function parseConnectionUrl(value: string, preferredProfile?: string): ParsedConnectionUrl {
const input = value.trim();
if (!input) {
throw new Error("Connection URL is empty");
}
const jdbcH2 = parseH2JdbcUrl(input);
if (jdbcH2) return jdbcH2;
const jdbcUCanAccess = parseJdbcUCanAccessUrl(input);
if (jdbcUCanAccess) return jdbcUCanAccess;
const jdbcGbase8s = parseJdbcGbase8sUrl(input);
if (jdbcGbase8s) return jdbcGbase8s;
const jdbcInformix = parseJdbcInformixUrl(input);
if (jdbcInformix) return jdbcInformix;
const jdbcDremioArrowFlightSql = parseJdbcDremioArrowFlightSqlUrl(input);
if (jdbcDremioArrowFlightSql) return jdbcDremioArrowFlightSql;
const jdbcDremio = parseJdbcDremioUrl(input);
if (jdbcDremio) return jdbcDremio;
const jdbcOracle = parseJdbcOracleUrl(input);
if (jdbcOracle) return jdbcOracle;
const jdbcSqlServer = parseJdbcSqlServerUrl(input);
if (jdbcSqlServer) return jdbcSqlServer;
const isJdbcUrl = /^jdbc:/i.test(input);
const source = isJdbcUrl ? input.replace(/^jdbc:/i, "") : input;
const mongoResult = parseMongoUrl(source);
if (mongoResult) return mongoResult;
let parsed: URL;
try {
parsed = new URL(source);
} catch {
throw new Error("Invalid connection URL");
}
const scheme = parsed.protocol.replace(/:$/, "").toLowerCase();
const profile = connectionProfileForScheme(scheme, preferredProfile);
if (!profile) {
throw new Error(`Unsupported connection URL scheme: ${scheme}`);
}
const urlParams = parsed.search.replace(/^\?/, "");
const name = connectionNameParam(parsed);
const urlParamsWithoutName = stripConnectionNameParam(urlParams);
const normalizedFragment = decodeUrlPart(parsed.hash.replace(/^#/, "")).trim().toLowerCase();
const parsedUrlParams = profile.type === "redis" && normalizedFragment === "insecure" ? [urlParamsWithoutName, "insecure=true"].filter(Boolean).join("&") : urlParamsWithoutName;
const mysqlCredentials = isJdbcUrl && profile.type === "mysql" ? extractMysqlCredentialParams(parsedUrlParams) : undefined;
const effectiveUrlParams = mysqlCredentials?.urlParams ?? parsedUrlParams;
if (profile.type === "mongodb") {
return {
dbType: profile.type,
driverProfile: profile.profile,
driverLabel: profile.label,
host: parsed.hostname,
port: parsed.port ? Number(parsed.port) : profile.defaultPort,
username: decodeUrlPart(parsed.username),
password: decodeUrlPart(parsed.password),
database: databaseFromPath(parsed.pathname),
urlParams: parsedUrlParams,
ssl: scheme === "mongodb+srv",
connectionString: normalizeMongoConnectionString(source),
useMongoUrl: true,
};
}
if (profile.type === "zookeeper") {
return {
...(name ? { name } : {}),
dbType: profile.type,
driverProfile: profile.profile,
driverLabel: profile.label,
host: parsed.hostname.replace(/^\[(.*)]$/, "$1"),
port: parsed.port ? Number(parsed.port) : profile.defaultPort,
username: decodeUrlPart(parsed.username),
password: decodeUrlPart(parsed.password),
database: undefined,
urlParams: urlParamsWithoutName,
ssl: false,
connectionString: zookeeperConnectStringFromUrl(parsed, profile.defaultPort),
};
}
return {
...(name ? { name } : {}),
dbType: profile.type,
driverProfile: profile.profile,
driverLabel: profile.label,
host: parsed.hostname,
port: parsed.port ? Number(parsed.port) : profile.defaultPort,
username: mysqlCredentials?.username ?? decodeUrlPart(parsed.username),
password: mysqlCredentials?.password ?? decodeUrlPart(parsed.password),
database: databaseFromPath(parsed.pathname),
urlParams: effectiveUrlParams,
ssl: scheme === "rediss" || scheme === "https" || urlParamsRequireTls(profile.type, effectiveUrlParams) || (profile.type === "mysql" && isTidbCloudHost(parsed.hostname)),
};
}
function zookeeperConnectStringFromUrl(parsed: URL, defaultPort: number): string {
const rawHost = parsed.hostname.replace(/^\[(.*)]$/, "$1");
const host = rawHost.includes(":") ? `[${rawHost}]` : rawHost;
const port = parsed.port ? Number(parsed.port) : defaultPort;
const chroot = parsed.pathname && parsed.pathname !== "/" ? parsed.pathname : "";
return `${host}:${port}${chroot}`;
}
function applyParsedUsername(config: Omit<ConnectionConfig, "id">, parsed: ParsedConnectionUrl): string {
if (parsed.dbType === "h2" && config.db_type === "h2" && !h2JdbcUrlHasUserParam(parsed.connectionString)) {
return config.username || parsed.username;
}
return parsed.username;
}
function applyParsedPassword(config: Omit<ConnectionConfig, "id">, parsed: ParsedConnectionUrl): string {
if (parsed.dbType === "h2" && config.db_type === "h2" && !h2JdbcUrlHasPasswordParam(parsed.connectionString)) {
return config.password || parsed.password;
}
return parsed.password;
}
export function applyParsedConnectionUrl(config: Omit<ConnectionConfig, "id">, parsed: ParsedConnectionUrl): Omit<ConnectionConfig, "id"> {
return {
...config,
db_type: parsed.dbType,
driver_profile: parsed.driverProfile,
driver_label: parsed.driverLabel,
host: parsed.host,
port: parsed.port,
name: parsed.name?.trim() || config.name,
username: applyParsedUsername(config, parsed),
password: applyParsedPassword(config, parsed),
database: parsed.database,
url_params: parsed.urlParams,
ssl: parsed.ssl,
connection_string: parsed.connectionString,
oracle_connection_type: parsed.oracleConnectionType,
};
}
@@ -0,0 +1,49 @@
import type { ConnectionConfig, DatabaseType } from "@/types/database";
import { filterDatabaseNamesForVisiblePicker, normalizeVisibleDatabaseSelection } from "@/lib/database/visibleDatabases";
const DRAFT_VISIBLE_DATABASES_PREFIX = "__visible_draft_";
const UNSUPPORTED_VISIBLE_DATABASE_TYPES = new Set<DatabaseType>(["elasticsearch", "qdrant", "milvus", "weaviate", "chromadb", "etcd", "zookeeper"]);
type VisibleDatabaseConnectionFields = Pick<
ConnectionConfig,
"db_type" | "driver_profile" | "host" | "port" | "username" | "database" | "connection_string" | "url_params" | "redis_connection_mode" | "redis_sentinel_master" | "redis_sentinel_nodes" | "redis_cluster_nodes" | "etcd_endpoints" | "jdbc_driver_class"
>;
export function buildDraftVisibleDatabasesConnectionId(seed: string): string {
return `${DRAFT_VISIBLE_DATABASES_PREFIX}${seed}`;
}
export function connectionCanChooseVisibleDatabases(connection: Pick<ConnectionConfig, "db_type"> | undefined): boolean {
return !!connection?.db_type && !UNSUPPORTED_VISIBLE_DATABASE_TYPES.has(connection.db_type);
}
export function initialVisibleDatabaseSelection(databaseNames: string[], visibleDatabases: string[] | undefined, connection?: Pick<ConnectionConfig, "db_type" | "driver_profile" | "visible_databases">): string[] {
if (Array.isArray(visibleDatabases)) {
return normalizeVisibleDatabaseSelection(visibleDatabases, databaseNames);
}
return filterDatabaseNamesForVisiblePicker(databaseNames, connection);
}
export function visibleDatabaseSelectionIsStale(previous: VisibleDatabaseConnectionFields, current: VisibleDatabaseConnectionFields): boolean {
return visibleDatabaseFingerprint(previous) !== visibleDatabaseFingerprint(current);
}
function visibleDatabaseFingerprint(connection: VisibleDatabaseConnectionFields): string {
return JSON.stringify({
db_type: connection.db_type,
driver_profile: connection.driver_profile || "",
host: connection.host || "",
port: Number(connection.port) || 0,
username: connection.username || "",
database: connection.database || "",
connection_string: connection.connection_string || "",
url_params: connection.url_params || "",
redis_connection_mode: connection.redis_connection_mode || "",
redis_sentinel_master: connection.redis_sentinel_master || "",
redis_sentinel_nodes: connection.redis_sentinel_nodes || "",
redis_cluster_nodes: connection.redis_cluster_nodes || "",
etcd_endpoints: connection.etcd_endpoints || "",
jdbc_driver_class: connection.jdbc_driver_class || "",
});
}
@@ -0,0 +1,43 @@
export interface DriverInstallProgress {
step: string;
downloaded?: number;
total?: number;
db_type?: string;
}
export interface DriverInstallProgressTargetState {
installing: string | null;
upgradingAll: boolean;
progress: DriverInstallProgress | null;
}
export function driverInstallProgressPercent(progress: DriverInstallProgress | null): number | null {
if (!progress?.total || progress.total <= 0) return null;
const percent = Math.round(((progress.downloaded ?? 0) / progress.total) * 100);
return Math.min(100, Math.max(0, percent));
}
export function isDriverInstallProgressTarget(dbType: string, state: DriverInstallProgressTargetState): boolean {
if (state.installing === dbType) return true;
return state.upgradingAll && state.progress?.db_type === dbType;
}
export function addDriverInstallQueue(queue: string[], dbType: string, activeDbType: string | null): string[] {
if (activeDbType === dbType || queue.includes(dbType)) return queue;
return [...queue, dbType];
}
export function removeDriverInstallQueue(queue: string[], dbType: string): string[] {
return queue.filter((queuedDbType) => queuedDbType !== dbType);
}
export function takeNextDriverInstallQueue(queue: string[], isInstallable: (dbType: string) => boolean): { next: string | null; queue: string[] } {
const remaining = [...queue];
while (remaining.length > 0) {
const next = remaining.shift() ?? null;
if (next && isInstallable(next)) {
return { next, queue: remaining };
}
}
return { next: null, queue: [] };
}
@@ -0,0 +1,59 @@
import type { DriverRuntimeHealth, DriverRuntimeStatus } from "@/lib/backend/api";
export function formatRuntimeBytes(bytes: number | null | undefined): string {
if (!bytes) return "-";
if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(0)} KB`;
return `${(bytes / 1024 / 1024).toFixed(1)} MB`;
}
export function formatRuntimeCpu(value: number | null | undefined): string {
if (value === null || value === undefined || Number.isNaN(value)) return "-";
return `${Math.max(0, value).toFixed(1)}%`;
}
export function formatRuntimeUptime(seconds: number | null | undefined): string {
if (!seconds) return "-";
if (seconds < 60) return `${seconds}s`;
const minutes = Math.floor(seconds / 60);
if (minutes < 60) return `${minutes}m`;
const hours = Math.floor(minutes / 60);
const remMinutes = minutes % 60;
return remMinutes > 0 ? `${hours}h ${remMinutes}m` : `${hours}h`;
}
export function runtimeStatusClass(status: DriverRuntimeStatus): string {
switch (status) {
case "running":
return "bg-emerald-500/10 text-emerald-700 dark:text-emerald-400";
case "error":
return "bg-destructive/10 text-destructive";
case "unknown":
return "bg-amber-500/10 text-amber-700 dark:text-amber-400";
default:
return "bg-muted text-muted-foreground";
}
}
export function runtimeStatusDotClass(status: DriverRuntimeStatus): string {
switch (status) {
case "running":
return "bg-emerald-500";
case "error":
return "bg-destructive";
case "unknown":
return "bg-amber-500";
default:
return "bg-muted-foreground/40";
}
}
export function runtimeHealthClass(health: DriverRuntimeHealth): string {
switch (health) {
case "error":
return "text-destructive";
case "warning":
return "text-amber-700 dark:text-amber-400";
default:
return "text-green-700 dark:text-green-400";
}
}