Skip to main content

akar_postgres/
lib.rs

1//! PostgreSQL extension for Akar.
2//!
3//! Provides integration with PostgreSQL databases using the native
4//! `tokio-postgres` crate with a synchronous wrapper via `block_on`.
5//!
6//! ## Native Rust approach
7//! Uses `tokio-postgres` (v0.7) with `futures::executor::block_on()` to bridge
8//! the async PostgreSQL client with Akar's synchronous runtime.
9//! Most complex extension due to catalog binding + table enumeration + type mapping.
10
11use akar_extension::{Extension, ExtensionContext};
12use std::sync::Arc;
13
14/// The PostgreSQL extension enables querying PostgreSQL databases from Akar.
15pub struct PostgresExtension;
16
17impl Default for PostgresExtension {
18    fn default() -> Self {
19        Self::new()
20    }
21}
22
23impl PostgresExtension {
24    pub fn new() -> Self {
25        Self
26    }
27}
28
29impl Extension for PostgresExtension {
30    fn name(&self) -> &'static str {
31        "POSTGRES"
32    }
33
34    fn load(&self, context: &ExtensionContext) -> Result<(), String> {
35        use akar_function::registry::ScalarFunction;
36
37        #[cfg(feature = "native")]
38        {
39            // sql_query(conn_str: String, sql: String) → executes SQL against PostgreSQL
40            let query_fn: Arc<dyn Fn(&[Value]) -> Result<Value, String> + Send + Sync> = Arc::new(|args| {
41                if args.len() < 2 {
42                    return Err("sql_query requires (connection_string, sql) arguments".into());
43                }
44                let conn_str = match &args[0] {
45                    Value::String(s) => s.clone(),
46                    _ => return Err("sql_query: first argument must be a connection string".into()),
47                };
48                let sql = match &args[1] {
49                    Value::String(s) => s.clone(),
50                    _ => return Err("sql_query: second argument must be a SQL string".into()),
51                };
52
53                // Create a one-shot tokio runtime for this query
54                let rt = tokio::runtime::Runtime::new().map_err(|e| format!("Failed to create tokio runtime: {e}"))?;
55
56                let (client, connection) = rt
57                    .block_on(async { tokio_postgres::connect(&conn_str, tokio_postgres::NoTls).await })
58                    .map_err(|e| format!("PostgreSQL connect error: {e}"))?;
59
60                // Spawn connection handler
61                rt.spawn(async move {
62                    if let Err(e) = connection.await {
63                        tracing::warn!("PostgreSQL connection error: {e}");
64                    }
65                });
66
67                let rows = rt
68                    .block_on(async { client.query(&sql, &[]).await })
69                    .map_err(|e| format!("PostgreSQL query error: {e}"))?;
70
71                // Collect first row as string result
72                if let Some(row) = rows.first() {
73                    let mut parts = Vec::new();
74                    for i in 0..row.len() {
75                        let val: Option<&str> = row.try_get::<_, &str>(i).ok();
76                        parts.push(val.unwrap_or("NULL").to_string());
77                    }
78                    Ok(Value::String(parts.join(",")))
79                } else {
80                    Ok(Value::String("(empty)".into()))
81                }
82            });
83
84            context.register_scalar_function(
85                "sql_query",
86                ScalarFunction::CustomScalar {
87                    name: "sql_query".into(),
88                    execute: query_fn,
89                },
90            );
91
92            tracing::info!("PostgreSQL extension loaded: 1 function registered (tokio-postgres native)");
93        }
94
95        #[cfg(not(feature = "native"))]
96        {
97            context.register_scalar_function(
98                "sql_query",
99                ScalarFunction::CustomScalar {
100                    name: "sql_query".into(),
101                    execute: Arc::new(|_| Err("PostgreSQL not available (feature 'native' disabled)".into())),
102                },
103            );
104            tracing::info!("PostgreSQL extension loaded: 1 function registered (placeholder)");
105        }
106
107        Ok(())
108    }
109}
110
111#[cfg(test)]
112mod tests {
113    use super::*;
114
115    #[test]
116    fn test_postgres_extension_name() {
117        let ext = PostgresExtension::new();
118        assert_eq!(ext.name(), "POSTGRES");
119    }
120}