Skip to content

armgit / dbx

Public Imported from GitHub
0

25 MB lightweight cross-platform database client for 100+ databases, including MySQL, PostgreSQL, SQLite, Redis, MongoDB, DuckDB, SQL Server, and Dameng. Built-in AI, MCP Server, CLI, desktop and Docker. | 轻量级跨平台数据库管理工具,支持 MySQL、PostgreSQL、SQLite、Redis、MongoDB、达梦等 100+ 数据库,提供桌面端、Docker、CLI、内置 AI 助手和 MCP。

fix(influxdb): support InfluxDB 2 connections

t8y25db35307d3f5
diff --git a/apps/desktop/src/components/connection/ConnectionDialog.vue b/apps/desktop/src/components/connection/ConnectionDialog.vue
index c857972fbd..780877939f 100644
--- a/apps/desktop/src/components/connection/ConnectionDialog.vue
+++ b/apps/desktop/src/components/connection/ConnectionDialog.vue
@@ -14,6 +14,7 @@ import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
import { Switch } from "@/components/ui/switch";
import type { ConnectionConfig, DatabaseType, HttpTunnelConfig, JdbcDriverInfo, JdbcMavenBundleInfo, ProxyTunnelConfig, SshConfigHostEntry, SshTunnelConfig, TransportLayerConfig } from "@/types/database";
+import type { InfluxDbExternalConfig, InfluxDbVersion } from "@/types/influxdb";
import type { MqAdminConfig, MqAuth, MqSystemKind } from "@/types/mq";
import type { NacosAdminConfig, NacosAuthConfig } from "@/types/nacos";
import { CONNECTION_ATTEMPT_CANCELLED_MESSAGE, useConnectionStore } from "@/stores/connectionStore";
@@ -756,6 +757,38 @@ function hydrateNacosFields(value: unknown) {
resetNacosFields(value as Partial<NacosAdminConfig>);
}
+const influxDbVersion = ref<InfluxDbVersion>("1");
+const influxDbOrg = ref("");
+
+function resetInfluxDbFields(config?: Partial<InfluxDbExternalConfig>) {
+ influxDbVersion.value = config?.version === "2" ? "2" : "1";
+ influxDbOrg.value = config?.org?.trim() || "";
+}
+
+function hydrateInfluxDbFields(value: unknown) {
+ if (!value || typeof value !== "object") {
+ resetInfluxDbFields();
+ return;
+ }
+ resetInfluxDbFields(value as Partial<InfluxDbExternalConfig>);
+}
+
+function buildInfluxDbExternalConfig(): InfluxDbExternalConfig {
+ if (influxDbVersion.value !== "2") return { version: "1" };
+ const org = influxDbOrg.value.trim();
+ if (!org) throw new Error("InfluxDB 2.x organization is required");
+ if (!form.value.password.trim()) throw new Error("InfluxDB 2.x token is required");
+ if (!form.value.database?.trim()) throw new Error("InfluxDB 2.x bucket is required");
+ return { version: "2", org };
+}
+
+watch(influxDbVersion, (version) => {
+ if (form.value.db_type !== "influxdb") return;
+ if (version === "2") {
+ form.value.username = "";
+ }
+});
+
function requireMqField(value: string, message: string): string {
const trimmed = value.trim();
if (!trimmed) throw new Error(message);
@@ -1235,6 +1268,12 @@ function applyProfile(val: string, preserveConnectionFields = false) {
form.value.connection_string = undefined;
form.value.url_params = "";
}
+ if (profile.type === "influxdb") {
+ resetInfluxDbFields();
+ form.value.database = undefined;
+ form.value.password = "";
+ form.value.connection_string = undefined;
+ }
}
}
@@ -1302,6 +1341,7 @@ watch(
redis_scan_page_size: config.redis_scan_page_size ?? REDIS_SCAN_PAGE_SIZE_DEFAULT,
etcd_endpoints: config.etcd_endpoints || "",
informix_server: config.informix_server || "",
+ external_config: config.external_config,
read_only: config.read_only || false,
visible_databases: config.visible_databases,
};
@@ -1317,6 +1357,11 @@ watch(
} else {
resetNacosFields();
}
+ if (config.db_type === "influxdb") {
+ hydrateInfluxDbFields(config.external_config);
+ } else {
+ resetInfluxDbFields();
+ }
h2ConnectionMode.value = h2ConnectionModeForConfig(config);
customColorInput.value = config.color || "";
selectedTransportLayerId.value = form.value.transport_layers?.[0]?.id || null;
@@ -1343,6 +1388,7 @@ watch(
customDriverName.value = "";
resetMqFields();
resetNacosFields();
+ resetInfluxDbFields();
oceanbaseSubMode.value = "mysql";
h2ConnectionMode.value = "file";
dremioConnectionMode.value = "legacy";
@@ -1363,7 +1409,11 @@ watch(
},
);
-const databaseLabel = computed(() => (form.value.db_type === "oracle" ? t("connection.serviceName") : t("connection.database")));
+const databaseLabel = computed(() => {
+ if (form.value.db_type === "oracle") return t("connection.serviceName");
+ if (form.value.db_type === "influxdb" && influxDbVersion.value === "2") return "Bucket";
+ return t("connection.database");
+});
const databasePlaceholder = computed(() => {
const fallback = defaultDatabaseForProfile();
@@ -2110,6 +2160,14 @@ function connectionConfigForSubmit(id: string): ConnectionConfig {
config.database = nacosConfig.namespace || undefined;
config.connection_string = undefined;
config.url_params = "";
+ } else if (config.db_type === "influxdb") {
+ config.external_config = buildInfluxDbExternalConfig();
+ config.connection_string = undefined;
+ if (influxDbVersion.value === "2") {
+ config.username = "";
+ config.password = config.password.trim();
+ config.database = config.database?.trim() || undefined;
+ }
} else {
config.external_config = undefined;
}
@@ -4201,6 +4259,66 @@ function openExternalUrl(url: string) {
</template>
</template>
+ <!-- InfluxDB: v1 username/password or v2 token/org/bucket -->
+ <template v-else-if="form.db_type === 'influxdb'">
+ <div class="grid grid-cols-4 items-center gap-4">
+ <Label :class="connectionLabelSmallClass">{{ t("connection.version") }}</Label>
+ <Select v-model="influxDbVersion">
+ <SelectTrigger class="col-span-3">
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ <SelectItem value="1">InfluxDB 1.x</SelectItem>
+ <SelectItem value="2">InfluxDB 2.x</SelectItem>
+ </SelectContent>
+ </Select>
+ </div>
+ <div class="grid grid-cols-4 items-center gap-4">
+ <Label :class="connectionLabelClass">{{ t("connection.host") }}</Label>
+ <Input v-model="form.host" class="col-span-2" />
+ <Input v-model.number="form.port" type="number" class="col-span-1" />
+ </div>
+ <div class="grid grid-cols-4 items-center gap-4">
+ <span />
+ <label class="col-span-3 flex items-center gap-2 text-sm">
+ <input type="checkbox" v-model="form.ssl" class="mr-0" />
+ <span>{{ t("connection.sslEnable") }}</span>
+ </label>
+ </div>
+ <template v-if="influxDbVersion === '2'">
+ <div class="grid grid-cols-4 items-center gap-4">
+ <Label :class="connectionLabelClass">Organization</Label>
+ <Input v-model="influxDbOrg" class="col-span-3" placeholder="my-org" />
+ </div>
+ <div class="grid grid-cols-4 items-center gap-4">
+ <Label :class="connectionLabelClass">Bucket</Label>
+ <Input v-model="form.database" class="col-span-3" placeholder="my-bucket" />
+ </div>
+ <div class="grid grid-cols-4 items-center gap-4">
+ <Label :class="connectionLabelClass">Token</Label>
+ <PasswordInput v-model="form.password" class="col-span-3" />
+ </div>
+ </template>
+ <template v-else>
+ <div class="grid grid-cols-4 items-center gap-4">
+ <Label :class="connectionLabelClass">{{ t("connection.user") }}</Label>
+ <Input v-model="form.username" class="col-span-3" />
+ </div>
+ <div class="grid grid-cols-4 items-center gap-4">
+ <Label :class="connectionLabelClass">{{ t("connection.password") }}</Label>
+ <PasswordInput v-model="form.password" class="col-span-3" />
+ </div>
+ <div class="grid grid-cols-4 items-center gap-4">
+ <Label :class="connectionLabelClass">{{ t("connection.database") }}</Label>
+ <Input v-model="form.database" class="col-span-3" :placeholder="t('connection.databasePlaceholder')" />
+ </div>
+ </template>
+ <div class="grid grid-cols-4 items-center gap-4">
+ <Label :class="connectionLabelClass">{{ t("connection.urlParams") }}</Label>
+ <Input v-model="form.url_params" class="col-span-3" :placeholder="influxDbVersion === '2' ? 'precision=ns' : 'epoch=ms'" />
+ </div>
+ </template>
+
<!-- Turso: simplified form (URL + Token) -->
<template v-else-if="form.db_type === 'turso'">
<div class="grid grid-cols-4 items-center gap-4">
@@ -4318,9 +4436,7 @@ function openExternalUrl(url: string) {
? 'OAuthType=0;[email protected];OAuthPvtKeyPath=/path/key.json'
: form.db_type === 'informix'
? 'CLIENT_LOCALE=en_US.utf8;DB_LOCALE=en_US.utf8'
- : form.db_type === 'influxdb'
- ? 'epoch=ms'
- : 'sslmode=disable'
+ : 'sslmode=disable'
"
/>
</div>
diff --git a/apps/desktop/src/types/influxdb.ts b/apps/desktop/src/types/influxdb.ts
new file mode 100644
index 0000000000..187580d4a6
--- /dev/null
+++ b/apps/desktop/src/types/influxdb.ts
@@ -0,0 +1,6 @@
+export type InfluxDbVersion = "1" | "2";
+
+export interface InfluxDbExternalConfig {
+ version?: InfluxDbVersion;
+ org?: string;
+}
diff --git a/crates/dbx-core/src/connection.rs b/crates/dbx-core/src/connection.rs
index 2268220e89..d9fb76e580 100644
--- a/crates/dbx-core/src/connection.rs
+++ b/crates/dbx-core/src/connection.rs
@@ -1164,16 +1164,7 @@ impl AppState {
PoolKind::VectorDb(client)
}
DatabaseType::InfluxDb => {
- let username = if db_config.username.is_empty() { None } else { Some(db_config.username.clone()) };
- let password = if db_config.password.is_empty() { None } else { Some(db_config.password.clone()) };
- let client = db::influxdb_driver::InfluxdbClient::new_with_ca_cert(
- &url,
- username,
- password,
- db_config.url_params.clone(),
- Some(&db_config.ca_cert_path),
- connect_timeout,
- )?;
+ let client = db::influxdb_driver::InfluxdbClient::new_for_config(&url, &db_config, connect_timeout)?;
db::influxdb_driver::test_connection(&client, connect_timeout).await?;
PoolKind::InfluxDb(client)
}
diff --git a/crates/dbx-core/src/db/influxdb_driver.rs b/crates/dbx-core/src/db/influxdb_driver.rs
index f6db02f473..cf21733e0e 100644
--- a/crates/dbx-core/src/db/influxdb_driver.rs
+++ b/crates/dbx-core/src/db/influxdb_driver.rs
@@ -1,19 +1,28 @@
use percent_encoding::{utf8_percent_encode, NON_ALPHANUMERIC};
use reqwest::{Certificate, Client as HttpClient, Response};
-use serde::Deserialize;
+use serde::{Deserialize, Serialize};
use std::fs;
use std::time::{Duration, Instant};
use super::with_connection_timeout;
+use crate::models::connection::ConnectionConfig;
use crate::sql::starts_with_executable_sql_keyword;
use crate::types::{ColumnInfo, DatabaseInfo, QueryResult, TableInfo};
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+enum InfluxdbApiVersion {
+ V1,
+ V2,
+}
+
pub struct InfluxdbClient {
http: HttpClient,
base_url: String,
username: Option<String>,
password: Option<String>,
url_params: Option<String>,
+ version: InfluxdbApiVersion,
+ org: Option<String>,
}
impl InfluxdbClient {
@@ -25,7 +34,15 @@ impl InfluxdbClient {
timeout: Duration,
) -> Self {
let http = HttpClient::builder().connect_timeout(timeout).build().unwrap_or_else(|_| HttpClient::new());
- Self { http, base_url: url.trim_end_matches('/').to_string(), username, password, url_params }
+ Self {
+ http,
+ base_url: url.trim_end_matches('/').to_string(),
+ username,
+ password,
+ url_params,
+ version: InfluxdbApiVersion::V1,
+ org: None,
+ }
}
pub fn new_with_ca_cert(
@@ -36,19 +53,70 @@ impl InfluxdbClient {
ca_cert_path: Option<&str>,
timeout: Duration,
) -> Result<Self, String> {
- let mut builder = HttpClient::builder().connect_timeout(timeout);
- if let Some(path) = ca_cert_path.map(str::trim).filter(|path| !path.is_empty()) {
- let path = expand_cert_path(path);
- let cert_bytes =
- fs::read(&path).map_err(|e| format!("Failed to read InfluxDB CA certificate at {path}: {e}"))?;
- let cert = Certificate::from_pem(&cert_bytes)
- .or_else(|_| Certificate::from_der(&cert_bytes))
- .map_err(|e| format!("Failed to parse InfluxDB CA certificate at {path}: {e}"))?;
- builder = builder.add_root_certificate(cert);
- }
- let http = builder.build().map_err(|e| format!("Failed to configure InfluxDB HTTP client: {e}"))?;
- Ok(Self { http, base_url: url.trim_end_matches('/').to_string(), username, password, url_params })
+ let http = build_http_client(ca_cert_path, timeout)?;
+ Ok(Self {
+ http,
+ base_url: url.trim_end_matches('/').to_string(),
+ username,
+ password,
+ url_params,
+ version: InfluxdbApiVersion::V1,
+ org: None,
+ })
}
+
+ pub fn new_for_config(url: &str, config: &ConnectionConfig, timeout: Duration) -> Result<Self, String> {
+ let version = influxdb_api_version(config.external_config.as_ref());
+ let org = influxdb_org(config.external_config.as_ref());
+ // InfluxDB 2.x authenticates with a token and scopes requests by org/bucket.
+ let (username, password) = match version {
+ InfluxdbApiVersion::V1 => (
+ (!config.username.is_empty()).then_some(config.username.clone()),
+ (!config.password.is_empty()).then_some(config.password.clone()),
+ ),
+ InfluxdbApiVersion::V2 => (None, (!config.password.is_empty()).then_some(config.password.clone())),
+ };
+ let http = build_http_client(Some(&config.ca_cert_path), timeout)?;
+ Ok(Self {
+ http,
+ base_url: url.trim_end_matches('/').to_string(),
+ username,
+ password,
+ url_params: config.url_params.clone(),
+ version,
+ org,
+ })
+ }
+}
+
+fn build_http_client(ca_cert_path: Option<&str>, timeout: Duration) -> Result<HttpClient, String> {
+ let mut builder = HttpClient::builder().connect_timeout(timeout);
+ if let Some(path) = ca_cert_path.map(str::trim).filter(|path| !path.is_empty()) {
+ let path = expand_cert_path(path);
+ let cert_bytes =
+ fs::read(&path).map_err(|e| format!("Failed to read InfluxDB CA certificate at {path}: {e}"))?;
+ let cert = Certificate::from_pem(&cert_bytes)
+ .or_else(|_| Certificate::from_der(&cert_bytes))
+ .map_err(|e| format!("Failed to parse InfluxDB CA certificate at {path}: {e}"))?;
+ builder = builder.add_root_certificate(cert);
+ }
+ builder.build().map_err(|e| format!("Failed to configure InfluxDB HTTP client: {e}"))
+}
+
+fn influxdb_api_version(external_config: Option<&serde_json::Value>) -> InfluxdbApiVersion {
+ match external_config.and_then(|value| value.get("version")).and_then(serde_json::Value::as_str).map(str::trim) {
+ Some("2" | "v2" | "V2") => InfluxdbApiVersion::V2,
+ _ => InfluxdbApiVersion::V1,
+ }
+}
+
+fn influxdb_org(external_config: Option<&serde_json::Value>) -> Option<String> {
+ external_config
+ .and_then(|value| value.get("org").or_else(|| value.get("organization")))
+ .and_then(serde_json::Value::as_str)
+ .map(str::trim)
+ .filter(|value| !value.is_empty())
+ .map(str::to_string)
}
fn expand_cert_path(path: &str) -> String {
@@ -84,6 +152,8 @@ impl Clone for InfluxdbClient {
username: self.username.clone(),
password: self.password.clone(),
url_params: self.url_params.clone(),
+ version: self.version,
+ org: self.org.clone(),
}
}
}
@@ -124,6 +194,24 @@ struct InfluxSeries {
values: Vec<Vec<serde_json::Value>>,
}
+#[derive(Deserialize)]
+struct InfluxBucketsResult {
+ #[serde(default)]
+ buckets: Vec<InfluxBucket>,
+}
+
+#[derive(Deserialize)]
+struct InfluxBucket {
+ name: String,
+}
+
+#[derive(Serialize)]
+struct FluxQueryRequest<'a> {
+ query: &'a str,
+ #[serde(rename = "type")]
+ query_type: &'static str,
+}
+
fn build_query_url(client: &InfluxdbClient, database: Option<&str>, sql: &str) -> String {
let mut params: Vec<String> = vec![];
if let Some(url_params) = &client.url_params {
@@ -137,7 +225,27 @@ fn build_query_url(client: &InfluxdbClient, database: Option<&str>, sql: &str) -
format!("{}/query?{}", &client.base_url, params.join("&").as_str())
}
+fn encode_url_param(value: &str) -> String {
+ utf8_percent_encode(value, NON_ALPHANUMERIC).to_string()
+}
+
+fn build_v2_buckets_url(client: &InfluxdbClient, offset: usize) -> Result<String, String> {
+ let org = client.org.as_deref().ok_or_else(|| "InfluxDB 2.x organization is required".to_string())?;
+ Ok(format!("{}/api/v2/buckets?org={}&limit=100&offset={offset}", &client.base_url, encode_url_param(org)))
+}
+
+fn build_v2_query_url(client: &InfluxdbClient) -> Result<String, String> {
+ let org = client.org.as_deref().ok_or_else(|| "InfluxDB 2.x organization is required".to_string())?;
+ Ok(format!("{}/api/v2/query?org={}", &client.base_url, encode_url_param(org)))
+}
+
fn build_request(client: &InfluxdbClient, req: reqwest::RequestBuilder) -> reqwest::RequestBuilder {
+ if client.version == InfluxdbApiVersion::V2 {
+ if let Some(token) = client.password.as_deref().map(str::trim).filter(|token| !token.is_empty()) {
+ return req.header("Authorization", format!("Token {token}"));
+ }
+ return req;
+ }
match (&client.username, &client.password) {
(Some(u), Some(p)) if !u.is_empty() => req.basic_auth(u, Some(p)),
(Some(u), None) if !u.is_empty() => req.basic_auth(u, None::<&str>),
@@ -145,6 +253,13 @@ fn build_request(client: &InfluxdbClient, req: reqwest::RequestBuilder) -> reqwe
}
}
+fn require_v2_token(client: &InfluxdbClient) -> Result<(), String> {
+ if client.password.as_deref().map(str::trim).filter(|token| !token.is_empty()).is_none() {
+ return Err("InfluxDB 2.x token is required".to_string());
+ }
+ Ok(())
+}
+
async fn influx_query(client: &InfluxdbClient, sql: &str, database: Option<&str>) -> Result<InfluxJsonResult, String> {
let url = build_query_url(client, database, sql);
log::info!("[influxdb] query url={url} username={:?} password={}", client.username, client.password.is_some());
@@ -165,7 +280,55 @@ async fn influx_query(client: &InfluxdbClient, sql: &str, database: Option<&str>
.map_err(|e| format!("InfluxDB parse error: {e}; response: {response_text}"))
}
+async fn influx_v2_buckets(client: &InfluxdbClient, timeout: Duration) -> Result<Vec<InfluxBucket>, String> {
+ require_v2_token(client)?;
+ let mut buckets = Vec::new();
+ let mut offset = 0;
+ loop {
+ let url = build_v2_buckets_url(client, offset)?;
+ let req = build_request(client, client.http.get(&url));
+ let resp = with_connection_timeout("InfluxDB", timeout, async {
+ req.send().await.map_err(|e| format!("InfluxDB connection failed: {e}"))
+ })
+ .await?;
+ if !resp.status().is_success() {
+ return handle_influx_error(resp).await;
+ }
+ let body = resp.text().await.unwrap_or_default();
+ let mut page = serde_json::from_str::<InfluxBucketsResult>(&body)
+ .map(|result| result.buckets)
+ .map_err(|e| format!("InfluxDB parse error: {e}; response: {body}"))?;
+ let page_len = page.len();
+ buckets.append(&mut page);
+ if page_len < 100 {
+ break;
+ }
+ offset += page_len;
+ }
+ Ok(buckets)
+}
+
+async fn influx_flux_query(client: &InfluxdbClient, sql: &str) -> Result<QueryResult, String> {
+ require_v2_token(client)?;
+ let start = Instant::now();
+ let url = build_v2_query_url(client)?;
+ let body = FluxQueryRequest { query: sql, query_type: "flux" };
+ let resp = build_request(client, client.http.post(&url).json(&body))
+ .send()
+ .await
+ .map_err(|e| format!("InfluxDB request failed: {e}"))?;
+ if !resp.status().is_success() {
+ return handle_influx_error(resp).await;
+ }
+ let response_text = resp.text().await.unwrap_or_default();
+ parse_flux_csv(&response_text, start)
+}
+
pub async fn test_connection(client: &InfluxdbClient, timeout: Duration) -> Result<(), String> {
+ if client.version == InfluxdbApiVersion::V2 {
+ influx_v2_buckets(client, timeout).await?;
+ return Ok(());
+ }
let url = build_query_url(client, None, "SHOW DATABASES");
let req = build_request(client, client.http.get(&url));
let resp = with_connection_timeout("InfluxDB", timeout, async {
@@ -180,6 +343,13 @@ pub async fn test_connection(client: &InfluxdbClient, timeout: Duration) -> Resu
}
pub async fn list_databases(client: &InfluxdbClient) -> Result<Vec<DatabaseInfo>, String> {
+ if client.version == InfluxdbApiVersion::V2 {
+ return Ok(influx_v2_buckets(client, Duration::from_secs(30))
+ .await?
+ .into_iter()
+ .map(|bucket| DatabaseInfo { name: bucket.name })
+ .collect());
+ }
let result = influx_query(client, "SHOW DATABASES", None).await?;
Ok(result
.results
@@ -191,6 +361,23 @@ pub async fn list_databases(client: &InfluxdbClient) -> Result<Vec<DatabaseInfo>
}
pub async fn list_tables(client: &InfluxdbClient, database: &str) -> Result<Vec<TableInfo>, String> {
+ if client.version == InfluxdbApiVersion::V2 {
+ let query = format!(
+ "import \"influxdata/influxdb/schema\"\nschema.measurements(bucket: \"{}\", start: 0)",
+ escape_flux_string(database)
+ );
+ let result = influx_flux_query(client, &query).await?;
+ return Ok(flux_column_values(&result, "_value")
+ .into_iter()
+ .map(|name| TableInfo {
+ name,
+ table_type: "TABLE".to_string(),
+ comment: None,
+ parent_schema: None,
+ parent_name: None,
+ })
+ .collect());
+ }
let result = influx_query(client, "SHOW MEASUREMENTS", Some(database)).await?;
let empty = vec![];
let series = result.results.first().map(|r| &r.series).unwrap_or(&empty);
@@ -212,6 +399,9 @@ pub async fn list_tables(client: &InfluxdbClient, database: &str) -> Result<Vec<
}
pub async fn get_columns(client: &InfluxdbClient, database: &str, table: &str) -> Result<Vec<ColumnInfo>, String> {
+ if client.version == InfluxdbApiVersion::V2 {
+ return get_columns_v2(client, database, table).await;
+ }
let empty = vec![];
let tag_sql = format!("SHOW TAG KEYS FROM \"{}\"", table);
@@ -269,6 +459,9 @@ pub async fn get_columns(client: &InfluxdbClient, database: &str, table: &str) -
}
pub async fn execute_query(client: &InfluxdbClient, database: &str, sql: &str) -> Result<QueryResult, String> {
+ if client.version == InfluxdbApiVersion::V2 && looks_like_flux_query(sql) {
+ return influx_flux_query(client, sql).await;
+ }
let start = Instant::now();
let json = influx_query(client, sql, Some(database)).await?;
let series = json.results.iter().flat_map(|r| &r.series).next();
@@ -298,6 +491,142 @@ pub async fn execute_query(client: &InfluxdbClient, database: &str, sql: &str) -
}
}
+async fn get_columns_v2(client: &InfluxdbClient, bucket: &str, measurement: &str) -> Result<Vec<ColumnInfo>, String> {
+ let tag_query = format!(
+ "import \"influxdata/influxdb/schema\"\nschema.measurementTagKeys(bucket: \"{}\", measurement: \"{}\", start: 0)",
+ escape_flux_string(bucket),
+ escape_flux_string(measurement)
+ );
+ let field_query = format!(
+ "import \"influxdata/influxdb/schema\"\nschema.measurementFieldKeys(bucket: \"{}\", measurement: \"{}\", start: 0)",
+ escape_flux_string(bucket),
+ escape_flux_string(measurement)
+ );
+ let tag_result = influx_flux_query(client, &tag_query).await?;
+ let field_result = influx_flux_query(client, &field_query).await?;
+ let time_col = ColumnInfo {
+ name: "time".to_string(),
+ data_type: "timestamp".to_string(),
+ is_nullable: false,
+ column_default: None,
+ is_primary_key: true,
+ extra: None,
+ comment: None,
+ numeric_precision: None,
+ numeric_scale: None,
+ character_maximum_length: None,
+ };
+ let tag_cols = flux_column_values(&tag_result, "_value")
+ .into_iter()
+ .filter(|name| !is_influx_system_column(name))
+ .map(|name| ColumnInfo {
+ name,
+ data_type: "string".to_string(),
+ is_nullable: true,
+ column_default: None,
+ is_primary_key: true,
+ extra: None,
+ comment: None,
+ numeric_precision: None,
+ numeric_scale: None,
+ character_maximum_length: None,
+ });
+ let field_cols = flux_column_values(&field_result, "_value").into_iter().map(|name| ColumnInfo {
+ name,
+ data_type: "field".to_string(),
+ is_nullable: true,
+ column_default: None,
+ is_primary_key: false,
+ extra: None,
+ comment: None,
+ numeric_precision: None,
+ numeric_scale: None,
+ character_maximum_length: None,
+ });
+ Ok(std::iter::once(time_col).chain(tag_cols).chain(field_cols).collect())
+}
+
+fn escape_flux_string(value: &str) -> String {
+ value.replace('\\', "\\\\").replace('"', "\\\"")
+}
+
+fn looks_like_flux_query(sql: &str) -> bool {
+ let trimmed = sql.trim_start().to_ascii_lowercase();
+ trimmed.starts_with("from(")
+ || trimmed.starts_with("import ")
+ || trimmed.starts_with("option ")
+ || trimmed.contains("|>")
+}
+
+fn is_influx_system_column(name: &str) -> bool {
+ matches!(name, "_start" | "_stop" | "_time" | "_value" | "_field" | "_measurement")
+}
+
+fn flux_column_values(result: &QueryResult, column: &str) -> Vec<String> {
+ let Some(index) = result.columns.iter().position(|name| name == column) else {
+ return Vec::new();
+ };
+ result
+ .rows
+ .iter()
+ .filter_map(|row| row.get(index).and_then(serde_json::Value::as_str))
+ .filter(|value| !value.trim().is_empty())
+ .map(str::to_string)
+ .collect()
+}
+
+fn parse_flux_csv(text: &str, start: Instant) -> Result<QueryResult, String> {
+ let mut headers: Option<Vec<String>> = None;
+ let mut rows = Vec::new();
+ let mut reader = csv::ReaderBuilder::new().has_headers(false).from_reader(text.as_bytes());
+ for record in reader.records() {
+ let record = record.map_err(|e| format!("InfluxDB Flux CSV parse error: {e}"))?;
+ if record.is_empty() || record.iter().all(|value| value.trim().is_empty()) {
+ continue;
+ }
+ if record.get(0).is_some_and(|value| value.starts_with('#')) {
+ continue;
+ }
+ if headers.is_none() {
+ let mut parsed = record.iter().map(str::to_string).collect::<Vec<_>>();
+ if parsed.first().is_some_and(|value| value.is_empty()) {
+ parsed.remove(0);
+ }
+ headers = Some(parsed);
+ continue;
+ }
+ let mut values =
+ record
+ .iter()
+ .map(|value| {
+ if value.is_empty() {
+ serde_json::Value::Null
+ } else {
+ serde_json::Value::String(value.to_string())
+ }
+ })
+ .collect::<Vec<_>>();
+ if values.len() == headers.as_ref().map(Vec::len).unwrap_or_default() + 1
+ && record.get(0).is_some_and(|value| value.is_empty())
+ {
+ values.remove(0);
+ }
+ rows.push(values);
+ }
+ let columns = headers.unwrap_or_default();
+ Ok(QueryResult {
+ column_sortables: columns.iter().map(|_| false).collect(),
+ columns,
+ column_types: vec![],
+ affected_rows: rows.len() as u64,
+ rows,
+ execution_time_ms: start.elapsed().as_millis(),
+ truncated: false,
+ session_id: None,
+ has_more: false,
+ })
+}
+
async fn handle_influx_error<T>(resp: Response) -> Result<T, String> {
let status = resp.status();
@@ -345,18 +674,105 @@ fn extract_error_message(body: &str) -> Option<String> {
#[cfg(test)]
mod tests {
use super::*;
+ use serde_json::json;
- #[test]
- fn query_url() {
- let client = InfluxdbClient {
+ fn v1_client() -> InfluxdbClient {
+ InfluxdbClient {
http: reqwest::Client::new(),
base_url: "http://localhost:8086".to_string(),
username: None,
password: None,
url_params: None,
- };
+ version: InfluxdbApiVersion::V1,
+ org: None,
+ }
+ }
+
+ #[test]
+ fn query_url() {
+ let client = v1_client();
let url = build_query_url(&client, Some("sample"), "SHOW DATABASES");
assert_eq!(url, "http://localhost:8086/query?db=sample&q=SHOW%20DATABASES");
}
+
+ #[test]
+ fn v2_config_uses_token_auth_and_org_urls() {
+ let config: ConnectionConfig = serde_json::from_value(json!({
+ "id": "influx-v2",
+ "name": "InfluxDB 2",
+ "db_type": "influxdb",
+ "host": "127.0.0.1",
+ "port": 8086,
+ "username": "ignored-user",
+ "password": "token-value",
+ "database": "metrics",
+ "external_config": {
+ "version": "2",
+ "org": "DBX Org"
+ }
+ }))
+ .unwrap();
+
+ let client = InfluxdbClient::new_for_config("http://localhost:8086/", &config, Duration::from_secs(1)).unwrap();
+
+ assert_eq!(client.version, InfluxdbApiVersion::V2);
+ assert_eq!(client.username, None);
+ assert_eq!(client.password.as_deref(), Some("token-value"));
+ assert_eq!(client.org.as_deref(), Some("DBX Org"));
+ assert_eq!(
+ build_v2_buckets_url(&client, 0).unwrap(),
+ "http://localhost:8086/api/v2/buckets?org=DBX%20Org&limit=100&offset=0"
+ );
+ assert_eq!(build_v2_query_url(&client).unwrap(), "http://localhost:8086/api/v2/query?org=DBX%20Org");
+ }
+
+ #[test]
+ fn v2_config_accepts_organization_alias() {
+ let config: ConnectionConfig = serde_json::from_value(json!({
+ "id": "influx-v2",
+ "name": "InfluxDB 2",
+ "db_type": "influxdb",
+ "host": "127.0.0.1",
+ "port": 8086,
+ "username": "",
+ "password": "token-value",
+ "external_config": {
+ "version": "v2",
+ "organization": "alias-org"
+ }
+ }))
+ .unwrap();
+
+ let client = InfluxdbClient::new_for_config("http://localhost:8086", &config, Duration::from_secs(1)).unwrap();
+
+ assert_eq!(client.version, InfluxdbApiVersion::V2);
+ assert_eq!(client.org.as_deref(), Some("alias-org"));
+ }
+
+ #[test]
+ fn parses_flux_csv_annotations() {
+ let csv = "\
+#datatype,string,long,dateTime:RFC3339,string,double
+#group,false,false,false,true,false
+#default,_result,,,,
+,result,table,_time,_measurement,_value
+,,0,2026-07-06T00:00:00Z,cpu,42.5
+";
+
+ let result = parse_flux_csv(csv, Instant::now()).unwrap();
+
+ assert_eq!(result.columns, vec!["result", "table", "_time", "_measurement", "_value"]);
+ assert_eq!(result.rows.len(), 1);
+ assert_eq!(result.rows[0][3], serde_json::Value::String("cpu".to_string()));
+ assert_eq!(result.rows[0][4], serde_json::Value::String("42.5".to_string()));
+ }
+
+ #[test]
+ fn recognizes_influx_system_columns() {
+ assert!(is_influx_system_column("_start"));
+ assert!(is_influx_system_column("_measurement"));
+ assert!(!is_influx_system_column("host"));
+ assert!(!is_influx_system_column("usage"));
+ }
}
diff --git a/src-tauri/src/commands/connection.rs b/src-tauri/src/commands/connection.rs
index 46a8df72d8..5415d455a6 100644
--- a/src-tauri/src/commands/connection.rs
+++ b/src-tauri/src/commands/connection.rs
@@ -737,16 +737,7 @@ pub async fn test_connection(state: State<'_, Arc<AppState>>, config: Connection
.map(|_| "Connection successful".to_string())
}
DatabaseType::InfluxDb => {
- let username = if config.username.is_empty() { None } else { Some(config.username.clone()) };
- let password = if config.password.is_empty() { None } else { Some(config.password.clone()) };
- let client = db::influxdb_driver::InfluxdbClient::new_with_ca_cert(
- &url,
- username,
- password,
- config.url_params.clone(),
- Some(&config.ca_cert_path),
- connect_timeout,
- )?;
+ let client = db::influxdb_driver::InfluxdbClient::new_for_config(&url, &config, connect_timeout)?;
db::influxdb_driver::test_connection(&client, connect_timeout)
.await
.map(|_| "Connection successful".to_string())
@@ -1054,16 +1045,7 @@ pub async fn connect_db(
PoolKind::Turso(client)
}
DatabaseType::InfluxDb => {
- let username = if db_config.username.is_empty() { None } else { Some(db_config.username.clone()) };
- let password = if db_config.password.is_empty() { None } else { Some(db_config.password.clone()) };
- let client = db::influxdb_driver::InfluxdbClient::new_with_ca_cert(
- &url,
- username,
- password,
- db_config.url_params,
- Some(&db_config.ca_cert_path),
- connect_timeout,
- )?;
+ let client = db::influxdb_driver::InfluxdbClient::new_for_config(&url, &db_config, connect_timeout)?;
db::influxdb_driver::test_connection(&client, connect_timeout).await?;
PoolKind::InfluxDb(client)
}