Skip to main content

laravel_nestedset/
check.rs

1//! Checking a table's trees for broken bounds and rebuilding the bounds from `parent_id`.
2
3use std::collections::{HashMap, HashSet};
4use std::fmt::Write as _;
5
6use laravel::db::sqlx::AssertSqlSafe;
7use laravel::db::{self, IntoExpr, Values};
8use laravel::model::__query;
9
10use crate::chain::integer_key;
11use crate::event::{TreeChange, changed};
12use crate::locks::Locks;
13use crate::node::NestedSet;
14use crate::ops::{ATTEMPTS, connection, quote, untouched};
15
16/// What [`NestedSet::check_tree`] found: the keys of the broken nodes, by kind of damage.
17#[derive(Debug, Clone, PartialEq, Eq)]
18#[non_exhaustive]
19pub struct TreeReport<K> {
20    /// Nodes whose bounds can't be right: `lft` below 1, `lft >= rgt`, or an even width.
21    pub oddness: Vec<K>,
22    /// Nodes that share a bound with another node of their tree.
23    pub duplicates: Vec<K>,
24    /// Nodes whose `parent_id` isn't the nearest node around them.
25    pub wrong_parent: Vec<K>,
26    /// Nodes whose `parent_id` names a row that isn't in their tree.
27    pub missing_parent: Vec<K>,
28    /// Nodes whose stored depth doesn't match their place, when the model has a
29    /// [`depth_column`](NestedSet::depth_column).
30    pub wrong_depth: Vec<K>,
31}
32
33impl<K> TreeReport<K> {
34    /// Whether any node is broken.
35    #[must_use]
36    pub fn is_broken(&self) -> bool {
37        !(self.oddness.is_empty()
38            && self.duplicates.is_empty()
39            && self.wrong_parent.is_empty()
40            && self.missing_parent.is_empty()
41            && self.wrong_depth.is_empty())
42    }
43}
44
45/// Splits the table's rows into their trees, each in bound order.
46async fn trees<M: NestedSet>(locks: Option<&Locks>) -> laravel::Result<Vec<Vec<M>>> {
47    let query = __query::<M>();
48    let query = match locks {
49        Some(locks) => locks.fresh(query),
50        None => query,
51    };
52    let rows = query
53        .order_by(M::lft_column().asc())
54        .order_by(M::META.key.asc())
55        .get()
56        .await?;
57    let mut order: Vec<String> = Vec::new();
58    let mut trees: HashMap<String, Vec<M>> = HashMap::new();
59    for row in rows {
60        let name = row.scope().lock_name();
61        if !trees.contains_key(&name) {
62            order.push(name.clone());
63        }
64        trees.entry(name).or_default().push(row);
65    }
66    Ok(order.into_iter().filter_map(|name| trees.remove(&name)).collect())
67}
68
69pub(crate) async fn check_tree<M: NestedSet>() -> laravel::Result<TreeReport<M::Key>> {
70    let mut report = TreeReport {
71        oddness: Vec::new(),
72        duplicates: Vec::new(),
73        wrong_parent: Vec::new(),
74        missing_parent: Vec::new(),
75        wrong_depth: Vec::new(),
76    };
77    for tree in trees::<M>(None).await? {
78        check(&tree, &mut report);
79    }
80    Ok(report)
81}
82
83/// Checks one tree, whose nodes are in bound order.
84fn check<M: NestedSet>(nodes: &[M], report: &mut TreeReport<M::Key>) {
85    let keys: HashSet<&M::Key> = nodes.iter().map(NestedSet::node_key).collect();
86    let mut seen: HashMap<i64, usize> = HashMap::new();
87    for node in nodes {
88        *seen.entry(node.lft()).or_default() += 1;
89        *seen.entry(node.rgt()).or_default() += 1;
90    }
91
92    // The nodes still open around the current one, innermost last.
93    let mut open: Vec<&M> = Vec::new();
94    for node in nodes {
95        let key = node.node_key();
96        let odd = node.lft() < 1 || node.lft() >= node.rgt() || (node.rgt() - node.lft()) % 2 == 0;
97        if odd {
98            report.oddness.push(key.clone());
99        }
100        if seen[&node.lft()] > 1 || seen[&node.rgt()] > 1 {
101            report.duplicates.push(key.clone());
102        }
103        while open.last().is_some_and(|around| around.rgt() < node.lft()) {
104            open.pop();
105        }
106        let around = open
107            .last()
108            .filter(|around| around.rgt() > node.rgt())
109            .map(|around| around.node_key());
110        match node.parent_key() {
111            Some(parent) if !keys.contains(parent) => report.missing_parent.push(key.clone()),
112            parent if !odd && around != parent => report.wrong_parent.push(key.clone()),
113            _ => {}
114        }
115        if let Some(column) = M::depth_column() {
116            let depth = open.iter().filter(|around| around.rgt() > node.rgt()).count();
117            if !odd && usize::try_from(*column.get(node)).ok() != Some(depth) {
118                report.wrong_depth.push(key.clone());
119            }
120        }
121        if !odd {
122            open.push(node);
123        }
124    }
125}
126
127pub(crate) async fn fix_tree<M: NestedSet>() -> laravel::Result<u64>
128where
129    Option<M::Key>: IntoExpr,
130{
131    // Which trees there are, read before the transaction: inside it, every read comes after the
132    // locks.
133    let mut scopes: Vec<_> = trees::<M>(None).await?.iter().map(|tree| tree[0].scope()).collect();
134    scopes.sort_by_key(crate::scope::Scope::lock_name);
135    connection::<M>()?
136        .transaction_with_attempts(ATTEMPTS, async |tx| {
137            let mut locks = Locks::open::<M>(tx).await?;
138            locks.roots::<M>(tx).await?;
139            for scope in &scopes {
140                locks.tree(tx, scope).await?;
141            }
142            let trees = trees::<M>(Some(&locks)).await?;
143            let mut fixed = 0;
144            for tree in &trees {
145                let parents: Vec<Option<M::Key>> = tree.iter().map(|node| node.parent_key().cloned()).collect();
146                fixed += write_rebuilt(tree, &parents).await?;
147            }
148            if fixed > 0 {
149                changed::<M>(TreeChange::Fixed, None).await?;
150            }
151            locks.release_after_commit(tx).await?;
152            Ok(fixed)
153        })
154        .await
155}
156
157/// Writes the bounds, parent, and depth [`rebuild`] works out for one tree to the rows that
158/// differ, and returns how many it changed. `parents[i]` is the parent `nodes[i]` should have;
159/// siblings keep the order of `nodes`.
160pub(crate) async fn write_rebuilt<M: NestedSet>(nodes: &[M], parents: &[Option<M::Key>]) -> laravel::Result<u64>
161where
162    Option<M::Key>: IntoExpr,
163{
164    let changed: Vec<(&M, Rebuilt<M::Key>)> = rebuild(nodes, parents)
165        .into_iter()
166        .filter(|(node, rebuilt)| {
167            (rebuilt.lft, rebuilt.rgt, rebuilt.parent.as_ref()) != (node.lft(), node.rgt(), node.parent_key())
168                || M::depth_column().is_some_and(|column| *column.get(*node) != rebuilt.depth)
169        })
170        .collect();
171    let keys: Option<Vec<i64>> = changed.iter().map(|(node, _)| integer_key(*node)).collect();
172    match keys {
173        Some(keys) => write_in_batches(&changed, &keys).await?,
174        None => write_one_by_one(&changed).await?,
175    }
176    Ok(changed.len() as u64)
177}
178
179/// The nodes that get each new parent.
180type ByParent<K> = Vec<(Option<K>, Vec<K>)>;
181
182/// Rows per batched `UPDATE`.
183const BATCH: usize = 1_000;
184
185/// Writes integer-keyed rows a thousand at a time: one `UPDATE` with a `CASE` per column for the
186/// bounds and depth, whose SQL holds only integers, and one bound `UPDATE` per new parent.
187async fn write_in_batches<M: NestedSet>(changed: &[(&M, Rebuilt<M::Key>)], keys: &[i64]) -> laravel::Result<()>
188where
189    Option<M::Key>: IntoExpr,
190{
191    let driver = connection::<M>()?.driver();
192    let key = quote(driver, M::META.key.name());
193    for (rows, keys) in changed.chunks(BATCH).zip(keys.chunks(BATCH)) {
194        let case = |value: &dyn Fn(&Rebuilt<M::Key>) -> i64, column: &str| {
195            let mut arms = String::new();
196            for ((_, rebuilt), key) in rows.iter().zip(keys) {
197                let _ = write!(arms, " WHEN {key} THEN {}", value(rebuilt));
198            }
199            let column = quote(driver, column);
200            db::raw!(AssertSqlSafe(format!("CASE {key}{arms} ELSE {column} END")))
201        };
202        let mut values = Values::new()
203            .set(
204                M::lft_column().name(),
205                case(&|rebuilt| rebuilt.lft, M::lft_column().name()),
206            )
207            .set(
208                M::rgt_column().name(),
209                case(&|rebuilt| rebuilt.rgt, M::rgt_column().name()),
210            );
211        if let Some(column) = M::depth_column() {
212            values = values.set(column.name(), case(&|rebuilt| rebuilt.depth, column.name()));
213        }
214        __query::<M>()
215            .filter(M::META.key.is_in(rows.iter().map(|(node, _)| node.node_key().clone())))
216            .update_values(untouched::<M>(values))
217            .await?;
218    }
219
220    let mut by_parent: ByParent<M::Key> = Vec::new();
221    for (node, rebuilt) in changed
222        .iter()
223        .filter(|(node, rebuilt)| rebuilt.parent.as_ref() != node.parent_key())
224    {
225        match by_parent.iter_mut().find(|(parent, _)| *parent == rebuilt.parent) {
226            Some((_, nodes)) => nodes.push(node.node_key().clone()),
227            None => by_parent.push((rebuilt.parent.clone(), vec![node.node_key().clone()])),
228        }
229    }
230    for (parent, nodes) in by_parent {
231        for chunk in nodes.chunks(BATCH) {
232            let values = Values::new().set(M::parent_column().name(), parent.clone());
233            __query::<M>()
234                .filter(M::META.key.is_in(chunk.iter().cloned()))
235                .update_values(untouched::<M>(values))
236                .await?;
237        }
238    }
239    Ok(())
240}
241
242/// Writes each row with its own `UPDATE`, for keys that aren't integers.
243async fn write_one_by_one<M: NestedSet>(changed: &[(&M, Rebuilt<M::Key>)]) -> laravel::Result<()>
244where
245    Option<M::Key>: IntoExpr,
246{
247    for (node, rebuilt) in changed {
248        let mut values = Values::new()
249            .set(M::lft_column().name(), rebuilt.lft)
250            .set(M::rgt_column().name(), rebuilt.rgt)
251            .set(M::parent_column().name(), rebuilt.parent.clone());
252        if let Some(column) = M::depth_column() {
253            values = values.set(column.name(), rebuilt.depth);
254        }
255        __query::<M>()
256            .filter(M::META.key.eq(node.node_key().clone()))
257            .update_values(untouched::<M>(values))
258            .await?;
259    }
260    Ok(())
261}
262
263/// Where a node belongs, as [`rebuild`] works it out.
264struct Rebuilt<K> {
265    lft: i64,
266    rgt: i64,
267    depth: i64,
268    parent: Option<K>,
269}
270
271/// The bounds and parent each node of one tree should have, from `parent_id`. Siblings keep their
272/// current order. A node whose parent is missing, or that sits in a `parent_id` cycle, becomes a
273/// root.
274fn rebuild<'a, M: NestedSet>(nodes: &'a [M], parents: &[Option<M::Key>]) -> Vec<(&'a M, Rebuilt<M::Key>)> {
275    let positions: HashMap<&M::Key, usize> = nodes
276        .iter()
277        .enumerate()
278        .map(|(index, node)| (node.node_key(), index))
279        .collect();
280    let mut children: HashMap<usize, Vec<usize>> = HashMap::new();
281    let mut tops = Vec::new();
282    for (index, parent) in parents.iter().enumerate() {
283        match parent.as_ref().and_then(|parent| positions.get(parent)) {
284            Some(&parent) if parent != index => children.entry(parent).or_default().push(index),
285            _ => tops.push(index),
286        }
287    }
288
289    let mut result = Vec::with_capacity(nodes.len());
290    let mut visited = vec![false; nodes.len()];
291    let mut bound = 0;
292    // Nodes no top reaches sit in a cycle: each one left over starts a tree of its own.
293    let starts: Vec<usize> = tops.into_iter().chain(0..nodes.len()).collect();
294    for start in starts {
295        if visited[start] {
296            continue;
297        }
298        // Depth-first: (node, parent, whether its children are done).
299        let mut stack = vec![(start, None::<usize>, false)];
300        let mut lfts: HashMap<usize, (i64, i64)> = HashMap::new();
301        while let Some((index, parent, done)) = stack.pop() {
302            if done {
303                bound += 1;
304                let parent_key = parent.map(|parent| nodes[parent].node_key().clone());
305                let (lft, depth) = lfts[&index];
306                result.push((
307                    &nodes[index],
308                    Rebuilt {
309                        lft,
310                        rgt: bound,
311                        depth,
312                        parent: parent_key,
313                    },
314                ));
315                continue;
316            }
317            if visited[index] {
318                continue;
319            }
320            visited[index] = true;
321            bound += 1;
322            let depth = parent.map_or(0, |parent| lfts[&parent].1 + 1);
323            lfts.insert(index, (bound, depth));
324            stack.push((index, parent, true));
325            if let Some(below) = children.get(&index) {
326                for &child in below.iter().rev() {
327                    if !visited[child] {
328                        stack.push((child, Some(index), false));
329                    }
330                }
331            }
332        }
333    }
334    result
335}