rustango_cms/category/
mod.rs1pub mod assign;
27pub mod model;
28
29pub use assign::PageCategory;
30pub use model::{Category, CategoryError, CategoryNode, NewCategory, Taxonomy, DEFAULT_MAX_DEPTH};
31
32use rustango::sql::Pool;
33
34#[async_trait::async_trait]
40pub trait TaxonomyHandler: Send + Sync + 'static {
41 fn slug(&self) -> &'static str;
43 fn verbose_name(&self) -> &'static str;
45 fn hierarchical(&self) -> bool {
47 true
48 }
49 fn max_depth(&self) -> i32 {
51 DEFAULT_MAX_DEPTH
52 }
53 fn icon(&self) -> Option<&'static str> {
55 None
56 }
57 fn description(&self) -> Option<&'static str> {
58 None
59 }
60 fn ext_table(&self) -> Option<&'static str> {
63 None
64 }
65 async fn ext_widgets(
69 &self,
70 _pool: &Pool,
71 _category_id: i64,
72 ) -> Result<Vec<crate::widget::Widget>, rustango::sql::ExecError> {
73 Ok(Vec::new())
74 }
75 async fn save_ext(
77 &self,
78 _pool: &Pool,
79 _category_id: i64,
80 _form: &std::collections::HashMap<String, String>,
81 ) -> Result<(), rustango::sql::ExecError> {
82 Ok(())
83 }
84}
85
86pub struct TaxonomyHandlerRegistration {
90 pub factory: fn() -> Box<dyn TaxonomyHandler>,
91}
92
93inventory::collect!(TaxonomyHandlerRegistration);
94
95pub fn registered_handlers() -> impl Iterator<Item = Box<dyn TaxonomyHandler>> {
97 inventory::iter::<TaxonomyHandlerRegistration>
98 .into_iter()
99 .map(|r| (r.factory)())
100}
101
102#[must_use]
104pub fn find_handler(slug: &str) -> Option<Box<dyn TaxonomyHandler>> {
105 registered_handlers().find(|h| h.slug() == slug)
106}
107
108pub async fn upsert_taxonomy(
115 pool: &Pool,
116 handler: &dyn TaxonomyHandler,
117) -> Result<(), rustango::sql::ExecError> {
118 use rustango::core::Column as _;
119 use rustango::sql::{Auto, FetcherPool as _};
120
121 let mut existing: Vec<Taxonomy> = Taxonomy::objects()
122 .where_(Taxonomy::slug.eq(handler.slug().to_owned()))
123 .fetch(pool)
124 .await?;
125 if let Some(mut row) = existing.pop() {
126 row.verbose_name = handler.verbose_name().to_owned();
127 row.hierarchical = handler.hierarchical();
128 row.max_depth = handler.max_depth().max(1);
129 row.icon = handler.icon().unwrap_or_default().to_owned();
130 row.description = handler.description().unwrap_or_default().to_owned();
131 row.ext_table = handler.ext_table().unwrap_or_default().to_owned();
132 row.save(pool).await?;
133 } else {
134 let mut row = Taxonomy {
135 id: Auto::Unset,
136 slug: handler.slug().to_owned(),
137 verbose_name: handler.verbose_name().to_owned(),
138 hierarchical: handler.hierarchical(),
139 max_depth: handler.max_depth().max(1),
140 icon: handler.icon().unwrap_or_default().to_owned(),
141 description: handler.description().unwrap_or_default().to_owned(),
142 ext_table: handler.ext_table().unwrap_or_default().to_owned(),
143 created_at: Auto::Unset,
144 updated_at: Auto::Unset,
145 };
146 row.insert(pool).await?;
147 }
148 Ok(())
149}
150
151pub async fn taxonomies(pool: &Pool) -> Result<Vec<Taxonomy>, rustango::sql::ExecError> {
157 use rustango::sql::FetcherPool as _;
158 Taxonomy::objects()
159 .order_by(&[("slug", false)])
160 .fetch(pool)
161 .await
162}
163
164pub async fn find_taxonomy(
169 pool: &Pool,
170 slug: &str,
171) -> Result<Option<Taxonomy>, rustango::sql::ExecError> {
172 use rustango::core::Column as _;
173 Taxonomy::objects()
174 .where_(Taxonomy::slug.eq(slug.to_owned()))
175 .first(pool)
176 .await
177}
178
179#[derive(Default)]
184pub struct CategoryTaxonomy;
185
186impl TaxonomyHandler for CategoryTaxonomy {
187 fn slug(&self) -> &'static str {
188 "category"
189 }
190 fn verbose_name(&self) -> &'static str {
191 "Categories"
192 }
193 fn hierarchical(&self) -> bool {
194 true
195 }
196 fn icon(&self) -> Option<&'static str> {
197 Some("category")
198 }
199 fn description(&self) -> Option<&'static str> {
200 Some("Hierarchical content categories.")
201 }
202}
203
204crate::register_taxonomy!(CategoryTaxonomy);
205
206#[cfg(all(test, feature = "sqlite"))]
207mod tests {
208 use super::*;
209 use rustango::core::Model as _;
210 use rustango::migrate::ddl::create_table_if_not_exists_sql_with_dialect;
211
212 #[test]
213 fn built_in_category_is_registered() {
214 let found = registered_handlers().any(|h| h.slug() == "category");
215 assert!(found, "built-in category vocabulary must be registered");
216 let h = find_handler("category").expect("handler");
217 assert!(h.hierarchical());
218 assert_eq!(h.verbose_name(), "Categories");
219 }
220
221 #[tokio::test]
222 async fn upsert_taxonomy_is_idempotent_find_or_create() {
223 let pool = Pool::connect("sqlite::memory:").await.expect("pool");
224 let ddl = create_table_if_not_exists_sql_with_dialect(pool.dialect(), &Taxonomy::SCHEMA);
225 for stmt in ddl.split(';').map(str::trim).filter(|s| !s.is_empty()) {
226 rustango::sql::raw_execute_pool(&pool, stmt, Vec::new())
227 .await
228 .expect("ddl");
229 }
230 let h = CategoryTaxonomy;
231 upsert_taxonomy(&pool, &h).await.expect("first");
232 upsert_taxonomy(&pool, &h).await.expect("second");
233 let all = taxonomies(&pool).await.expect("list");
234 assert_eq!(
235 all.iter().filter(|t| t.slug == "category").count(),
236 1,
237 "one row, not duplicated"
238 );
239 let cat = find_taxonomy(&pool, "category")
240 .await
241 .expect("q")
242 .expect("row");
243 assert!(cat.hierarchical);
244 assert_eq!(cat.verbose_name, "Categories");
245 }
246}