sqlive/read_capture.rs
1//! What the statements a live query runs read, as the authorizer reports
2//! it while each is prepared, and the scope each table was read in (§4).
3
4use std::collections::{BTreeMap, BTreeSet};
5use std::sync::Arc;
6
7use crate::read_set::{ColumnSet, ReadSet, TableRead};
8use crate::row_scope::{RowScope, Scopes};
9
10/// The views and tables a live query reads whole: a read through one of them
11/// depends on the object itself, which can change with no change to the
12/// tables it reads.
13pub struct WholeViews(BTreeSet<String>);
14
15impl WholeViews {
16 /// The views and tables named `views`, in any letter case.
17 pub fn new<'a>(views: impl IntoIterator<Item = &'a str>) -> Self {
18 Self(views.into_iter().map(str::to_ascii_lowercase).collect())
19 }
20
21 /// Whether `name` names one, in any letter case.
22 pub fn contains(&self, name: &str) -> bool {
23 self.0.contains(&name.to_ascii_lowercase())
24 }
25}
26
27/// What a read context's statements read. Each statement running has its own
28/// frame, innermost last, so a statement a row mapper starts records its own
29/// reads and leaves the statement around it with its own. The first frame
30/// holds reads made outside any statement.
31pub struct ReadCapture {
32 frames: Vec<ReadFrame>,
33 completed: ReadSet,
34 whole: Arc<WholeViews>,
35}
36
37/// What one statement read, as SQLite reported it while preparing it.
38#[derive(Clone, Default)]
39pub struct ReadFrame {
40 columns: ColumnSet,
41 /// Tables some of whose columns it read through a view or a CTE, and
42 /// the names, lowercase, of the innermost each read was through.
43 indirect: BTreeMap<String, BTreeSet<String>>,
44}
45
46impl ReadFrame {
47 fn extend(&mut self, other: &Self) {
48 self.columns.extend(other.columns.iter().cloned());
49 for (table, views) in &other.indirect {
50 self.indirect.entry(table.clone()).or_default().extend(views.iter().cloned());
51 }
52 }
53}
54
55impl ReadCapture {
56 /// A capture with one frame, for reads made outside any statement.
57 pub fn new(whole: Arc<WholeViews>) -> Self {
58 Self { frames: vec![ReadFrame::default()], completed: ReadSet::new(), whole }
59 }
60
61 fn current(&mut self) -> &mut ReadFrame {
62 self.frames.last_mut().expect("a read capture keeps its first frame")
63 }
64
65 /// The statement being prepared read `column` of `table`, through the
66 /// view or CTE `accessor` when it names one.
67 pub fn read(&mut self, table: &str, column: &str, accessor: Option<&str>) {
68 let whole = accessor.filter(|name| self.whole.contains(name));
69 let frame = self.current();
70 frame.columns.insert((table.to_ascii_lowercase(), column.to_ascii_lowercase()));
71 if let Some(view) = accessor {
72 frame
73 .indirect
74 .entry(table.to_ascii_lowercase())
75 .or_default()
76 .insert(view.to_ascii_lowercase());
77 }
78 // A read through one of the views read whole reads the view itself
79 // too, even when the statement reads none of the view's columns, as
80 // a count of its rows or an EXISTS doesn't: a view can change with
81 // no change to its tables, as one that calls a function of the
82 // host's state can (§4).
83 if let Some(view) = whole {
84 frame.columns.insert((view.to_ascii_lowercase(), String::new()));
85 }
86 }
87
88 /// What the statement being prepared has read so far.
89 pub fn statement(&mut self) -> ReadFrame {
90 self.current().clone()
91 }
92
93 /// The statement being run read what `recorded` holds when it was
94 /// prepared.
95 pub fn replay(&mut self, recorded: &ReadFrame) {
96 self.current().extend(recorded);
97 }
98
99 /// A statement begins.
100 pub fn begin(&mut self) {
101 self.frames.push(ReadFrame::default());
102 }
103
104 /// End the statement begun last: each table it read in the scope
105 /// `scopes` gives it, or whole.
106 pub fn end(&mut self, scopes: &Scopes) {
107 assert!(self.frames.len() > 1, "a statement's frame was begun");
108 let frame = self.frames.pop().expect("the statement's frame");
109 self.finish(frame, scopes);
110 }
111
112 /// Everything read so far, each statement still running counted whole.
113 pub fn reads(&mut self) -> ReadSet {
114 for frame in std::mem::take(&mut self.frames) {
115 self.finish(frame, &Scopes::default());
116 }
117 self.frames.push(ReadFrame::default());
118 self.completed.clone()
119 }
120
121 /// Record `frame`'s tables but the FTS5 shadow tables `scopes` names,
122 /// each read through the scope `scopes` gives it, or whole, with the
123 /// columns its rows depend on that the authorizer
124 /// didn't report (`unreported_columns.rs`): SQLite reports no read at all
125 /// of a table that a subquery reads only through a USING join. A table
126 /// read through a view or CTE that the
127 /// statement didn't read as a source of its own, such as a view read
128 /// whole, may give the statement any of its rows, so `finish` records it
129 /// as read in every row.
130 fn finish(&mut self, frame: ReadFrame, scopes: &Scopes) {
131 let mut tables: BTreeMap<String, BTreeSet<String>> = BTreeMap::new();
132 for (table, column) in frame
133 .columns
134 .into_iter()
135 .chain(scopes.unreported.columns().iter().cloned())
136 .filter(|(table, _)| !scopes.fts5_shadows.contains(table))
137 {
138 tables.entry(table).or_default().insert(column);
139 }
140 self.completed.extend(tables.into_iter().map(|(table, columns)| {
141 TableRead {
142 scope: match scopes.tables.get(&table) {
143 Some(scope)
144 if frame
145 .indirect
146 .get(&table)
147 .is_none_or(|views| views.is_subset(&scopes.inlined)) =>
148 {
149 scope.clone()
150 }
151 _ => RowScope::All,
152 },
153 table,
154 columns,
155 inserted_only: false,
156 }
157 }));
158 }
159}