/*
[dependencies]
tokio = { version = "1", features = ["full"] }
tokio-postgres = "0.7"
async-trait = "0.1.68"
*/
use flowmatrix_udf_plugin::udf;
use tokio_postgres::{NoTls, Error, Client};
use async_trait::async_trait;
use std::sync::Arc;
use tokio::sync::OnceCell;
static CLIENT: OnceCell<Arc<Client>> = OnceCell::const_new();
async fn get_client() -> Arc<Client> {
CLIENT.get_or_init(|| async {
let conn_str = "host=localhost user=flowmatrix password=flowmatrix dbname=my_db";
let (client, connection) = tokio_postgres::connect(conn_str, NoTls).await.unwrap();
tokio::spawn(async move {
if let Err(e) = connection.await {
println!("connection error: {}", e);
}
});
Arc::new(client)
});
}
#[udf(ordered, timeout="100ms", allowed_in_flight=100)]
async fn user_name_from_id(id: i64) -> Option<String> {
let client = get_client().await;
let rows = client
.query_opt("SELECT name FROM users WHERE id = $1", &[&id])
.await
.unwrap();
rows.map(|row| row.get(0))
}