Skip to main content

rustango_cms/
tree_ops.rs

1//! Tree mutation + read API on top of [`Page`].
2//!
3//! All operations are dialect-agnostic. Read-only queries accept
4//! `&rustango::sql::Pool`. Write operations that require atomic
5//! transactions (`create_root`, `create_child`, `move_to`,
6//! `cascade_url_path_to_descendants`) open a `PoolTx` via
7//! `transaction_pool(&tenant.pool())` and use the `_tx` ORM helpers.
8//!
9//! Path generation is two-step: the materialized-path segment is the
10//! row's auto-assigned id, which we don't know until after INSERT. To
11//! avoid the brief window where `path = ""`, every create wraps the
12//! insert + path update in a transaction.
13//!
14//! `move_to` also takes a transaction because it rewrites every row
15//! in the moved subtree atomically.
16//!
17//! `created_at` / `updated_at` are framework-stamped (`auto_now_add`
18//! / `auto_now`); callers don't fill them.
19
20use chrono::Utc;
21use rustango::core::Column as _;
22use rustango::extractors::Tenant;
23use rustango::sql::{
24    sqlx, transaction_pool, Auto, ExecError, FetcherPool as _, FetcherTx as _, Pool, PoolTx,
25};
26
27use crate::page::{Page, PageStatus};
28use crate::page_type::find_handler;
29use crate::page_type_model::PageType;
30use crate::tree::{depth_of, descendants_like, MaterializedPath, PathError};
31
32/// Errors from tree operations.
33#[derive(Debug, thiserror::Error)]
34pub enum TreeError {
35    #[error(transparent)]
36    Db(#[from] ExecError),
37    #[error(transparent)]
38    Sqlx(#[from] sqlx::Error),
39    #[error(transparent)]
40    Path(#[from] PathError),
41    #[error(transparent)]
42    Query(#[from] rustango::core::QueryError),
43    #[error("page id was not assigned after insert")]
44    MissingId,
45    #[error("page {0} not found")]
46    NotFound(i64),
47    #[error("cms_page_type row {0} not found — has `ensure_seeded` run for this tenant?")]
48    UnknownPageType(i64),
49    #[error("cannot move a page beneath itself or its own descendant")]
50    CycleAttempt,
51    #[error(
52        "page-type `{child_type}` is not in `{parent_type}.allowed_child_types` — \
53         parent refuses this child"
54    )]
55    DisallowedChildType {
56        parent_type: String,
57        child_type: String,
58    },
59    #[error(
60        "page-type `{child_type}.allowed_parent_types` does not include \
61         `{parent_type}` — child refuses this parent"
62    )]
63    DisallowedParentType {
64        parent_type: String,
65        child_type: String,
66    },
67}
68
69/// Run `f` inside a framework [`rustango::sql::atomic`] scope while
70/// letting it return [`TreeError`] — the bridge that lets the
71/// `on_commit` cache-invalidation pattern reach the tree-write paths.
72///
73/// `rustango::sql::atomic` fixes its closure's error to [`ExecError`],
74/// but the tree helpers (`cascade_url_path_to_descendants`, `move_to`,
75/// …) speak `TreeError`, and there's no `TreeError -> ExecError`
76/// conversion (only the reverse, via [`TreeError::Db`]). This adapter
77/// closes that gap: a `TreeError` from `f` is stashed and a sentinel
78/// `ExecError` is returned to drive `atomic`'s rollback, then the real
79/// error is recovered afterwards. Recovery keys off the **stash**, not
80/// the sentinel value, so a genuine `ExecError` raised by `BEGIN` /
81/// `COMMIT` itself is never misread as a domain error.
82///
83/// `on_commit` callbacks queued by `f` (e.g. via
84/// [`crate::cache_invalidate::invalidate_urls_on_commit`]) fire only on
85/// the commit path — a `TreeError` rolls the transaction back and drops
86/// them, exactly like a native `atomic` block.
87///
88/// The cleaner long-term fix is a generic `atomic` in the framework
89/// (closure returning `Result<T, E: From<ExecError>>`); until that
90/// lands, this adapter keeps the rollout unblocked.
91///
92/// # Errors
93/// The first [`TreeError`] returned by `f`, or a `BEGIN` / `COMMIT`
94/// driver error surfaced as [`TreeError::Db`].
95pub async fn atomic_tree<T, F>(pool: &Pool, f: F) -> Result<T, TreeError>
96where
97    T: Send + 'static,
98    F: Send
99        + 'static
100        + for<'tx> FnOnce(
101            &'tx mut PoolTx<'_>,
102        ) -> std::pin::Pin<
103            Box<dyn std::future::Future<Output = Result<T, TreeError>> + Send + 'tx>,
104        >,
105{
106    let stash: std::sync::Arc<std::sync::Mutex<Option<TreeError>>> =
107        std::sync::Arc::new(std::sync::Mutex::new(None));
108    let stash_cb = std::sync::Arc::clone(&stash);
109    let out = rustango::sql::atomic(pool, move |tx| {
110        Box::pin(async move {
111            let mut guard = tx.lock().await?;
112            match f(&mut guard).await {
113                Ok(v) => Ok(v),
114                Err(e) => {
115                    *stash_cb.lock().expect("atomic_tree stash poisoned") = Some(e);
116                    // Sentinel: any ExecError drives atomic's rollback;
117                    // the value is never read (recovery uses the stash).
118                    Err(ExecError::EmptyReturning)
119                }
120            }
121        })
122    })
123    .await;
124    match out {
125        Ok(v) => Ok(v),
126        Err(commit_err) => {
127            let domain = stash.lock().expect("atomic_tree stash poisoned").take();
128            Err(domain.unwrap_or(TreeError::Db(commit_err)))
129        }
130    }
131}
132
133/// Builder for the user-supplied fields when creating a page. Tree
134/// fields (path, depth, parent_id, sort_order) and timestamps are
135/// computed by the create_* helpers — callers don't fill them.
136#[derive(Debug, Clone)]
137pub struct NewPage {
138    pub page_type_id: i64,
139    pub title: String,
140    pub slug: String,
141    pub status: PageStatus,
142    pub seo_title: String,
143    pub seo_description: String,
144}
145
146impl NewPage {
147    pub fn new(page_type_id: i64, title: impl Into<String>, slug: impl Into<String>) -> Self {
148        Self {
149            page_type_id,
150            title: title.into(),
151            slug: slug.into(),
152            status: PageStatus::Draft,
153            seo_title: String::new(),
154            seo_description: String::new(),
155        }
156    }
157
158    pub fn with_status(mut self, status: PageStatus) -> Self {
159        self.status = status;
160        self
161    }
162
163    pub fn with_seo(mut self, title: impl Into<String>, description: impl Into<String>) -> Self {
164        self.seo_title = title.into();
165        self.seo_description = description.into();
166        self
167    }
168
169    fn into_page(self, parent_id: Option<i64>, sort_order: i32) -> Page {
170        let published_at = matches!(self.status, PageStatus::Published).then(Utc::now);
171        // #251 — first_published_at + last_published_at mirror on
172        // first publish (same instant). Subsequent edits bump only
173        // `last_published_at`; `published_at` stays as the
174        // chronological-ordering anchor.
175        let last_published_at = published_at;
176        Page {
177            id: Auto::Unset,
178            page_type_id: self.page_type_id,
179            title: self.title,
180            slug: self.slug,
181            path: String::new(),
182            url_path: String::new(),
183            // Empty means "follow url_path" — a new page inherits the
184            // frontend's default routing until someone says otherwise.
185            preview_path: String::new(),
186            // Empty means "use the page type's template" — a new page
187            // looks like its type until someone overrides it.
188            template_override: String::new(),
189            depth: 0,
190            parent_id,
191            locale_variant_of: None,
192            alias_of: None,
193            theme_id: None,
194            sort_order,
195            status: self.status.as_str().to_owned(),
196            published_at,
197            last_published_at,
198            go_live_at: None,
199            expire_at: None,
200            seo_title: self.seo_title,
201            seo_description: self.seo_description,
202            robots_index: true,
203            sitemap_priority: 0.5,
204            show_in_menus: false,
205            og_title: String::new(),
206            og_description: String::new(),
207            og_image_media_id: None,
208            twitter_card: "summary_large_image".to_owned(),
209            notification_pre_published_sent: false,
210            created_at: Auto::Unset,
211            updated_at: Auto::Unset,
212        }
213    }
214}
215
216/// Compute the public URL path a page is reachable at,
217/// given its parent's `url_path` (or `None` for root) and its own
218/// slug. Maintained on every create / slug-change / move.
219///
220/// Invariants:
221/// - Always starts with `/`.
222/// - No trailing slash, except for the empty-slug root which is `/`.
223/// - Empty slug under a non-root parent is treated as "use parent's
224///   path" (rare but useful for landing pages that share a parent's
225///   URL). Use sparingly — the resolver picks the highest-priority
226///   match among equal URLs.
227pub fn compute_url_path(parent_url_path: Option<&str>, slug: &str) -> String {
228    match parent_url_path {
229        None => {
230            // Root page.
231            if slug.is_empty() {
232                "/".to_owned()
233            } else {
234                format!("/{slug}")
235            }
236        }
237        Some(parent) => {
238            if slug.is_empty() {
239                parent.to_owned()
240            } else if parent == "/" {
241                format!("/{slug}")
242            } else {
243                format!("{parent}/{slug}")
244            }
245        }
246    }
247}
248
249/// Recompute and persist `url_path` for every
250/// descendant of `root_page` after its own `url_path` changes.
251///
252/// Walks in path order so each descendant's parent has been updated
253/// before the descendant itself is processed. Caches each updated
254/// `(id → url_path)` in-memory to avoid re-fetching parents. Runs
255/// inside `conn` so callers can wrap the whole self-edit + cascade
256/// in one transaction.
257///
258/// # Errors
259/// Driver / query failures or ORM save errors.
260pub async fn cascade_url_path_to_descendants(
261    tx: &mut PoolTx<'_>,
262    root_page: &Page,
263) -> Result<usize, TreeError> {
264    let root_id = page_id(root_page)?;
265    let pattern = descendants_like(&root_page.path);
266    let descendants: Vec<Page> = Page::objects()
267        .where_(Page::path.like(pattern))
268        .where_(Page::path.ne(root_page.path.clone()))
269        .order_by(&[("path", false)])
270        .fetch_tx(tx)
271        .await?;
272
273    let mut by_id: std::collections::HashMap<i64, String> = std::collections::HashMap::new();
274    by_id.insert(root_id, root_page.url_path.clone());
275
276    let mut updated = 0usize;
277    for mut d in descendants {
278        let Some(parent_id) = d.parent_id else {
279            continue;
280        };
281        let parent_url_path = by_id.get(&parent_id).cloned().unwrap_or_default();
282        let new_url = compute_url_path(Some(parent_url_path.as_str()), &d.slug);
283        if d.url_path == new_url {
284            let did = d.id.get().copied().unwrap_or_default();
285            by_id.insert(did, new_url);
286            continue;
287        }
288        d.url_path = new_url.clone();
289        let did = d.id.get().copied().unwrap_or_default();
290        by_id.insert(did, new_url);
291        d.save_tx(tx).await?;
292        updated += 1;
293    }
294    Ok(updated)
295}
296
297/// Recompute `url_path` for every page in the tenant
298/// from scratch. Walks all pages in `path` order so parents update
299/// before children. Useful as a one-shot recovery / backfill verb
300/// when external SQL has touched `cms_page` outside the admin.
301///
302/// # Errors
303/// Driver / query failures or ORM save errors.
304pub async fn rebuild_all_url_paths(pool: &Pool) -> Result<usize, TreeError> {
305    // #317 — stream pages in `path` order (a materialized path sorts
306    // parents before their children) in chunks rather than materializing
307    // every `Page` row up front: a 10k+ page tenant would otherwise
308    // buffer the entire tree of full Page structs in memory at once.
309    // Each page is only needed transiently to recompute its `url_path`;
310    // the sole cross-row state is the compact id→url_path map for parent
311    // lookups, so chunked iteration keeps peak memory bounded to one
312    // chunk + that map. Recomputing `url_path` never mutates `path` (the
313    // ORDER BY / cursor key), so the LIMIT/OFFSET window stays stable
314    // across chunks — no row is skipped or visited twice.
315    let mut iter = Page::objects()
316        .order_by(&[("path", false)])
317        .iterator(2_000)?;
318
319    let mut by_id: std::collections::HashMap<i64, String> = std::collections::HashMap::new();
320    let mut updated = 0usize;
321    while let Some(mut p) = iter.next_row(pool).await? {
322        let id = page_id(&p)?;
323        let new_url = match p.parent_id {
324            None => compute_url_path(None, &p.slug),
325            Some(parent_id) => {
326                let parent_url = by_id.get(&parent_id).cloned().unwrap_or_default();
327                compute_url_path(Some(parent_url.as_str()), &p.slug)
328            }
329        };
330        if p.url_path != new_url {
331            p.url_path = new_url.clone();
332            p.save_pool(pool).await?;
333            updated += 1;
334        }
335        by_id.insert(id, new_url);
336    }
337    Ok(updated)
338}
339
340impl Page {
341    /// Insert a new root page. Returns the persisted row with `id`,
342    /// `path`, `depth`, and `sort_order` populated.
343    pub async fn create_root(tenant: &Tenant, new: NewPage) -> Result<Self, TreeError> {
344        Self::create_root_pool(tenant.pool(), new).await
345    }
346
347    /// Backend-agnostic [`Self::create_root`] — takes a `&Pool` directly,
348    /// so content can be seeded / scripted outside an HTTP request on any
349    /// dialect. `create_root` needs a `&Tenant`, but `Tenant` is only
350    /// publicly constructible on Postgres (test-gated), leaving no way to
351    /// seed pages on SQLite/MySQL; this is that way.
352    pub async fn create_root_pool(pool: &Pool, new: NewPage) -> Result<Self, TreeError> {
353        let mut tx = transaction_pool(pool).await?;
354        // #317 — compute sort_order inside the tx under a FOR UPDATE lock
355        // on the existing roots so concurrent root inserts can't read the
356        // same max and collide.
357        let sort_order = next_root_sort_order_tx(&mut tx).await?;
358        let mut page = new.into_page(None, sort_order);
359
360        page.insert_tx(&mut tx).await?;
361        let id = page_id(&page)?;
362
363        let path = MaterializedPath::root(id)?;
364        page.path = path.into_string();
365        page.depth = 1;
366        page.url_path = compute_url_path(None, &page.slug);
367        page.save_tx(&mut tx).await?;
368        tx.commit().await?;
369
370        Ok(page)
371    }
372
373    /// Append a new child under `parent`. Sort order is the next
374    /// integer after the parent's existing children.
375    ///
376    /// Validates the type constraint in both directions before
377    /// inserting: the parent's `allowed_child_types` must permit
378    /// the child's type, and the child's `allowed_parent_types`
379    /// must permit the parent's type. Either failure short-circuits
380    /// the write.
381    pub async fn create_child(
382        tenant: &Tenant,
383        parent: &Page,
384        new: NewPage,
385    ) -> Result<Self, TreeError> {
386        Self::create_child_pool(tenant.pool(), parent, new).await
387    }
388
389    /// Backend-agnostic [`Self::create_child`] — takes a `&Pool` directly
390    /// so content can be seeded / scripted outside an HTTP request on any
391    /// dialect (see [`Self::create_root_pool`]).
392    pub async fn create_child_pool(
393        pool: &Pool,
394        parent: &Page,
395        new: NewPage,
396    ) -> Result<Self, TreeError> {
397        let parent_id = page_id(parent)?;
398        validate_child_placement(pool, parent.page_type_id, new.page_type_id).await?;
399
400        let mut tx = transaction_pool(pool).await?;
401        // #317 — serialize concurrent inserts under this parent. Lock the
402        // parent row (FOR UPDATE) so a second create_child blocks until
403        // the first commits; otherwise both read the same
404        // MAX(sort_order) and write duplicate sort_orders. Locking the
405        // parent (not the sibling set) covers the first child too, when
406        // there are no siblings to lock. The lock is held for the whole
407        // tx — dropping the result Vec doesn't release it. No-op on
408        // SQLite (no row locks; writers serialize anyway).
409        let _locked_parent: Vec<Page> = Page::objects()
410            .where_(Page::id.eq(parent_id))
411            .select_for_update()
412            .fetch_tx(&mut tx)
413            .await?;
414        let sort_order = next_child_sort_order_tx(&mut tx, parent_id).await?;
415        let mut page = new.into_page(Some(parent_id), sort_order);
416
417        page.insert_tx(&mut tx).await?;
418        let id = page_id(&page)?;
419
420        let path = MaterializedPath::child_of(&parent.path, id)?;
421        page.depth = path.depth();
422        page.path = path.into_string();
423        page.url_path = compute_url_path(Some(parent.url_path.as_str()), &page.slug);
424        page.save_tx(&mut tx).await?;
425        tx.commit().await?;
426
427        Ok(page)
428    }
429
430    /// Immediate children, ordered by `sort_order`.
431    pub async fn children(&self, pool: &Pool) -> Result<Vec<Page>, TreeError> {
432        let id = page_id(self)?;
433        let rows = Page::objects()
434            .where_(Page::parent_id.eq(id))
435            .order_by(&[("sort_order", false), ("id", false)])
436            .fetch(pool)
437            .await?;
438        Ok(rows)
439    }
440
441    /// Pages that share this page's parent (excluding self), ordered
442    /// by `sort_order`. Roots return all other roots.
443    pub async fn siblings(&self, pool: &Pool) -> Result<Vec<Page>, TreeError> {
444        let id = page_id(self)?;
445        let qs = Page::objects().order_by(&[("sort_order", false), ("id", false)]);
446        let rows = match self.parent_id {
447            Some(pid) => qs.where_(Page::parent_id.eq(pid)).fetch(pool).await?,
448            None => qs.where_(Page::parent_id.is_null()).fetch(pool).await?,
449        };
450        Ok(rows
451            .into_iter()
452            .filter(|p| p.id.get().copied() != Some(id))
453            .collect())
454    }
455
456    /// All ancestors of this page from root → immediate parent.
457    /// Empty for roots. Order is root-first.
458    pub async fn ancestors(&self, pool: &Pool) -> Result<Vec<Page>, TreeError> {
459        let paths = MaterializedPath::ancestors_of(&self.path);
460        if paths.is_empty() {
461            return Ok(Vec::new());
462        }
463        let mut rows = Page::objects()
464            .where_(Page::path.is_in(paths.iter().cloned()))
465            .order_by(&[("path", false)])
466            .fetch(pool)
467            .await?;
468        rows.sort_by(|a, b| a.path.cmp(&b.path));
469        Ok(rows)
470    }
471
472    /// All descendants (excluding self), ordered by `path` (which is
473    /// also tree-pre-order).
474    pub async fn descendants(&self, pool: &Pool) -> Result<Vec<Page>, TreeError> {
475        let pattern = descendants_like(&self.path);
476        let rows = Page::objects()
477            .where_(Page::path.like(pattern))
478            .where_(Page::path.ne(self.path.clone()))
479            .order_by(&[("path", false)])
480            .fetch(pool)
481            .await?;
482        Ok(rows)
483    }
484
485    /// Move this page (and its entire subtree) under `new_parent`. Pass
486    /// `None` to promote it to a root. The subtree's `url_path`s follow in
487    /// the same transaction, so the tree and the URLs never disagree.
488    ///
489    /// Refuses cycles (moving under self or a descendant) and
490    /// type-constraint violations (re-checks both directions against
491    /// the new parent before writing).
492    pub async fn move_to(
493        &mut self,
494        tenant: &Tenant,
495        new_parent: Option<&Page>,
496    ) -> Result<(), TreeError> {
497        let self_id = page_id(self)?;
498
499        if let Some(np) = new_parent {
500            let np_id = page_id(np)?;
501            if np_id == self_id || np.path.starts_with(&self.path) {
502                return Err(TreeError::CycleAttempt);
503            }
504            validate_child_placement(tenant.pool(), np.page_type_id, self.page_type_id).await?;
505        }
506
507        let new_id_path = match new_parent {
508            Some(np) => MaterializedPath::child_of(&np.path, self_id)?.into_string(),
509            None => MaterializedPath::root(self_id)?.into_string(),
510        };
511        if new_id_path == self.path {
512            return Ok(());
513        }
514
515        let subtree = self.descendants(tenant.pool()).await?;
516        let mut tx = transaction_pool(tenant.pool()).await?;
517        self.move_to_in_tx(new_parent, subtree, &mut tx).await?;
518        tx.commit().await?;
519        Ok(())
520    }
521
522    /// Transaction-scoped core of [`move_to`](Self::move_to). Assumes cycle / placement
523    /// validation has already run and `subtree` (this page's descendants)
524    /// was read on the pool **before** the transaction opened — so this
525    /// makes **no pool reads**. That matters: reading the pool while
526    /// holding a tx connection can deadlock a single-connection SQLite
527    /// pool. Pre-reading lets a batch (bulk move) reparent many pages in
528    /// one transaction.
529    ///
530    /// # Errors
531    /// Driver errors from the lock / saves, or [`TreeError`] from path
532    /// math.
533    pub async fn move_to_in_tx(
534        &mut self,
535        new_parent: Option<&Page>,
536        subtree: Vec<Page>,
537        tx: &mut PoolTx<'_>,
538    ) -> Result<(), TreeError> {
539        let self_id = page_id(self)?;
540        let new_id_path = match new_parent {
541            Some(np) => MaterializedPath::child_of(&np.path, self_id)?.into_string(),
542            None => MaterializedPath::root(self_id)?.into_string(),
543        };
544        if new_id_path == self.path {
545            return Ok(());
546        }
547        let old_prefix = self.path.clone();
548
549        // #317 — compute the destination sort_order inside the tx, under a
550        // FOR UPDATE lock on the new parent row (or the roots set when
551        // promoting to a root), so a concurrent insert/move into the same
552        // parent can't hand out a duplicate sort_order.
553        let new_sort_order = match new_parent {
554            Some(np) => {
555                let np_id = page_id(np)?;
556                let _locked_parent: Vec<Page> = Page::objects()
557                    .where_(Page::id.eq(np_id))
558                    .select_for_update()
559                    .fetch_tx(tx)
560                    .await?;
561                next_child_sort_order_tx(tx, np_id).await?
562            }
563            None => next_root_sort_order_tx(tx).await?,
564        };
565
566        self.parent_id = new_parent.and_then(|p| p.id.get().copied());
567        self.sort_order = new_sort_order;
568        self.depth = depth_of(&new_id_path);
569        self.path = new_id_path.clone();
570        // #706 — the URL moves with the tree, in this transaction. It used
571        // to be left to the admin handler, in a second transaction a
572        // library caller never ran, so a moved subtree kept its old URLs.
573        self.url_path = compute_url_path(new_parent.map(|p| p.url_path.as_str()), &self.slug);
574        self.save_tx(tx).await?;
575
576        // `subtree` is in path order, so a parent's new URL is known
577        // before its children's.
578        let mut url_of: std::collections::HashMap<i64, String> = std::collections::HashMap::new();
579        url_of.insert(self_id, self.url_path.clone());
580        for mut row in subtree {
581            let suffix = row
582                .path
583                .strip_prefix(&old_prefix)
584                .expect("descendant path must start with old prefix");
585            row.path = format!("{new_id_path}{suffix}");
586            row.depth = depth_of(&row.path);
587            let parent_url = row.parent_id.and_then(|pid| url_of.get(&pid).cloned());
588            row.url_path = compute_url_path(parent_url.as_deref(), &row.slug);
589            if let Some(id) = row.id.get().copied() {
590                url_of.insert(id, row.url_path.clone());
591            }
592            row.save_tx(tx).await?;
593        }
594        Ok(())
595    }
596}
597
598// ---------- helpers ----------
599
600fn page_id(page: &Page) -> Result<i64, TreeError> {
601    page.id.get().copied().ok_or(TreeError::MissingId)
602}
603
604/// Next `sort_order` for a new root, read inside `tx` after taking a
605/// `FOR UPDATE` lock on **one** deterministic root row (the lowest id) so
606/// concurrent root inserts serialize.
607///
608/// Roots have no parent row to lock, but we must NOT lock the whole roots
609/// set: concurrent transactions acquire the multiple row locks in
610/// conflicting orders and PG aborts one with a deadlock (40P01). Locking a
611/// single, always-the-same row (lowest id) can't deadlock — every tx
612/// contends on that one row — mirroring `create_child`'s single-parent
613/// lock. The subsequent max read is serialized by that lock.
614///
615/// Empty roots → nothing to lock → a narrow gap when the first couple of
616/// roots are created concurrently (rare; acceptable). `FOR UPDATE` is a
617/// no-op on SQLite, which serializes writers via its implicit tx lock.
618async fn next_root_sort_order_tx(tx: &mut PoolTx<'_>) -> Result<i32, TreeError> {
619    let _lock: Vec<Page> = Page::objects()
620        .where_(Page::parent_id.is_null())
621        .order_by(&[("id", false)])
622        .limit(1)
623        .select_for_update()
624        .fetch_tx(tx)
625        .await?;
626    let rows = Page::objects()
627        .where_(Page::parent_id.is_null())
628        .order_by(&[("sort_order", true)])
629        .fetch_tx(tx)
630        .await?;
631    Ok(rows.first().map(|p| p.sort_order + 1).unwrap_or(0))
632}
633
634/// Next `sort_order` for a new child of `parent_id`, read inside `tx`.
635/// The caller locks the parent row with `FOR UPDATE` first (see
636/// [`Page::create_child`]), which serializes every insert under that
637/// parent — including the first child, when no siblings exist to lock —
638/// so this is a plain read of the current max.
639async fn next_child_sort_order_tx(tx: &mut PoolTx<'_>, parent_id: i64) -> Result<i32, TreeError> {
640    let rows = Page::objects()
641        .where_(Page::parent_id.eq(parent_id))
642        .order_by(&[("sort_order", true)])
643        .fetch_tx(tx)
644        .await?;
645    Ok(rows.first().map(|p| p.sort_order + 1).unwrap_or(0))
646}
647
648/// Check that the (parent_type, child_type) pairing is permitted by
649/// both handlers' whitelists. Skipped when either type's whitelist is
650/// empty (the convention for "no restriction"). Public to make it
651/// usable from admin form hooks and other write paths.
652///
653/// Fetches both `cms_page_type` rows in a single `WHERE id IN (..)`
654/// query, then dispatches to the in-process handler registry for the
655/// declared whitelists.
656///
657/// # Errors
658/// * [`TreeError::UnknownPageType`] when either id doesn't resolve to
659///   a `cms_page_type` row.
660/// * [`TreeError::DisallowedChildType`] when the parent rejects.
661/// * [`TreeError::DisallowedParentType`] when the child rejects.
662pub async fn validate_child_placement(
663    pool: &Pool,
664    parent_type_id: i64,
665    child_type_id: i64,
666) -> Result<(), TreeError> {
667    let rows: Vec<PageType> = PageType::objects()
668        .where_(PageType::id.is_in([parent_type_id, child_type_id]))
669        .fetch(pool)
670        .await?;
671
672    let parent = rows
673        .iter()
674        .find(|r| r.id.get().copied() == Some(parent_type_id))
675        .ok_or(TreeError::UnknownPageType(parent_type_id))?;
676    let child = rows
677        .iter()
678        .find(|r| r.id.get().copied() == Some(child_type_id))
679        .ok_or(TreeError::UnknownPageType(child_type_id))?;
680
681    // #448 — a leaf type (code only) accepts no children at all.
682    if find_handler(&parent.type_name).is_some_and(|h| h.is_leaf()) {
683        return Err(TreeError::DisallowedChildType {
684            parent_type: parent.type_name.clone(),
685            child_type: child.type_name.clone(),
686        });
687    }
688    // The rows hold both lists for code and admin-made types alike (#843).
689    let allowed = parent.allowed_children();
690    if !allowed.is_empty() && !allowed.iter().any(|t| *t == child.type_name) {
691        return Err(TreeError::DisallowedChildType {
692            parent_type: parent.type_name.clone(),
693            child_type: child.type_name.clone(),
694        });
695    }
696    let allowed = child.allowed_parents();
697    if !allowed.is_empty() && !allowed.iter().any(|t| *t == parent.type_name) {
698        return Err(TreeError::DisallowedParentType {
699            parent_type: parent.type_name.clone(),
700            child_type: child.type_name.clone(),
701        });
702    }
703
704    Ok(())
705}
706
707// MaterializedPath::ancestors() returns Vec<String>; we want a static-style
708// helper available without an instance for the `ancestors` query above.
709impl MaterializedPath {
710    pub fn ancestors_of(path: &str) -> Vec<String> {
711        let mut out = Vec::new();
712        let mut acc = String::new();
713        for seg in path.split(crate::tree::SEPARATOR).filter(|s| !s.is_empty()) {
714            acc.push_str(seg);
715            acc.push(crate::tree::SEPARATOR);
716            if acc != path {
717                out.push(acc.clone());
718            }
719        }
720        if let Some(last) = out.last() {
721            if last == path {
722                out.pop();
723            }
724        }
725        out
726    }
727}
728
729// `atomic_tree`'s commit/rollback behavior is exercised against a
730// serverless SQLite-in-memory pool, so it's gated on the `sqlite`
731// feature:
732//   cargo test --lib --no-default-features --features sqlite atomic_tree
733#[cfg(all(test, feature = "sqlite"))]
734mod atomic_tree_tests {
735    use super::*;
736    use rustango::sql::Pool;
737    use std::sync::atomic::{AtomicBool, Ordering};
738    use std::sync::Arc;
739
740    async fn mem_pool() -> Pool {
741        Pool::connect("sqlite::memory:")
742            .await
743            .expect("sqlite in-memory pool")
744    }
745
746    #[tokio::test]
747    async fn commit_returns_value_and_fires_on_commit() {
748        let pool = mem_pool().await;
749        let fired = Arc::new(AtomicBool::new(false));
750        let f = fired.clone();
751        let out = atomic_tree(&pool, move |_tx| {
752            Box::pin(async move {
753                rustango::sql::on_commit(move || f.store(true, Ordering::SeqCst));
754                Ok::<i32, TreeError>(7)
755            })
756        })
757        .await;
758        assert_eq!(out.expect("commit"), 7);
759        // on_commit callbacks drain synchronously after COMMIT, before
760        // `atomic` returns — so the flag is already set here.
761        assert!(
762            fired.load(Ordering::SeqCst),
763            "on_commit must fire on commit"
764        );
765    }
766
767    #[tokio::test]
768    async fn tree_error_propagates_unchanged_and_drops_on_commit() {
769        let pool = mem_pool().await;
770        let fired = Arc::new(AtomicBool::new(false));
771        let f = fired.clone();
772        let out: Result<(), TreeError> = atomic_tree(&pool, move |_tx| {
773            Box::pin(async move {
774                rustango::sql::on_commit(move || f.store(true, Ordering::SeqCst));
775                Err(TreeError::CycleAttempt)
776            })
777        })
778        .await;
779        // The original `TreeError` is recovered from the stash — not the
780        // `ExecError` sentinel (which would surface as `TreeError::Db`).
781        assert!(matches!(out, Err(TreeError::CycleAttempt)), "got {out:?}");
782        assert!(
783            !fired.load(Ordering::SeqCst),
784            "on_commit must be dropped on a TreeError rollback"
785        );
786    }
787}