| 1 | //! 问数数据源:系统层注册(凭据集中、跨 KB 复用)+ 知识库层挂载(权限跟 KB 走)。 |
| 2 | //! 查询执行时的安全闸(只读会话、SQL 解析白名单、LIMIT/超时)在 server 侧。 |
| 3 | |
| 4 | use chrono::{DateTime, Utc}; |
| 5 | use sqlx::PgPool; |
| 6 | use utopia_core::models::DataSourceView; |
| 7 | use utopia_core::{AppError, AppResult}; |
| 8 | use uuid::Uuid; |
| 9 | |
| 10 | /// data_sources 的行投影,list 与 mounted 共用。 |
| 11 | type DataSourceRow = ( |
| 12 | Uuid, |
| 13 | String, |
| 14 | String, |
| 15 | String, |
| 16 | DateTime<Utc>, |
| 17 | Option<DateTime<Utc>>, |
| 18 | Option<bool>, |
| 19 | ); |
| 20 | |
| 21 | /// 连接串 → 无凭据摘要(host:port/db)。解析失败给占位符,绝不回显原串。 |
| 22 | pub fn conn_summary(conn: &str) -> String { |
| 23 | url::Url::parse(conn) |
| 24 | .ok() |
| 25 | .map(|u| { |
| 26 | format!( |
| 27 | "{}:{}{}", |
| 28 | u.host_str().unwrap_or("?"), |
| 29 | u.port() |
| 30 | .map(|p| p.to_string()) |
| 31 | .unwrap_or_else(|| "5432".into()), |
| 32 | u.path() |
| 33 | ) |
| 34 | }) |
| 35 | .unwrap_or_else(|| "(unparsed)".into()) |
| 36 | } |
| 37 | |
| 38 | pub async fn list(pool: &PgPool) -> AppResult<Vec<DataSourceView>> { |
| 39 | let rows: Vec<DataSourceRow> = sqlx::query_as( |
| 40 | "SELECT id, name, engine, conn_string, created_at, last_test_at, last_test_ok |
| 41 | FROM data_sources ORDER BY name", |
| 42 | ) |
| 43 | .fetch_all(pool) |
| 44 | .await?; |
| 45 | Ok(rows |
| 46 | .into_iter() |
| 47 | .map( |
| 48 | |(id, name, engine, conn, created_at, last_test_at, last_test_ok)| DataSourceView { |
| 49 | id, |
| 50 | name, |
| 51 | engine, |
| 52 | summary: conn_summary(&conn), |
| 53 | created_at, |
| 54 | last_test_at, |
| 55 | last_test_ok, |
| 56 | }, |
| 57 | ) |
| 58 | .collect()) |
| 59 | } |
| 60 | |
| 61 | pub async fn create( |
| 62 | pool: &PgPool, |
| 63 | name: &str, |
| 64 | engine: &str, |
| 65 | conn_string: &str, |
| 66 | created_by: Uuid, |
| 67 | ) -> AppResult<Uuid> { |
| 68 | if name.trim().is_empty() { |
| 69 | return Err(AppError::invalid( |
| 70 | "ds_name_required", |
| 71 | "Data source name is required", |
| 72 | )); |
| 73 | } |
| 74 | if engine != "postgres" { |
| 75 | return Err(AppError::invalid( |
| 76 | "only_postgres", |
| 77 | "Only the postgres engine is supported for now", |
| 78 | )); |
| 79 | } |
| 80 | if !conn_string.starts_with("postgres://") && !conn_string.starts_with("postgresql://") { |
| 81 | return Err(AppError::invalid( |
| 82 | "bad_conn_string", |
| 83 | "Connection string must start with postgres://", |
| 84 | )); |
| 85 | } |
| 86 | let id = Uuid::now_v7(); |
| 87 | sqlx::query( |
| 88 | "INSERT INTO data_sources (id, name, engine, conn_string, created_by) |
| 89 | VALUES ($1, $2, $3, $4, $5)", |
| 90 | ) |
| 91 | .bind(id) |
| 92 | .bind(name.trim()) |
| 93 | .bind(engine) |
| 94 | .bind(conn_string.trim()) |
| 95 | .bind(created_by) |
| 96 | .execute(pool) |
| 97 | .await?; |
| 98 | Ok(id) |
| 99 | } |
| 100 | |
| 101 | pub async fn delete(pool: &PgPool, id: Uuid) -> AppResult<()> { |
| 102 | let res = sqlx::query("DELETE FROM data_sources WHERE id = $1") |
| 103 | .bind(id) |
| 104 | .execute(pool) |
| 105 | .await?; |
| 106 | if res.rows_affected() == 0 { |
| 107 | return Err(AppError::NotFound); |
| 108 | } |
| 109 | Ok(()) |
| 110 | } |
| 111 | |
| 112 | /// 连接串只在服务端内部流转(测试连接/查询执行)。 |
| 113 | pub async fn conn_string(pool: &PgPool, id: Uuid) -> AppResult<String> { |
| 114 | let row: Option<(String,)> = |
| 115 | sqlx::query_as("SELECT conn_string FROM data_sources WHERE id = $1") |
| 116 | .bind(id) |
| 117 | .fetch_optional(pool) |
| 118 | .await?; |
| 119 | row.map(|(c,)| c).ok_or(AppError::NotFound) |
| 120 | } |
| 121 | |
| 122 | pub async fn record_test(pool: &PgPool, id: Uuid, ok: bool) -> AppResult<()> { |
| 123 | sqlx::query("UPDATE data_sources SET last_test_at = now(), last_test_ok = $2 WHERE id = $1") |
| 124 | .bind(id) |
| 125 | .bind(ok) |
| 126 | .execute(pool) |
| 127 | .await?; |
| 128 | Ok(()) |
| 129 | } |
| 130 | |
| 131 | // --------------------------------------------------------------------------- |
| 132 | // KB 挂载 |
| 133 | // --------------------------------------------------------------------------- |
| 134 | |
| 135 | pub async fn mount(pool: &PgPool, kb_id: Uuid, data_source_id: Uuid) -> AppResult<()> { |
| 136 | sqlx::query( |
| 137 | "INSERT INTO kb_data_sources (kb_id, data_source_id) VALUES ($1, $2) |
| 138 | ON CONFLICT DO NOTHING", |
| 139 | ) |
| 140 | .bind(kb_id) |
| 141 | .bind(data_source_id) |
| 142 | .execute(pool) |
| 143 | .await?; |
| 144 | Ok(()) |
| 145 | } |
| 146 | |
| 147 | pub async fn unmount(pool: &PgPool, kb_id: Uuid, data_source_id: Uuid) -> AppResult<()> { |
| 148 | sqlx::query("DELETE FROM kb_data_sources WHERE kb_id = $1 AND data_source_id = $2") |
| 149 | .bind(kb_id) |
| 150 | .bind(data_source_id) |
| 151 | .execute(pool) |
| 152 | .await?; |
| 153 | Ok(()) |
| 154 | } |
| 155 | |
| 156 | pub async fn mounted(pool: &PgPool, kb_id: Uuid) -> AppResult<Vec<DataSourceView>> { |
| 157 | let rows: Vec<DataSourceRow> = sqlx::query_as( |
| 158 | "SELECT d.id, d.name, d.engine, d.conn_string, d.created_at, |
| 159 | d.last_test_at, d.last_test_ok |
| 160 | FROM kb_data_sources m JOIN data_sources d ON d.id = m.data_source_id |
| 161 | WHERE m.kb_id = $1 ORDER BY d.name", |
| 162 | ) |
| 163 | .bind(kb_id) |
| 164 | .fetch_all(pool) |
| 165 | .await?; |
| 166 | Ok(rows |
| 167 | .into_iter() |
| 168 | .map( |
| 169 | |(id, name, engine, conn, created_at, last_test_at, last_test_ok)| DataSourceView { |
| 170 | id, |
| 171 | name, |
| 172 | engine, |
| 173 | summary: conn_summary(&conn), |
| 174 | created_at, |
| 175 | last_test_at, |
| 176 | last_test_ok, |
| 177 | }, |
| 178 | ) |
| 179 | .collect()) |
| 180 | } |
| 181 | |
| 182 | /// (engine, conn_string):查询执行/测试/拉 schema 用(凭据不出服务端)。 |
| 183 | pub async fn engine_and_conn(pool: &PgPool, id: Uuid) -> AppResult<(String, String)> { |
| 184 | let row: Option<(String, String)> = |
| 185 | sqlx::query_as("SELECT engine, conn_string FROM data_sources WHERE id = $1") |
| 186 | .bind(id) |
| 187 | .fetch_optional(pool) |
| 188 | .await?; |
| 189 | row.ok_or(AppError::NotFound) |
| 190 | } |