Skip to main content

rustango_cms/page_builder/
model.rs

1//! Page-builder storage models — migration-tracked, versioned.
2//!
3//! No DDL runs when a Developer edits a schema: a structure change writes
4//! a new **draft** row, and publishing flips draft→published (version+1)
5//! while archiving the prior published row. Page values live in one stable
6//! JSON store ([`PageBuilderData`]) and upgrade lazily. Tables are created
7//! once by the generated `0006_page_builder` migration, never altered by
8//! the builder.
9
10use chrono::{DateTime, Utc};
11use rustango::core::Column as _;
12use rustango::sql::{Auto, FetcherPool as _, Pool};
13use rustango::Model;
14use serde::{Deserialize, Serialize};
15use serde_json::Value;
16use std::collections::HashMap;
17
18use crate::page_builder::schema::{ComponentDoc, ComponentEntry};
19
20/// Lifecycle of a schema row. Exactly one `draft` and one `published`
21/// per page type at a time (code-enforced); `archived` rows are history.
22pub const STATUS_DRAFT: &str = "draft";
23pub const STATUS_PUBLISHED: &str = "published";
24pub const STATUS_ARCHIVED: &str = "archived";
25
26/// A versioned body-schema document attached to a page type.
27#[derive(Model, Debug, Clone, Serialize, Deserialize)]
28#[rustango(
29    table = "cms_page_type_schema",
30    app = "cms",
31    display = "status",
32    admin(
33        list_display = "page_type_id, status, version, updated_at",
34        ordering = "page_type_id, version",
35        list_filter = "status",
36    )
37)]
38pub struct PageTypeSchema {
39    #[rustango(primary_key)]
40    pub id: Auto<i64>,
41
42    #[rustango(fk = "cms_page_type", on = "id", index)]
43    pub page_type_id: i64,
44
45    /// `draft` | `published` | `archived`.
46    #[rustango(max_length = 16, index)]
47    pub status: String,
48
49    /// Monotonic per page type; the published version pages record.
50    #[rustango(default = "1")]
51    pub version: i32,
52
53    /// The authored node tree ([`crate::page_builder::schema::Document`]).
54    #[rustango(default = "'{}'::jsonb")]
55    pub document: Value,
56
57    pub created_by: Option<i64>,
58
59    #[rustango(auto_now_add)]
60    pub created_at: Auto<DateTime<Utc>>,
61    #[rustango(auto_now)]
62    pub updated_at: Auto<DateTime<Utc>>,
63}
64
65/// A reusable field-group (a component), referenced from
66/// schemas by slug (`c_<slug>`).
67#[derive(Model, Debug, Clone, Serialize, Deserialize)]
68#[rustango(
69    table = "cms_component",
70    app = "cms",
71    display = "label",
72    admin(
73        list_display = "slug, label, version, updated_at",
74        search_fields = "slug, label",
75        ordering = "slug",
76    )
77)]
78pub struct Component {
79    #[rustango(primary_key)]
80    pub id: Auto<i64>,
81
82    #[rustango(max_length = 100, unique)]
83    pub slug: String,
84
85    #[rustango(max_length = 200)]
86    pub label: String,
87
88    #[rustango(max_length = 80, default = "''")]
89    pub icon: String,
90
91    #[rustango(max_length = 255, default = "''")]
92    pub description: String,
93
94    /// Bumped on every save; stamped onto instances for lazy upgrade.
95    #[rustango(default = "1")]
96    pub version: i32,
97
98    /// [`crate::page_builder::schema::ComponentDoc`].
99    #[rustango(default = "'{}'::jsonb")]
100    pub document: Value,
101
102    #[rustango(auto_now_add)]
103    pub created_at: Auto<DateTime<Utc>>,
104    #[rustango(auto_now)]
105    pub updated_at: Auto<DateTime<Utc>>,
106}
107
108/// The filled builder values for one page (additive to any code page
109/// type's own extension table). One row per page.
110#[derive(Model, Debug, Clone, Serialize, Deserialize)]
111#[rustango(
112    table = "cms_page_builder_data",
113    app = "cms",
114    display = "page_id",
115    admin(
116        list_display = "page_id, schema_version, updated_at",
117        ordering = "page_id"
118    )
119)]
120pub struct PageBuilderData {
121    #[rustango(primary_key)]
122    pub id: Auto<i64>,
123
124    #[rustango(fk = "cms_page", on = "id", unique)]
125    pub page_id: i64,
126
127    /// Published schema version the data was last saved against.
128    #[rustango(default = "0")]
129    pub schema_version: i32,
130
131    /// `{ "<component_slug>": <version> }` snapshot for lazy upgrade.
132    #[rustango(default = "'{}'::jsonb")]
133    pub component_versions: Value,
134
135    /// The filled values (scalars + nested groups + stream arrays +
136    /// `_orphaned`).
137    #[rustango(default = "'{}'::jsonb")]
138    pub data: Value,
139
140    #[rustango(auto_now)]
141    pub updated_at: Auto<DateTime<Utc>>,
142}
143
144// ---- schema row helpers -------------------------------------------------
145
146/// The published schema row for a page type, if any.
147///
148/// # Errors
149/// Propagates query failures.
150pub async fn published_for(
151    pool: &Pool,
152    page_type_id: i64,
153) -> Result<Option<PageTypeSchema>, rustango::sql::ExecError> {
154    PageTypeSchema::objects()
155        .where_(PageTypeSchema::page_type_id.eq(page_type_id))
156        .where_(PageTypeSchema::status.eq(STATUS_PUBLISHED.to_owned()))
157        .first(pool)
158        .await
159}
160
161/// The draft schema row for a page type, if any.
162///
163/// # Errors
164/// Propagates query failures.
165pub async fn draft_for(
166    pool: &Pool,
167    page_type_id: i64,
168) -> Result<Option<PageTypeSchema>, rustango::sql::ExecError> {
169    PageTypeSchema::objects()
170        .where_(PageTypeSchema::page_type_id.eq(page_type_id))
171        .where_(PageTypeSchema::status.eq(STATUS_DRAFT.to_owned()))
172        .first(pool)
173        .await
174}
175
176/// Published + archived rows for a page type, newest version first — the
177/// version history.
178///
179/// # Errors
180/// Propagates query failures.
181pub async fn list_versions(
182    pool: &Pool,
183    page_type_id: i64,
184) -> Result<Vec<PageTypeSchema>, rustango::sql::ExecError> {
185    let mut rows: Vec<PageTypeSchema> = PageTypeSchema::objects()
186        .where_(PageTypeSchema::page_type_id.eq(page_type_id))
187        .fetch(pool)
188        .await?;
189    rows.retain(|r| r.status != STATUS_DRAFT);
190    rows.sort_by(|a, b| b.version.cmp(&a.version));
191    Ok(rows)
192}
193
194/// Upsert the single draft for a page type with `document`. Creates the
195/// draft (version = published+1) if none exists.
196///
197/// # Errors
198/// Propagates query / write failures.
199pub async fn save_draft(
200    pool: &Pool,
201    page_type_id: i64,
202    document: Value,
203    created_by: Option<i64>,
204) -> Result<PageTypeSchema, rustango::sql::ExecError> {
205    if let Some(mut draft) = draft_for(pool, page_type_id).await? {
206        draft.document = document;
207        draft.save(pool).await?;
208        return Ok(draft);
209    }
210    let next = published_for(pool, page_type_id)
211        .await?
212        .map_or(1, |p| p.version + 1);
213    let mut row = PageTypeSchema {
214        id: Auto::Unset,
215        page_type_id,
216        status: STATUS_DRAFT.to_owned(),
217        version: next,
218        document,
219        created_by,
220        created_at: Auto::Unset,
221        updated_at: Auto::Unset,
222    };
223    row.insert(pool).await?;
224    Ok(row)
225}
226
227/// Publish the draft: archive the current published row, flip the draft
228/// to published with version = prev_published + 1. Returns the new
229/// published row, or `None` when there is no draft to publish.
230///
231/// # Errors
232/// Propagates query / write failures.
233pub async fn publish(
234    pool: &Pool,
235    page_type_id: i64,
236) -> Result<Option<PageTypeSchema>, rustango::sql::ExecError> {
237    let Some(mut draft) = draft_for(pool, page_type_id).await? else {
238        return Ok(None);
239    };
240    let prev = published_for(pool, page_type_id).await?;
241    // Archive and flip in one transaction (#649): committed separately, a
242    // failed flip left the old schema archived and no schema published, so
243    // every page of the type rendered an empty builder body. Both rows are
244    // read above, on the pool, before the transaction takes a connection.
245    let mut tx = rustango::sql::transaction_pool(pool).await?;
246    let prev_version = match prev {
247        Some(mut prev) => {
248            prev.status = STATUS_ARCHIVED.to_owned();
249            prev.save_tx(&mut tx).await?;
250            prev.version
251        }
252        None => 0,
253    };
254    draft.status = STATUS_PUBLISHED.to_owned();
255    draft.version = prev_version + 1;
256    draft.save_tx(&mut tx).await?;
257    tx.commit().await?;
258    Ok(Some(draft))
259}
260
261// ---- component helpers --------------------------------------------------
262
263/// Every reusable component, ordered by slug.
264///
265/// # Errors
266/// Propagates query failures.
267pub async fn all_components(pool: &Pool) -> Result<Vec<Component>, rustango::sql::ExecError> {
268    Component::objects()
269        .order_by(&[("slug", false)])
270        .fetch(pool)
271        .await
272}
273
274/// Component library as a `slug → entry` map for [`crate::page_builder::validate_schema`]
275/// / [`crate::page_builder::compile()`]. Malformed component docs are skipped.
276///
277/// # Errors
278/// Propagates query failures.
279pub async fn component_map(
280    pool: &Pool,
281) -> Result<HashMap<String, ComponentEntry>, rustango::sql::ExecError> {
282    let rows = all_components(pool).await?;
283    let mut map = HashMap::new();
284    for c in rows {
285        let doc: ComponentDoc = serde_json::from_value(c.document.clone()).unwrap_or_default();
286        map.insert(
287            c.slug.clone(),
288            ComponentEntry {
289                doc,
290                version: c.version.max(1) as u32,
291            },
292        );
293    }
294    Ok(map)
295}
296
297/// One component by id.
298///
299/// # Errors
300/// Propagates query failures.
301pub async fn component_by_id(
302    pool: &Pool,
303    id: i64,
304) -> Result<Option<Component>, rustango::sql::ExecError> {
305    Component::objects()
306        .where_(Component::id.eq(id))
307        .first(pool)
308        .await
309}
310
311/// Create a component (version 1). `document` is a [`ComponentDoc`] JSON.
312///
313/// # Errors
314/// Propagates the insert failure (incl. the unique-slug violation).
315pub async fn create_component(
316    pool: &Pool,
317    slug: &str,
318    label: &str,
319    icon: &str,
320    description: &str,
321    document: Value,
322) -> Result<Component, rustango::sql::ExecError> {
323    let mut row = Component {
324        id: Auto::Unset,
325        slug: slug.to_owned(),
326        label: label.to_owned(),
327        icon: icon.to_owned(),
328        description: description.to_owned(),
329        version: 1,
330        document,
331        created_at: Auto::Unset,
332        updated_at: Auto::Unset,
333    };
334    row.insert(pool).await?;
335    Ok(row)
336}
337
338/// Update a component's metadata + document and bump its version so
339/// referencing schemas pick the change up lazily (next open / render).
340/// The slug is immutable (it's the reference key).
341///
342/// # Errors
343/// Propagates query / write failures.
344pub async fn update_component(
345    pool: &Pool,
346    id: i64,
347    label: &str,
348    icon: &str,
349    description: &str,
350    document: Value,
351) -> Result<Option<Component>, rustango::sql::ExecError> {
352    let Some(mut row) = component_by_id(pool, id).await? else {
353        return Ok(None);
354    };
355    row.label = label.to_owned();
356    row.icon = icon.to_owned();
357    row.description = description.to_owned();
358    row.document = document;
359    row.version += 1;
360    row.save(pool).await?;
361    Ok(Some(row))
362}
363
364/// Delete a component by id (no-op if it's already gone).
365///
366/// # Errors
367/// Propagates the delete failure.
368pub async fn delete_component(pool: &Pool, id: i64) -> Result<(), rustango::sql::ExecError> {
369    if let Some(row) = component_by_id(pool, id).await? {
370        row.delete(pool).await?;
371    }
372    Ok(())
373}
374
375/// Page types whose non-archived (draft or published) schema references
376/// a component slug — returns `(page_type_id, status)` pairs. Used to
377/// block deletion of an in-use component.
378///
379/// # Errors
380/// Propagates query failures.
381pub async fn component_references(
382    pool: &Pool,
383    slug: &str,
384) -> Result<Vec<(i64, String)>, rustango::sql::ExecError> {
385    let rows: Vec<PageTypeSchema> = PageTypeSchema::objects().fetch(pool).await?;
386    let mut out = Vec::new();
387    for row in rows {
388        if row.status == STATUS_ARCHIVED {
389            continue;
390        }
391        if let Ok(doc) = crate::page_builder::schema::parse(&row.document) {
392            if crate::page_builder::schema::references_component(&doc, slug) {
393                out.push((row.page_type_id, row.status));
394            }
395        }
396    }
397    Ok(out)
398}
399
400/// How many live page-type schemas reference each of `slugs`, from one
401/// scan of the schemas (what [`component_references`] would count, for
402/// every slug at once).
403///
404/// # Errors
405/// Propagates query failures.
406pub async fn component_reference_counts<'a>(
407    pool: &Pool,
408    slugs: &[&'a str],
409) -> Result<HashMap<&'a str, usize>, rustango::sql::ExecError> {
410    let rows: Vec<PageTypeSchema> = PageTypeSchema::objects().fetch(pool).await?;
411    let mut out: HashMap<&'a str, usize> = HashMap::new();
412    for row in rows {
413        if row.status == STATUS_ARCHIVED {
414            continue;
415        }
416        if let Ok(doc) = crate::page_builder::schema::parse(&row.document) {
417            for slug in slugs {
418                if crate::page_builder::schema::references_component(&doc, slug) {
419                    *out.entry(*slug).or_default() += 1;
420                }
421            }
422        }
423    }
424    Ok(out)
425}
426
427// ---- page value helpers -------------------------------------------------
428
429/// The stored builder values for a page, if any.
430///
431/// # Errors
432/// Propagates query failures.
433pub async fn data_for_page(
434    pool: &Pool,
435    page_id: i64,
436) -> Result<Option<PageBuilderData>, rustango::sql::ExecError> {
437    PageBuilderData::objects()
438        .where_(PageBuilderData::page_id.eq(page_id))
439        .first(pool)
440        .await
441}
442
443/// Upsert a page's builder values.
444///
445/// # Errors
446/// Propagates query / write failures.
447pub async fn upsert_data(
448    pool: &Pool,
449    page_id: i64,
450    schema_version: i32,
451    component_versions: Value,
452    data: Value,
453) -> Result<(), rustango::sql::ExecError> {
454    if let Some(mut row) = data_for_page(pool, page_id).await? {
455        row.schema_version = schema_version;
456        row.component_versions = component_versions;
457        row.data = data;
458        row.save(pool).await?;
459    } else {
460        let mut row = PageBuilderData {
461            id: Auto::Unset,
462            page_id,
463            schema_version,
464            component_versions,
465            data,
466            updated_at: Auto::Unset,
467        };
468        row.insert(pool).await?;
469    }
470    Ok(())
471}
472
473#[cfg(all(test, feature = "sqlite"))]
474mod tests {
475    use super::*;
476    use rustango::core::Model as _;
477    use rustango::migrate::ddl::create_table_if_not_exists_sql_with_dialect;
478
479    async fn mem_pool() -> Pool {
480        let pool = Pool::connect("sqlite::memory:").await.expect("mem pool");
481        // Only the schema table is needed for these unit tests (no FK
482        // enforcement target rows involved — page_type_id is a bare int
483        // here; sqlite in-memory has FKs off unless a target exists).
484        for schema in [
485            &crate::page_type_model::PageType::SCHEMA,
486            &PageTypeSchema::SCHEMA,
487            &Component::SCHEMA,
488        ] {
489            let ddl = create_table_if_not_exists_sql_with_dialect(pool.dialect(), schema);
490            for stmt in ddl.split(';').map(str::trim).filter(|s| !s.is_empty()) {
491                rustango::sql::raw_execute_pool(&pool, stmt, Vec::new())
492                    .await
493                    .expect("ddl");
494            }
495        }
496        pool
497    }
498
499    async fn mk_page_type(pool: &Pool, type_name: &str) -> i64 {
500        let mut pt = crate::page_type_model::PageType {
501            id: Auto::Unset,
502            app_label: "cms".to_owned(),
503            type_name: type_name.to_owned(),
504            verbose_name: type_name.to_owned(),
505            default_template: "page.html".to_owned(),
506            view_mode: "auto".to_owned(),
507            is_creatable: true,
508            allowed_parent_types: serde_json::json!([]),
509            allowed_child_types: serde_json::json!([]),
510            workflow: String::new(),
511            created_at: Auto::Unset,
512            updated_at: Auto::Unset,
513        };
514        pt.insert(pool).await.expect("insert page type");
515        pt.id.get().copied().unwrap()
516    }
517
518    #[tokio::test]
519    async fn reference_counts_match_per_slug_lookups() {
520        let pool = mem_pool().await;
521        let a = mk_page_type(&pool, "A").await;
522        let b = mk_page_type(&pool, "B").await;
523        let direct = |slug: &str| serde_json::json!({"nodes": [{"kind": "component", "ref": slug}]});
524        save_draft(&pool, a, direct("cta"), None).await.unwrap();
525        publish(&pool, a).await.unwrap();
526        save_draft(
527            &pool,
528            a,
529            serde_json::json!({"nodes": [{"kind": "flex", "key": "z", "allowed": ["c_cta", "c_hero"]}]}),
530            None,
531        )
532        .await
533        .unwrap();
534        save_draft(&pool, b, direct("hero"), None).await.unwrap();
535        publish(&pool, b).await.unwrap();
536        save_draft(&pool, b, serde_json::json!({"nodes": []}), None).await.unwrap();
537        publish(&pool, b).await.unwrap(); // archives the version naming `hero`
538
539        let slugs = ["cta", "hero", "unused"];
540        let counts = component_reference_counts(&pool, &slugs).await.unwrap();
541        for slug in slugs {
542            let one = component_references(&pool, slug).await.unwrap().len();
543            assert_eq!(counts.get(slug).copied().unwrap_or(0), one, "{slug}");
544        }
545        assert_eq!(counts.get("cta"), Some(&2));
546        assert_eq!(counts.get("hero"), Some(&1));
547    }
548
549    #[tokio::test]
550    async fn draft_publish_versions_flow() {
551        let pool = mem_pool().await;
552        let ptid = mk_page_type(&pool, "Standard").await;
553        // First draft → publish → v1.
554        save_draft(&pool, ptid, serde_json::json!({"nodes": []}), None)
555            .await
556            .unwrap();
557        assert!(draft_for(&pool, ptid).await.unwrap().is_some());
558        let p1 = publish(&pool, ptid).await.unwrap().expect("published");
559        assert_eq!(p1.version, 1);
560        assert_eq!(p1.status, STATUS_PUBLISHED);
561        assert!(
562            draft_for(&pool, ptid).await.unwrap().is_none(),
563            "draft consumed"
564        );
565
566        // Edit → new draft carries v2 preview → publish → v2, v1 archived.
567        let d2 = save_draft(&pool, ptid, serde_json::json!({"nodes": [1]}), None)
568            .await
569            .unwrap();
570        assert_eq!(d2.version, 2);
571        let p2 = publish(&pool, ptid).await.unwrap().expect("published v2");
572        assert_eq!(p2.version, 2);
573        let hist = list_versions(&pool, ptid).await.unwrap();
574        assert_eq!(hist.len(), 2, "v2 published + v1 archived");
575        assert_eq!(hist[0].version, 2);
576        assert_eq!(hist[0].status, STATUS_PUBLISHED);
577        assert_eq!(hist[1].status, STATUS_ARCHIVED);
578
579        // Publish with no draft → None.
580        assert!(publish(&pool, ptid).await.unwrap().is_none());
581    }
582
583    #[tokio::test]
584    async fn re_saving_draft_updates_in_place() {
585        let pool = mem_pool().await;
586        let ptid = mk_page_type(&pool, "Standard").await;
587        save_draft(&pool, ptid, serde_json::json!({"nodes": [1]}), None)
588            .await
589            .unwrap();
590        save_draft(&pool, ptid, serde_json::json!({"nodes": [1, 2]}), None)
591            .await
592            .unwrap();
593        let drafts: Vec<PageTypeSchema> = PageTypeSchema::objects()
594            .where_(PageTypeSchema::page_type_id.eq(ptid))
595            .where_(PageTypeSchema::status.eq(STATUS_DRAFT.to_owned()))
596            .fetch(&pool)
597            .await
598            .unwrap();
599        assert_eq!(drafts.len(), 1, "one draft, updated in place");
600    }
601}