Skip to main content

laravel_nestedset/
commands.rs

1//! The service provider and the `nestedset:check` and `nestedset:fix` console commands.
2
3use std::future::Future;
4use std::pin::Pin;
5
6use laravel::console::{Console, clap};
7use laravel::container::{Inject, Registrar};
8use laravel::db::IntoExpr;
9use laravel::foundation::ServiceProvider;
10
11use crate::node::NestedSet;
12
13type Boxed<T> = Pin<Box<dyn Future<Output = laravel::Result<T>> + Send>>;
14
15/// The broken nodes of one table, by kind, as text keys.
16type Findings = Vec<(&'static str, Vec<String>)>;
17
18/// A registered model: its table and type-erased `check_tree` and `fix_tree`.
19#[derive(Clone, Copy)]
20struct Entry {
21    table: &'static str,
22    check: fn() -> Boxed<Findings>,
23    fix: fn() -> Boxed<u64>,
24}
25
26fn check<M: NestedSet>() -> Boxed<Findings> {
27    Box::pin(async {
28        let report = M::check_tree().await?;
29        let keys = |keys: Vec<M::Key>| keys.iter().map(ToString::to_string).collect::<Vec<_>>();
30        Ok(vec![
31            ("bad bounds", keys(report.oddness)),
32            ("shared bounds", keys(report.duplicates)),
33            ("parent_id doesn't match the bounds", keys(report.wrong_parent)),
34            ("parent_id points to no node", keys(report.missing_parent)),
35        ])
36    })
37}
38
39fn fix<M: NestedSet>() -> Boxed<u64>
40where
41    Option<M::Key>: IntoExpr,
42{
43    Box::pin(M::fix_tree())
44}
45
46/// The models the console commands work on.
47struct NestedSetModels(Vec<Entry>);
48
49impl NestedSetModels {
50    /// The models named by `table`, or all of them when `table` is `None`.
51    fn select(&self, table: Option<&str>) -> Vec<Entry> {
52        self.0
53            .iter()
54            .filter(|entry| table.is_none_or(|table| entry.table == table))
55            .copied()
56            .collect()
57    }
58}
59
60/// Registers the `nestedset:check` and `nestedset:fix` commands for the models you list.
61///
62/// ```no_run
63/// # use laravel::model::{Column, model};
64/// # use laravel_nestedset::NestedSet;
65/// # #[model]
66/// # pub struct Category {
67/// #     pub id: i64,
68/// #     #[default]
69/// #     pub lft: i64,
70/// #     #[default]
71/// #     pub rgt: i64,
72/// #     pub parent_id: Option<i64>,
73/// # }
74/// # impl NestedSet for Category {
75/// #     fn lft_column() -> Column<Self, i64> { Category::lft }
76/// #     fn rgt_column() -> Column<Self, i64> { Category::rgt }
77/// #     fn parent_column() -> Column<Self, Option<i64>> { Category::parent_id }
78/// # }
79/// use laravel::Application;
80/// use laravel_nestedset::NestedSetServiceProvider;
81///
82/// Application::configure().with_providers(|providers| {
83///     providers.add(NestedSetServiceProvider::new().model::<Category>());
84/// });
85/// ```
86///
87/// ```shell
88/// laravel nestedset:check             # every registered table; exits with 1 when one is broken
89/// laravel nestedset:check categories  # one table
90/// laravel nestedset:fix categories    # rebuild the bounds from parent_id
91/// ```
92#[derive(Clone, Default)]
93pub struct NestedSetServiceProvider {
94    models: Vec<Entry>,
95}
96
97impl NestedSetServiceProvider {
98    /// A provider without models yet.
99    #[must_use]
100    pub fn new() -> Self {
101        Self::default()
102    }
103
104    /// Adds the model `M`: the commands name it by its table.
105    #[must_use]
106    pub fn model<M: NestedSet>(mut self) -> Self
107    where
108        Option<M::Key>: IntoExpr,
109    {
110        self.models.push(Entry {
111            table: M::META.table,
112            check: check::<M>,
113            fix: fix::<M>,
114        });
115        self
116    }
117}
118
119impl ServiceProvider for NestedSetServiceProvider {
120    fn register(&self, app: &mut Registrar) {
121        app.instance(NestedSetModels(self.models.clone()));
122        let commands = app.commands();
123        commands.add::<CheckCommand>();
124        commands.add::<FixCommand>();
125    }
126}
127
128/// Check nested set trees for broken nodes.
129#[derive(clap::Parser)]
130#[command(name = "nestedset:check")]
131struct CheckCommand {
132    /// The table to check, such as `categories`. Every registered table when left out.
133    table: Option<String>,
134}
135
136#[laravel::console::command]
137impl CheckCommand {
138    async fn handle(self, console: &mut Console, models: Inject<NestedSetModels>) -> laravel::Result<u8> {
139        let Some(entries) = selected(&models, self.table.as_deref(), console) else {
140            return Ok(2);
141        };
142        let mut broken = false;
143        for entry in entries {
144            let findings = (entry.check)().await?;
145            if findings.iter().all(|(_, keys)| keys.is_empty()) {
146                console.success(format!("`{}` is valid.", entry.table));
147                continue;
148            }
149            broken = true;
150            console.error(format!("`{}` is broken.", entry.table));
151            for (kind, keys) in findings.into_iter().filter(|(_, keys)| !keys.is_empty()) {
152                console.line(format!("  {kind}: {}", shorten(&keys)));
153            }
154        }
155        if broken {
156            console.info("Run `nestedset:fix` to rebuild the bounds from parent_id.");
157        }
158        Ok(u8::from(broken))
159    }
160}
161
162/// Rebuild the bounds of nested set trees from `parent_id`.
163#[derive(clap::Parser)]
164#[command(name = "nestedset:fix")]
165struct FixCommand {
166    /// The table to fix, such as `categories`. Every registered table when left out.
167    table: Option<String>,
168}
169
170#[laravel::console::command]
171impl FixCommand {
172    async fn handle(self, console: &mut Console, models: Inject<NestedSetModels>) -> laravel::Result<u8> {
173        let Some(entries) = selected(&models, self.table.as_deref(), console) else {
174            return Ok(2);
175        };
176        for entry in entries {
177            match (entry.fix)().await? {
178                0 => console.success(format!("`{}` needed no changes.", entry.table)),
179                changed => console.success(format!("`{}`: fixed {changed} rows.", entry.table)),
180            }
181        }
182        Ok(0)
183    }
184}
185
186/// The models a command runs on, or `None` after telling the user that nothing matches.
187fn selected(models: &NestedSetModels, table: Option<&str>, console: &mut Console) -> Option<Vec<Entry>> {
188    let entries = models.select(table);
189    if !entries.is_empty() {
190        return Some(entries);
191    }
192    match table {
193        Some(table) => console.error(format!(
194            "No nested set model uses the table `{table}`. Add it with `NestedSetServiceProvider::model`."
195        )),
196        None => console.error("No nested set models are registered. Add them with `NestedSetServiceProvider::model`."),
197    }
198    None
199}
200
201/// The first keys of a list, with a count of the rest.
202fn shorten(keys: &[String]) -> String {
203    const SHOWN: usize = 20;
204    let shown = keys.iter().take(SHOWN).cloned().collect::<Vec<_>>().join(", ");
205    match keys.len().saturating_sub(SHOWN) {
206        0 => shown,
207        more => format!("{shown} and {more} more"),
208    }
209}