use async_trait::async_trait;
use ironflow_core::error::OperationError;
use ironflow_core::operation::{Operation, OperationContext, TypedOperation};
use serde::{Deserialize, Serialize};
use serde_json::Value;
use sqlx::{PgPool, Row};
use crate::helpers::{pg_error, to_value};
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct IndexInfo {
pub name: String,
pub is_unique: bool,
pub is_primary: bool,
pub definition: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ListIndexesOutput {
pub indexes: Vec<IndexInfo>,
}
pub struct ListIndexes {
pool: PgPool,
schema: String,
table: String,
}
impl ListIndexes {
pub fn new(pool: PgPool, schema: impl Into<String>, table: impl Into<String>) -> Self {
Self {
pool,
schema: schema.into(),
table: table.into(),
}
}
pub async fn run(&self, _ctx: &OperationContext) -> Result<ListIndexesOutput, OperationError> {
let rows = sqlx::query(
"SELECT i.relname AS index_name, \
ix.indisunique AS is_unique, \
ix.indisprimary AS is_primary, \
pg_get_indexdef(ix.indexrelid) AS definition \
FROM pg_index ix \
JOIN pg_class i ON i.oid = ix.indexrelid \
JOIN pg_class t ON t.oid = ix.indrelid \
JOIN pg_namespace n ON n.oid = t.relnamespace \
WHERE n.nspname = $1 AND t.relname = $2 \
ORDER BY i.relname",
)
.bind(&self.schema)
.bind(&self.table)
.fetch_all(&self.pool)
.await
.map_err(pg_error)?;
let indexes = rows
.iter()
.map(|r| {
Ok(IndexInfo {
name: r.try_get::<String, _>("index_name").map_err(pg_error)?,
is_unique: r.try_get::<bool, _>("is_unique").map_err(pg_error)?,
is_primary: r.try_get::<bool, _>("is_primary").map_err(pg_error)?,
definition: r.try_get::<String, _>("definition").map_err(pg_error)?,
})
})
.collect::<Result<Vec<_>, OperationError>>()?;
Ok(ListIndexesOutput { indexes })
}
}
#[async_trait]
impl Operation for ListIndexes {
fn kind(&self) -> &str {
"postgres"
}
async fn execute(&self, ctx: &OperationContext) -> Result<Value, OperationError> {
to_value(&self.run(ctx).await?)
}
fn input(&self) -> Option<Value> {
Some(serde_json::json!({ "schema": self.schema, "table": self.table }))
}
}
impl TypedOperation for ListIndexes {
type Output = ListIndexesOutput;
}
#[cfg(test)]
mod tests {
use super::*;
#[tokio::test]
async fn kind() {
let pool = PgPool::connect_lazy("postgres://localhost/test").unwrap();
let op = ListIndexes::new(pool, "public", "users");
assert_eq!(op.kind(), "postgres");
}
}