Elffuss BraidHub

kikocis/utopia public

dev · 3.2 KiBRawPermalink
1//! Postgres 族(顺带覆盖 Greenplum / Timescale 等 PG 兼容系)。线协议直连,
2//! 是四个引擎里唯一有会话可设只读的那个。
3
4use super::{QueryEngine, QueryResult, SchemaColumn, ROW_CAP, STATEMENT_TIMEOUT_SECS};
5use sqlx::postgres::PgPoolOptions;
6use sqlx::Row;
7use std::time::Duration;
8
9pub struct PostgresEngine {
10 conn: String,
11}
12
13impl PostgresEngine {
14 pub fn new(conn: &str) -> Self {
15 Self {
16 conn: conn.to_string(),
17 }
18 }
19
20 async fn pool(&self) -> anyhow::Result<sqlx::PgPool> {
21 Ok(PgPoolOptions::new()
22 .max_connections(1)
23 .acquire_timeout(Duration::from_secs(5))
24 .connect(&self.conn)
25 .await?)
26 }
27}
28
29#[async_trait::async_trait]
30impl QueryEngine for PostgresEngine {
31 async fn test(&self) -> anyhow::Result<()> {
32 let pool = self.pool().await?;
33 sqlx::query("SELECT 1").execute(&pool).await?;
34 pool.close().await;
35 Ok(())
36 }
37
38 async fn fetch_schema(&self) -> anyhow::Result<Vec<SchemaColumn>> {
39 let pool = self.pool().await?;
40 let rows: Vec<(String, String, String, String, Option<String>)> = sqlx::query_as(
41 "SELECT c.table_schema, c.table_name, c.column_name,
42 c.data_type, pgd.description
43 FROM information_schema.columns c
44 LEFT JOIN pg_catalog.pg_statio_all_tables st
45 ON st.schemaname = c.table_schema AND st.relname = c.table_name
46 LEFT JOIN pg_catalog.pg_description pgd
47 ON pgd.objoid = st.relid AND pgd.objsubid = c.ordinal_position
48 WHERE c.table_schema NOT IN ('pg_catalog', 'information_schema')
49 ORDER BY c.table_schema, c.table_name, c.ordinal_position",
50 )
51 .fetch_all(&pool)
52 .await?;
53 pool.close().await;
54 Ok(rows
55 .into_iter()
56 .map(|(schema, table, column, data_type, comment)| SchemaColumn {
57 schema,
58 table,
59 column,
60 data_type,
61 comment,
62 })
63 .collect())
64 }
65
66 async fn execute(&self, sql: &str) -> anyhow::Result<QueryResult> {
67 let pool = self.pool().await?;
68 // 纵深防御第 3 层:会话级只读 + 超时(parser 漏网也写不进去、跑不死库)
69 sqlx::query("SET default_transaction_read_only = on")
70 .execute(&pool)
71 .await?;
72 sqlx::query(&format!(
73 "SET statement_timeout = '{STATEMENT_TIMEOUT_SECS}s'"
74 ))
75 .execute(&pool)
76 .await?;
77 // 第 2 层:外包 LIMIT;row_to_json 让 PG 全权处理类型→JSON(文本键序保留列序)
78 let wrapped = format!(
79 "SELECT row_to_json(_q)::text AS _j FROM ( {sql} ) AS _q LIMIT {}",
80 ROW_CAP + 1
81 );
82 let fetched = sqlx::query(&wrapped).fetch_all(&pool).await?;
83 pool.close().await;
84
85 let truncated = fetched.len() > ROW_CAP;
86 let rows = fetched
87 .into_iter()
88 .take(ROW_CAP)
89 .map(|r| r.try_get::<String, _>("_j").unwrap_or_else(|_| "{}".into()))
90 .collect();
91 Ok(QueryResult { rows, truncated })
92 }
93}