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(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(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(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(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(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// ---- page value helpers -------------------------------------------------
401
402/// The stored builder values for a page, if any.
403///
404/// # Errors
405/// Propagates query failures.
406pub async fn data_for_page(
407    pool: &Pool,
408    page_id: i64,
409) -> Result<Option<PageBuilderData>, rustango::sql::ExecError> {
410    PageBuilderData::objects()
411        .where_(PageBuilderData::page_id.eq(page_id))
412        .first(pool)
413        .await
414}
415
416/// Upsert a page's builder values.
417///
418/// # Errors
419/// Propagates query / write failures.
420pub async fn upsert_data(
421    pool: &Pool,
422    page_id: i64,
423    schema_version: i32,
424    component_versions: Value,
425    data: Value,
426) -> Result<(), rustango::sql::ExecError> {
427    if let Some(mut row) = data_for_page(pool, page_id).await? {
428        row.schema_version = schema_version;
429        row.component_versions = component_versions;
430        row.data = data;
431        row.save_pool(pool).await?;
432    } else {
433        let mut row = PageBuilderData {
434            id: Auto::Unset,
435            page_id,
436            schema_version,
437            component_versions,
438            data,
439            updated_at: Auto::Unset,
440        };
441        row.insert_pool(pool).await?;
442    }
443    Ok(())
444}
445
446#[cfg(all(test, feature = "sqlite"))]
447mod tests {
448    use super::*;
449    use rustango::core::Model as _;
450    use rustango::migrate::ddl::create_table_if_not_exists_sql_with_dialect;
451
452    async fn mem_pool() -> Pool {
453        let pool = Pool::connect("sqlite::memory:").await.expect("mem pool");
454        // Only the schema table is needed for these unit tests (no FK
455        // enforcement target rows involved — page_type_id is a bare int
456        // here; sqlite in-memory has FKs off unless a target exists).
457        for schema in [
458            &crate::page_type_model::PageType::SCHEMA,
459            &PageTypeSchema::SCHEMA,
460            &Component::SCHEMA,
461        ] {
462            let ddl = create_table_if_not_exists_sql_with_dialect(pool.dialect(), schema);
463            for stmt in ddl.split(';').map(str::trim).filter(|s| !s.is_empty()) {
464                rustango::sql::raw_execute_pool(&pool, stmt, Vec::new())
465                    .await
466                    .expect("ddl");
467            }
468        }
469        pool
470    }
471
472    async fn mk_page_type(pool: &Pool, type_name: &str) -> i64 {
473        let mut pt = crate::page_type_model::PageType {
474            id: Auto::Unset,
475            app_label: "cms".to_owned(),
476            type_name: type_name.to_owned(),
477            verbose_name: type_name.to_owned(),
478            default_template: "page.html".to_owned(),
479            view_mode: "auto".to_owned(),
480            is_creatable: true,
481            allowed_parent_types: serde_json::json!([]),
482            allowed_child_types: serde_json::json!([]),
483            workflow: String::new(),
484            created_at: Auto::Unset,
485            updated_at: Auto::Unset,
486        };
487        pt.insert_pool(pool).await.expect("insert page type");
488        pt.id.get().copied().unwrap()
489    }
490
491    #[tokio::test]
492    async fn draft_publish_versions_flow() {
493        let pool = mem_pool().await;
494        let ptid = mk_page_type(&pool, "Standard").await;
495        // First draft → publish → v1.
496        save_draft(&pool, ptid, serde_json::json!({"nodes": []}), None)
497            .await
498            .unwrap();
499        assert!(draft_for(&pool, ptid).await.unwrap().is_some());
500        let p1 = publish(&pool, ptid).await.unwrap().expect("published");
501        assert_eq!(p1.version, 1);
502        assert_eq!(p1.status, STATUS_PUBLISHED);
503        assert!(
504            draft_for(&pool, ptid).await.unwrap().is_none(),
505            "draft consumed"
506        );
507
508        // Edit → new draft carries v2 preview → publish → v2, v1 archived.
509        let d2 = save_draft(&pool, ptid, serde_json::json!({"nodes": [1]}), None)
510            .await
511            .unwrap();
512        assert_eq!(d2.version, 2);
513        let p2 = publish(&pool, ptid).await.unwrap().expect("published v2");
514        assert_eq!(p2.version, 2);
515        let hist = list_versions(&pool, ptid).await.unwrap();
516        assert_eq!(hist.len(), 2, "v2 published + v1 archived");
517        assert_eq!(hist[0].version, 2);
518        assert_eq!(hist[0].status, STATUS_PUBLISHED);
519        assert_eq!(hist[1].status, STATUS_ARCHIVED);
520
521        // Publish with no draft → None.
522        assert!(publish(&pool, ptid).await.unwrap().is_none());
523    }
524
525    #[tokio::test]
526    async fn re_saving_draft_updates_in_place() {
527        let pool = mem_pool().await;
528        let ptid = mk_page_type(&pool, "Standard").await;
529        save_draft(&pool, ptid, serde_json::json!({"nodes": [1]}), None)
530            .await
531            .unwrap();
532        save_draft(&pool, ptid, serde_json::json!({"nodes": [1, 2]}), None)
533            .await
534            .unwrap();
535        let drafts: Vec<PageTypeSchema> = PageTypeSchema::objects()
536            .where_(PageTypeSchema::page_type_id.eq(ptid))
537            .where_(PageTypeSchema::status.eq(STATUS_DRAFT.to_owned()))
538            .fetch(&pool)
539            .await
540            .unwrap();
541        assert_eq!(drafts.len(), 1, "one draft, updated in place");
542    }
543}