Skip to main content

ironflow_ops_postgres/schema/
schemas.rs

1//! Schema listing operation.
2
3use async_trait::async_trait;
4use ironflow_core::error::OperationError;
5use ironflow_core::operation::{Operation, OperationContext, TypedOperation};
6use serde::{Deserialize, Serialize};
7use serde_json::Value;
8use sqlx::{PgPool, Row};
9
10use crate::helpers::{pg_error, to_value};
11
12/// Output of [`ListSchemas`].
13#[derive(Debug, Clone, Serialize, Deserialize)]
14pub struct ListSchemasOutput {
15    /// Schema names.
16    pub schemas: Vec<String>,
17}
18
19/// List all schemas in the current database.
20///
21/// # Examples
22///
23/// ```no_run
24/// use ironflow_ops_postgres::schema::schemas::ListSchemas;
25/// use ironflow_core::operation::Operation;
26///
27/// # fn example(pool: sqlx::PgPool) {
28/// let op = ListSchemas::new(pool);
29/// assert_eq!(op.kind(), "postgres");
30/// # }
31/// ```
32pub struct ListSchemas {
33    pool: PgPool,
34}
35
36impl ListSchemas {
37    /// Create a new list-schemas operation.
38    pub fn new(pool: PgPool) -> Self {
39        Self { pool }
40    }
41
42    /// Execute and return a typed result.
43    ///
44    /// # Errors
45    ///
46    /// Returns [`OperationError::External`] on connection errors.
47    pub async fn run(&self, _ctx: &OperationContext) -> Result<ListSchemasOutput, OperationError> {
48        let rows =
49            sqlx::query("SELECT schema_name FROM information_schema.schemata ORDER BY schema_name")
50                .fetch_all(&self.pool)
51                .await
52                .map_err(pg_error)?;
53        let schemas = rows
54            .iter()
55            .map(|r| r.try_get::<String, _>("schema_name").map_err(pg_error))
56            .collect::<Result<Vec<_>, _>>()?;
57        Ok(ListSchemasOutput { schemas })
58    }
59}
60
61#[async_trait]
62impl Operation for ListSchemas {
63    fn kind(&self) -> &str {
64        "postgres"
65    }
66    async fn execute(&self, ctx: &OperationContext) -> Result<Value, OperationError> {
67        to_value(&self.run(ctx).await?)
68    }
69}
70
71impl TypedOperation for ListSchemas {
72    type Output = ListSchemasOutput;
73}
74
75#[cfg(test)]
76mod tests {
77    use super::*;
78
79    #[tokio::test]
80    async fn kind() {
81        let pool = PgPool::connect_lazy("postgres://localhost/test").unwrap();
82        let op = ListSchemas::new(pool);
83        assert_eq!(op.kind(), "postgres");
84    }
85}