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