feat: improve list_scripts to return actual Vec<(Uuid, Script)>

This commit is contained in:
itsscb 2025-05-04 22:57:19 +02:00
parent 85a51d74ea
commit f535df6da4
2 changed files with 45 additions and 21 deletions

View File

@ -1,7 +1,7 @@
use sqlx::{SqlitePool, migrate::Migrator};
use sqlx::{SqlitePool, migrate::Migrator, prelude::FromRow};
use uuid::Uuid;
use crate::script::Script;
use crate::script::{Parameter, Script};
static MIGRATOR: Migrator = sqlx::migrate!("./migrations");
@ -49,26 +49,51 @@ pub async fn add_script(pool: &SqlitePool, script: &Script) -> Result<(), String
Ok(())
}
#[derive(FromRow, Debug)]
struct ScriptRow {
id: String,
name: String,
path: String,
parameters: String,
default_parameter_set: Option<String>,
help_uri: Option<String>,
supports_paging: Option<String>,
supports_should_process: Option<bool>,
positional_binding: Option<bool>,
}
// TODO: Return Vec<Script> instead of String-Tuple
// TODO: Add Custom Error Type
#[allow(dead_code)]
pub async fn list_scripts(pool: &SqlitePool) -> Result<Vec<(String, String)>, String> {
struct Payload {
pub name: String,
pub path: String,
}
sqlx::query_as!(Payload, r#"SELECT name, path FROM scripts"#)
pub async fn list_scripts(pool: &SqlitePool) -> Result<Vec<(Uuid, Script)>, String> {
sqlx::query_as::<_, ScriptRow>("SELECT id, name, path, parameters, default_parameter_set, help_uri, supports_paging, supports_should_process, positional_binding FROM scripts")
.fetch_all(pool)
.await
.map_err(|e| e.to_string())
.map(|v| {
Ok(v.into_iter()
.map(|i| (i.name, i.path))
.collect::<Vec<(String, String)>>())
})?
.map_err(|e| e.to_string())?
.into_iter()
.map(|row| {
let params: Vec<Parameter> =
serde_json::from_str(&row.parameters).map_err(|e| e.to_string())?;
Ok((
Uuid::parse_str(&row.id).map_err(|e| e.to_string())?,
Script::builder()
.set_name(row.name)
.set_path(row.path)
.set_parameters(params)
.set_default_parameter_set(row.default_parameter_set)
.set_help_uri(row.help_uri)
.set_supports_paging(row.supports_paging)
.set_supports_should_process(row.supports_should_process)
.set_positional_binding(row.positional_binding)
.build()
.map_err(|e| e.to_string())?,
))
})
.collect()
}
mod test {
#[cfg(test)]
mod tests {
#![allow(unused_imports, clippy::unwrap_used, clippy::expect_used)]
use super::*;
@ -88,13 +113,11 @@ mod test {
assert!(add_script(&pool, &script).await.is_ok());
let want = (script.name(), script.path());
let got = list_scripts(&pool).await.unwrap();
assert_eq!(got.len(), 1);
assert_eq!(got[0].0, want.0);
assert_eq!(got[0].1, want.1);
assert_eq!(got[0].1.name(), "test-script.ps1");
assert_eq!(got[0].1.parameters().len(), 9);
std::fs::remove_file(&db_path).unwrap();
}
}

View File

@ -1,12 +1,13 @@
use std::sync::Arc;
use builder::Builder;
use parameter::Parameter;
use serde::{Deserialize, Serialize};
mod builder;
mod parameter;
pub use builder::Builder;
pub use parameter::Parameter;
#[derive(Serialize, Deserialize, Clone, Default, Debug)]
pub struct Script {
name: Arc<str>,