houhou/src-tauri/src/kanji.rs

73 lines
1.5 KiB
Rust
Raw Normal View History

2023-06-11 20:08:15 +00:00
use sqlx::{Row, SqlitePool};
use tauri::State;
pub struct KanjiDb(pub SqlitePool);
2023-06-11 20:08:15 +00:00
#[derive(Debug, Derivative, Serialize, Deserialize)]
#[derivative(Default)]
pub struct GetKanjiOptions {
2023-06-11 20:08:15 +00:00
/// For looking up an existing one
character: Option<String>,
2023-06-11 20:08:15 +00:00
#[derivative(Default(value = "10"))]
how_many: u32,
}
2023-06-11 20:08:15 +00:00
#[derive(Debug, Serialize, Deserialize)]
pub struct Kanji {
character: String,
meaning: String,
most_used_rank: u32,
}
2023-06-11 20:08:15 +00:00
#[derive(Debug, Serialize, Deserialize)]
pub struct GetKanjiResult {
count: u32,
2023-06-11 20:08:15 +00:00
kanji: Vec<Kanji>,
2023-06-11 20:08:15 +00:00
}
2023-06-11 20:08:15 +00:00
#[tauri::command]
2023-06-11 20:08:15 +00:00
pub async fn get_kanji(
state: State<'_, KanjiDb>,
options: Option<GetKanjiOptions>,
) -> Result<GetKanjiResult, ()> {
let opts = options.unwrap_or_default();
let result = sqlx::query(
2023-06-11 20:08:15 +00:00
r#"
SELECT * FROM KanjiSet
LEFT JOIN KanjiMeaningSet ON KanjiSet.ID = KanjiMeaningSet.Kanji_ID
GROUP BY KanjiSet.ID
HAVING MostUsedRank IS NOT NULL
ORDER BY MostUsedRank
LIMIT ?
"#,
2023-06-11 20:08:15 +00:00
)
.bind(opts.how_many)
.fetch_all(&state.0)
.await
.map_err(|_| ())?;
2023-06-11 20:08:15 +00:00
let kanji = result
.into_iter()
.map(|row| {
let character = row.get("Character");
let meaning = row.get("Meaning");
let most_used_rank = row.get("MostUsedRank");
Kanji {
character,
meaning,
most_used_rank,
}
})
.collect();
2023-06-11 20:08:15 +00:00
let count = sqlx::query("SELECT COUNT(*) FROM KanjiSet")
.fetch_one(&state.0)
2023-06-11 20:08:15 +00:00
.await
.map_err(|_| ())?;
2023-06-11 20:08:15 +00:00
let count = count.try_get(0).map_err(|_| ())?;
2023-06-11 20:08:15 +00:00
2023-06-11 20:08:15 +00:00
Ok(GetKanjiResult { kanji, count })
2023-06-11 20:08:15 +00:00
}