Skip to main content

coven_database/
lost.rs

1//! Decoding the durable lost-value fields into the read API.
2
3use crate::{DbError, RowKey, Slot, WriteId};
4use coven_format::loss::{Loss, LossCause, LossValues};
5use coven_merge::Rule;
6use sqlive::rusqlite::types::Value;
7
8/// One durable lost cell or removed row.
9#[derive(Clone, Debug, PartialEq)]
10pub struct LostValue {
11    /// The application's table.
12    pub table: String,
13    /// The row's primary key.
14    pub key: RowKey,
15    /// The displaced cell or removed row's cells.
16    pub lost: Lost,
17    /// What replaced these values.
18    pub replaced_by: Replacement,
19    /// Old-shape values kept independently of the current schema (§18.7).
20    /// Their table or columns may no longer exist; dismissal still works.
21    pub frozen: bool,
22    pub(crate) target: LossTarget,
23}
24
25#[derive(Clone, Debug, PartialEq, Eq)]
26pub(crate) enum LossTarget {
27    Removed { row: coven_merge::RowId, generation: u64 },
28    Acknowledgements(Vec<coven_format::dismissal::Dismissal>),
29}
30
31/// Values retained when a cell loses or a row is removed.
32#[derive(Clone, Debug, PartialEq)]
33pub enum Lost {
34    /// One displaced cell.
35    Cell(LostCell),
36    /// Every retained column, with its own setter.
37    Row(Vec<LostCell>),
38}
39
40/// One retained value and the write that set it.
41#[derive(Clone, Debug, PartialEq)]
42pub struct LostCell {
43    /// The column's name.
44    pub column: String,
45    /// The SQLite value as written, without foreign-key null substitution.
46    pub value: Value,
47    /// The write that set this cell.
48    pub set_by: WriteId,
49}
50
51/// The write, rules, breaking schema version, dropped data or refused
52/// permission responsible for a loss.
53#[derive(Clone, Debug, PartialEq)]
54pub enum Replacement {
55    /// A write that had not read the displaced value.
56    Write(WriteId),
57    /// All removal rules holding for the row.
58    Rules(Vec<RemovalRule>),
59    /// A breaking schema change the write had not read.
60    SchemaChange {
61        /// The schema version reached by the breaking change.
62        version: u32,
63    },
64    /// This original row change used dropped data (§9.5, §14.1). Sources name
65    /// generation/setter changes, additional direct-execution sources, then
66    /// verified foreign-key causes (§9.6), in authored role/execution order,
67    /// with repeats. Row identity distinguishes several causes in the same
68    /// write. An empty delete still names its write.
69    DataDependency {
70        /// The write containing this row change.
71        write: WriteId,
72        /// The failed sources, in role order.
73        sources: Vec<ChangeSource>,
74    },
75    /// A member's row change lacked permission; other changes may apply (§9.6).
76    NotAuthorized {
77        /// The write containing this row change.
78        write: WriteId,
79        /// Why it was refused.
80        reason: RowAuthorizationFailure,
81    },
82}
83
84/// Why a member's row change was refused (§9.6).
85#[derive(Clone, Debug, PartialEq, Eq)]
86pub enum RowAuthorizationFailure {
87    /// A direct target belongs to this member, or a foreign target had no
88    /// valid foreign-key derivation from an authorized direct change.
89    NotOwner {
90        /// The member whose write created the row.
91        owner: coven_foundation::id_source::MemberId,
92    },
93    /// A direct target is in a table limited to admins, and the write's
94    /// author was no admin in the state just before its slot.
95    NotAdmin,
96    /// The proposed derived payload differs from the reconstructed schema effect.
97    InvalidForeignKeyEffect,
98}
99
100/// An original row change or direct execution target used as data (§9.5, §9.6).
101#[derive(Clone, Debug, PartialEq)]
102pub struct ChangeSource {
103    /// The write containing it.
104    pub write: WriteId,
105    /// Its original table name, before any conversion.
106    pub table: String,
107    /// The row's primary key.
108    pub key: RowKey,
109    /// The row's audience.
110    pub audience: coven_merge::Audience,
111}
112
113/// A rule responsible for a removed row.
114#[derive(Clone, Debug, PartialEq, Eq)]
115pub enum RemovalRule {
116    /// A reference to an absent, stale or removed parent.
117    ForeignKey {
118        /// The referencing columns, in constraint order.
119        columns: Vec<String>,
120        /// The referenced table.
121        parent: String,
122        /// The referenced columns, in constraint order.
123        parent_columns: Vec<String>,
124    },
125    /// A failed CHECK.
126    Check {
127        /// The constraint's name.
128        constraint: String,
129    },
130    /// The row belongs to a deleted circle.
131    DeletedCircle {
132        /// The kept entry responsible for the deletion.
133        entry: Slot,
134    },
135    /// The same key is shown from another audience.
136    OtherAudience,
137    /// A competing row won the unique values.
138    Unique {
139        /// Column names or expression text, in constraint order.
140        terms: Vec<String>,
141        /// The WHERE expression of a partial constraint.
142        partial: Option<String>,
143    },
144}
145
146impl LostValue {
147    pub(crate) fn from_record(record: Loss) -> Result<Self, DbError> {
148        let key = RowKey::decode(&record.row.key)?;
149        let cell = |column, cell: coven_merge::Cell<coven_format::value::Value>| LostCell {
150            column,
151            value: crate::write_encoding::sql_value(&cell.value.value),
152            set_by: cell.write,
153        };
154        let lost = match record.values {
155            LossValues::Cell { column, cell: value } => Lost::Cell(cell(column, value)),
156            LossValues::Row(cells) => {
157                Lost::Row(cells.into_iter().map(|(column, value)| cell(column, value)).collect())
158            }
159        };
160        let original = record.cause.change_write();
161        let replaced_by = match record.cause {
162            LossCause::Write(write) => Replacement::Write(write),
163            LossCause::Rules(rules) => Replacement::Rules(
164                rules
165                    .into_iter()
166                    .map(|rule| match rule {
167                        Rule::ForeignKey(key) => RemovalRule::ForeignKey {
168                            columns: key.columns.0,
169                            parent: key.parent,
170                            parent_columns: key.parent_columns.0,
171                        },
172                        Rule::Unique(constraint) => RemovalRule::Unique {
173                            terms: constraint.terms,
174                            partial: constraint.partial,
175                        },
176                        Rule::Check(constraint) => RemovalRule::Check { constraint },
177                        Rule::DeletedCircle(entry) => RemovalRule::DeletedCircle { entry },
178                        Rule::OtherAudience => RemovalRule::OtherAudience,
179                    })
180                    .collect(),
181            ),
182            LossCause::Excluded { version, .. } => Replacement::SchemaChange { version },
183            LossCause::Dependency { write, sources } => Replacement::DataDependency {
184                write,
185                sources: sources
186                    .into_iter()
187                    .map(|source| {
188                        Ok(ChangeSource {
189                            write: source.write,
190                            key: RowKey::decode(&source.row.key)?,
191                            table: source.row.table,
192                            audience: source.row.audience,
193                        })
194                    })
195                    .collect::<Result<_, DbError>>()?,
196            },
197            LossCause::NotAuthorized { write, reason } => Replacement::NotAuthorized {
198                write,
199                reason: match reason {
200                    coven_format::loss::AuthorizationFailure::NotOwner { owner } => {
201                        RowAuthorizationFailure::NotOwner { owner }
202                    }
203                    coven_format::loss::AuthorizationFailure::NotAdmin => {
204                        RowAuthorizationFailure::NotAdmin
205                    }
206                    coven_format::loss::AuthorizationFailure::InvalidForeignKeyEffect => {
207                        RowAuthorizationFailure::InvalidForeignKeyEffect
208                    }
209                },
210            },
211        };
212        let row = record.row;
213        let frozen = record.frozen;
214        let target = if matches!(replaced_by, Replacement::Rules(_)) && !frozen {
215            LossTarget::Removed { row: row.clone(), generation: record.generation }
216        } else {
217            let cells = match &lost {
218                Lost::Cell(cell) => std::slice::from_ref(cell),
219                Lost::Row(cells) => cells,
220            };
221            LossTarget::Acknowledgements(if cells.is_empty() {
222                vec![coven_format::dismissal::Dismissal {
223                    row: row.clone(),
224                    target: coven_format::dismissal::DismissalTarget::EmptyRow,
225                    write: original.expect("an empty frozen loss names its original change"),
226                }]
227            } else {
228                cells
229                    .iter()
230                    .map(|cell| coven_format::dismissal::Dismissal {
231                        row: row.clone(),
232                        target: coven_format::dismissal::DismissalTarget::Cell(cell.column.clone()),
233                        write: cell.set_by,
234                    })
235                    .collect()
236            })
237        };
238        Ok(LostValue { table: row.table, key, lost, replaced_by, frozen, target })
239    }
240}
241
242#[cfg(test)]
243#[path = "lost_tests.rs"]
244mod tests;