pub mod assign;
pub mod model;
pub use assign::PageCategory;
pub use model::{Category, CategoryError, CategoryNode, NewCategory, Taxonomy, DEFAULT_MAX_DEPTH};
use rustango::sql::Pool;
#[async_trait::async_trait]
pub trait TaxonomyHandler: Send + Sync + 'static {
fn slug(&self) -> &'static str;
fn verbose_name(&self) -> &'static str;
fn hierarchical(&self) -> bool {
true
}
fn max_depth(&self) -> i32 {
DEFAULT_MAX_DEPTH
}
fn icon(&self) -> Option<&'static str> {
None
}
fn description(&self) -> Option<&'static str> {
None
}
fn ext_table(&self) -> Option<&'static str> {
None
}
async fn ext_widgets(
&self,
_pool: &Pool,
_category_id: i64,
) -> Result<Vec<crate::widget::Widget>, rustango::sql::ExecError> {
Ok(Vec::new())
}
async fn save_ext(
&self,
_pool: &Pool,
_category_id: i64,
_form: &std::collections::HashMap<String, String>,
) -> Result<(), rustango::sql::ExecError> {
Ok(())
}
}
pub struct TaxonomyHandlerRegistration {
pub factory: fn() -> Box<dyn TaxonomyHandler>,
}
inventory::collect!(TaxonomyHandlerRegistration);
pub fn registered_handlers() -> impl Iterator<Item = Box<dyn TaxonomyHandler>> {
inventory::iter::<TaxonomyHandlerRegistration>
.into_iter()
.map(|r| (r.factory)())
}
#[must_use]
pub fn find_handler(slug: &str) -> Option<Box<dyn TaxonomyHandler>> {
registered_handlers().find(|h| h.slug() == slug)
}
pub async fn upsert_taxonomy(
pool: &Pool,
handler: &dyn TaxonomyHandler,
) -> Result<(), rustango::sql::ExecError> {
use rustango::core::Column as _;
use rustango::sql::{Auto, FetcherPool as _};
let mut existing: Vec<Taxonomy> = Taxonomy::objects()
.where_(Taxonomy::slug.eq(handler.slug().to_owned()))
.fetch(pool)
.await?;
if let Some(mut row) = existing.pop() {
row.verbose_name = handler.verbose_name().to_owned();
row.hierarchical = handler.hierarchical();
row.max_depth = handler.max_depth().max(1);
row.icon = handler.icon().unwrap_or_default().to_owned();
row.description = handler.description().unwrap_or_default().to_owned();
row.ext_table = handler.ext_table().unwrap_or_default().to_owned();
row.save(pool).await?;
} else {
let mut row = Taxonomy {
id: Auto::Unset,
slug: handler.slug().to_owned(),
verbose_name: handler.verbose_name().to_owned(),
hierarchical: handler.hierarchical(),
max_depth: handler.max_depth().max(1),
icon: handler.icon().unwrap_or_default().to_owned(),
description: handler.description().unwrap_or_default().to_owned(),
ext_table: handler.ext_table().unwrap_or_default().to_owned(),
created_at: Auto::Unset,
updated_at: Auto::Unset,
};
row.insert(pool).await?;
}
Ok(())
}
pub async fn taxonomies(pool: &Pool) -> Result<Vec<Taxonomy>, rustango::sql::ExecError> {
use rustango::sql::FetcherPool as _;
Taxonomy::objects()
.order_by(&[("slug", false)])
.fetch(pool)
.await
}
pub async fn find_taxonomy(
pool: &Pool,
slug: &str,
) -> Result<Option<Taxonomy>, rustango::sql::ExecError> {
use rustango::core::Column as _;
Taxonomy::objects()
.where_(Taxonomy::slug.eq(slug.to_owned()))
.first(pool)
.await
}
#[derive(Default)]
pub struct CategoryTaxonomy;
impl TaxonomyHandler for CategoryTaxonomy {
fn slug(&self) -> &'static str {
"category"
}
fn verbose_name(&self) -> &'static str {
"Categories"
}
fn hierarchical(&self) -> bool {
true
}
fn icon(&self) -> Option<&'static str> {
Some("category")
}
fn description(&self) -> Option<&'static str> {
Some("Hierarchical content categories.")
}
}
crate::register_taxonomy!(CategoryTaxonomy);
#[cfg(all(test, feature = "sqlite"))]
mod tests {
use super::*;
use rustango::core::Model as _;
use rustango::migrate::ddl::create_table_if_not_exists_sql_with_dialect;
#[test]
fn built_in_category_is_registered() {
let found = registered_handlers().any(|h| h.slug() == "category");
assert!(found, "built-in category vocabulary must be registered");
let h = find_handler("category").expect("handler");
assert!(h.hierarchical());
assert_eq!(h.verbose_name(), "Categories");
}
#[tokio::test]
async fn upsert_taxonomy_is_idempotent_find_or_create() {
let pool = Pool::connect("sqlite::memory:").await.expect("pool");
let ddl = create_table_if_not_exists_sql_with_dialect(pool.dialect(), &Taxonomy::SCHEMA);
for stmt in ddl.split(';').map(str::trim).filter(|s| !s.is_empty()) {
rustango::sql::raw_execute_pool(&pool, stmt, Vec::new())
.await
.expect("ddl");
}
let h = CategoryTaxonomy;
upsert_taxonomy(&pool, &h).await.expect("first");
upsert_taxonomy(&pool, &h).await.expect("second");
let all = taxonomies(&pool).await.expect("list");
assert_eq!(
all.iter().filter(|t| t.slug == "category").count(),
1,
"one row, not duplicated"
);
let cat = find_taxonomy(&pool, "category")
.await
.expect("q")
.expect("row");
assert!(cat.hierarchical);
assert_eq!(cat.verbose_name, "Categories");
}
}