Skip to main content

sqlrite/sql/pager/
overflow.rs

1//! Overflow storage for cells that don't fit on one table-leaf page.
2//!
3//! Two pieces live here:
4//!
5//! - [`OverflowRef`] — the on-page marker that replaces a full cell when
6//!   the cell's body is too large to keep inline. It carries the rowid
7//!   (so the page's slot directory stays rowid-ordered), the total size
8//!   of the external body, and a pointer to the first overflow page of
9//!   the chain that holds the body.
10//! - [`write_overflow_chain`] / [`read_overflow_chain`] — turn raw bytes
11//!   into a chain of `Overflow`-typed pages and back. Each overflow page
12//!   reuses the existing 7-byte page header (type tag + next-page + payload
13//!   length) — we're not adding a new page format.
14//!
15//! **Decision to inline the rowid and NOT inline any of the body.** SQLite's
16//! leaf-cell scheme keeps a prefix of the body inline before spilling, so
17//! small lookups by rowid don't need a chain walk. We'd still have to chase
18//! the chain for most columns anyway, so for simplicity this implementation
19//! spills the entire body. A later optimization can split cells at a
20//! threshold and keep a prefix inline without changing the page layout.
21//!
22//! **Overflow threshold.** Inserting a cell whose encoded length is more
23//! than roughly a quarter of the page payload area (≈ 1000 bytes) is a
24//! good candidate for overflow — on a ~4 KiB page you can still keep at
25//! least 3-4 cells per page. The exact threshold is the caller's choice;
26//! this module just exposes [`OVERFLOW_THRESHOLD`] as a suggestion.
27
28use crate::error::{Result, SQLRiteError};
29use crate::sql::pager::cell::{Cell, KIND_LOCAL, KIND_OVERFLOW};
30use crate::sql::pager::page::{PAGE_HEADER_SIZE, PAGE_SIZE, PAYLOAD_PER_PAGE, PageType};
31use crate::sql::pager::pager::Pager;
32use crate::sql::pager::varint;
33
34/// Inline cell-body size above which the caller should consider overflowing.
35/// Sized so at least 4 inline cells can coexist on a page alongside their
36/// slot directory.
37pub const OVERFLOW_THRESHOLD: usize = PAYLOAD_PER_PAGE / 4;
38
39/// On-page marker that stands in for a cell whose body lives in an overflow
40/// chain. Rowid is inlined so the page's binary search over slots still
41/// works without chasing the chain.
42#[derive(Debug, Clone, PartialEq, Eq)]
43pub struct OverflowRef {
44    pub rowid: i64,
45    /// Exact byte count that `read_overflow_chain` must produce; the
46    /// caller then feeds those bytes to `LocalCellBody::decode`.
47    pub total_body_len: u64,
48    /// First page of the Overflow-type chain carrying the body.
49    pub first_overflow_page: u32,
50}
51
52impl OverflowRef {
53    /// Serializes the reference using the shared
54    /// `[cell_length varint | kind_tag | body]` prefix; `kind_tag` is
55    /// always `KIND_OVERFLOW` for this type.
56    pub fn encode(&self) -> Vec<u8> {
57        let mut body = Vec::with_capacity(1 + varint::MAX_VARINT_BYTES * 2 + 4);
58        body.push(KIND_OVERFLOW);
59        varint::write_i64(&mut body, self.rowid);
60        varint::write_u64(&mut body, self.total_body_len);
61        body.extend_from_slice(&self.first_overflow_page.to_le_bytes());
62
63        let mut out = Vec::with_capacity(body.len() + varint::MAX_VARINT_BYTES);
64        varint::write_u64(&mut out, body.len() as u64);
65        out.extend_from_slice(&body);
66        out
67    }
68
69    pub fn decode(buf: &[u8], pos: usize) -> Result<(OverflowRef, usize)> {
70        let (body_len, len_bytes) = varint::read_u64(buf, pos)?;
71        let body_start = pos + len_bytes;
72        let body_end = body_start
73            .checked_add(body_len as usize)
74            .ok_or_else(|| SQLRiteError::Internal("overflow ref length overflow".to_string()))?;
75        if body_end > buf.len() {
76            return Err(SQLRiteError::Internal(format!(
77                "overflow ref extends past buffer: needs {body_start}..{body_end}, have {}",
78                buf.len()
79            )));
80        }
81
82        let body = &buf[body_start..body_end];
83        if body.first().copied() != Some(KIND_OVERFLOW) {
84            return Err(SQLRiteError::Internal(format!(
85                "OverflowRef::decode called on non-overflow entry (kind_tag = {:#x})",
86                body.first().copied().unwrap_or(0)
87            )));
88        }
89        let mut cur = 1usize;
90        let (rowid, n) = varint::read_i64(body, cur)?;
91        cur += n;
92        let (total_body_len, n) = varint::read_u64(body, cur)?;
93        cur += n;
94        if cur + 4 > body.len() {
95            return Err(SQLRiteError::Internal(
96                "overflow ref truncated before first_overflow_page".to_string(),
97            ));
98        }
99        let first_overflow_page = u32::from_le_bytes(body[cur..cur + 4].try_into().unwrap());
100        cur += 4;
101        if cur != body.len() {
102            return Err(SQLRiteError::Internal(format!(
103                "overflow ref had {} trailing bytes",
104                body.len() - cur
105            )));
106        }
107        Ok((
108            OverflowRef {
109                rowid,
110                total_body_len,
111                first_overflow_page,
112            },
113            body_end - pos,
114        ))
115    }
116}
117
118/// An on-page entry: either a full local cell, or a pointer to an overflow
119/// chain carrying the cell's body.
120#[derive(Debug, Clone, PartialEq)]
121pub enum PagedEntry {
122    Local(Cell),
123    Overflow(OverflowRef),
124}
125
126impl PagedEntry {
127    pub fn rowid(&self) -> i64 {
128        match self {
129            PagedEntry::Local(c) => c.rowid,
130            PagedEntry::Overflow(r) => r.rowid,
131        }
132    }
133
134    pub fn encode(&self) -> Result<Vec<u8>> {
135        match self {
136            PagedEntry::Local(c) => c.encode(),
137            PagedEntry::Overflow(r) => Ok(r.encode()),
138        }
139    }
140
141    /// Dispatches on the kind tag and returns the appropriate variant.
142    pub fn decode(buf: &[u8], pos: usize) -> Result<(PagedEntry, usize)> {
143        match Cell::peek_kind(buf, pos)? {
144            KIND_LOCAL => {
145                let (c, n) = Cell::decode(buf, pos)?;
146                Ok((PagedEntry::Local(c), n))
147            }
148            KIND_OVERFLOW => {
149                let (r, n) = OverflowRef::decode(buf, pos)?;
150                Ok((PagedEntry::Overflow(r), n))
151            }
152            other => Err(SQLRiteError::Internal(format!(
153                "unknown paged-entry kind tag {other:#x} at offset {pos}"
154            ))),
155        }
156    }
157}
158
159/// Writes `bytes` into a chain of Overflow-typed pages starting at
160/// `start_page`, using consecutive page numbers. Returns the first page
161/// number *after* the chain (i.e., the next free page to hand out).
162pub fn write_overflow_chain(pager: &mut Pager, bytes: &[u8], start_page: u32) -> Result<u32> {
163    if bytes.is_empty() {
164        return Err(SQLRiteError::Internal(
165            "refusing to write an empty overflow chain — caller should inline instead".to_string(),
166        ));
167    }
168    let mut current_page = start_page;
169    let mut remaining = bytes;
170    while !remaining.is_empty() {
171        let chunk_len = remaining.len().min(PAYLOAD_PER_PAGE);
172        let (chunk, rest) = remaining.split_at(chunk_len);
173        let next = if rest.is_empty() { 0 } else { current_page + 1 };
174        pager.stage_page(current_page, encode_overflow_page(next, chunk)?);
175        current_page += 1;
176        remaining = rest;
177    }
178    Ok(current_page)
179}
180
181/// Walks an overflow chain starting at `first_page` and concatenates its
182/// payload bytes. Reads exactly `total_body_len` bytes — a mismatch between
183/// what the chain carries and what the OverflowRef claims is a corruption
184/// error.
185pub fn read_overflow_chain(pager: &Pager, first_page: u32, total_body_len: u64) -> Result<Vec<u8>> {
186    let mut out = Vec::with_capacity(total_body_len as usize);
187    let mut current = first_page;
188    while current != 0 {
189        let raw = pager.read_page(current).ok_or_else(|| {
190            SQLRiteError::Internal(format!("overflow chain references missing page {current}"))
191        })?;
192        let ty_byte = raw[0];
193        if ty_byte != PageType::Overflow as u8 {
194            return Err(SQLRiteError::Internal(format!(
195                "page {current} was supposed to be Overflow but is type {ty_byte}"
196            )));
197        }
198        let next = u32::from_le_bytes(raw[1..5].try_into().unwrap());
199        let payload_len = u16::from_le_bytes(raw[5..7].try_into().unwrap()) as usize;
200        if payload_len > PAYLOAD_PER_PAGE {
201            return Err(SQLRiteError::Internal(format!(
202                "overflow page {current} reports payload_len {payload_len} > max"
203            )));
204        }
205        out.extend_from_slice(&raw[PAGE_HEADER_SIZE..PAGE_HEADER_SIZE + payload_len]);
206        current = next;
207    }
208    if out.len() as u64 != total_body_len {
209        return Err(SQLRiteError::Internal(format!(
210            "overflow chain produced {} bytes, OverflowRef claimed {total_body_len}",
211            out.len()
212        )));
213    }
214    Ok(out)
215}
216
217/// Encodes a single `Overflow`-typed page holding `payload` bytes. Shared
218/// with the rest of the pager via the standard 7-byte page header layout.
219fn encode_overflow_page(next: u32, payload: &[u8]) -> Result<[u8; PAGE_SIZE]> {
220    if payload.len() > PAYLOAD_PER_PAGE {
221        return Err(SQLRiteError::Internal(format!(
222            "overflow page payload {} exceeds max {PAYLOAD_PER_PAGE}",
223            payload.len()
224        )));
225    }
226    let mut buf = [0u8; PAGE_SIZE];
227    buf[0] = PageType::Overflow as u8;
228    buf[1..5].copy_from_slice(&next.to_le_bytes());
229    buf[5..7].copy_from_slice(&(payload.len() as u16).to_le_bytes());
230    buf[PAGE_HEADER_SIZE..PAGE_HEADER_SIZE + payload.len()].copy_from_slice(payload);
231    Ok(buf)
232}
233
234#[cfg(test)]
235mod tests {
236    use super::*;
237    use crate::sql::db::table::Value;
238
239    fn tmp_path(name: &str) -> std::path::PathBuf {
240        let mut p = std::env::temp_dir();
241        let pid = std::process::id();
242        let nanos = std::time::SystemTime::now()
243            .duration_since(std::time::UNIX_EPOCH)
244            .map(|d| d.as_nanos())
245            .unwrap_or(0);
246        p.push(format!("sqlrite-overflow-{pid}-{nanos}-{name}.sqlrite"));
247        p
248    }
249
250    #[test]
251    fn overflow_ref_round_trip() {
252        let r = OverflowRef {
253            rowid: 42,
254            total_body_len: 123_456,
255            first_overflow_page: 7,
256        };
257        let bytes = r.encode();
258        let (back, consumed) = OverflowRef::decode(&bytes, 0).unwrap();
259        assert_eq!(back, r);
260        assert_eq!(consumed, bytes.len());
261    }
262
263    #[test]
264    fn paged_entry_dispatches_on_kind() {
265        let local = Cell::new(1, vec![Some(Value::Integer(10))]);
266        let local_bytes = local.encode().unwrap();
267        let (decoded, _) = PagedEntry::decode(&local_bytes, 0).unwrap();
268        assert_eq!(decoded, PagedEntry::Local(local));
269
270        let overflow = OverflowRef {
271            rowid: 2,
272            total_body_len: 5000,
273            first_overflow_page: 13,
274        };
275        let overflow_bytes = overflow.encode();
276        let (decoded, _) = PagedEntry::decode(&overflow_bytes, 0).unwrap();
277        assert_eq!(decoded, PagedEntry::Overflow(overflow));
278    }
279
280    #[test]
281    fn peek_rowid_works_for_both_kinds() {
282        let local = Cell::new(99, vec![Some(Value::Integer(1))]);
283        let local_bytes = local.encode().unwrap();
284        assert_eq!(Cell::peek_rowid(&local_bytes, 0).unwrap(), 99);
285
286        let overflow = OverflowRef {
287            rowid: -7,
288            total_body_len: 100,
289            first_overflow_page: 42,
290        };
291        let overflow_bytes = overflow.encode();
292        assert_eq!(Cell::peek_rowid(&overflow_bytes, 0).unwrap(), -7);
293    }
294
295    #[test]
296    fn write_then_read_overflow_chain() {
297        let path = tmp_path("chain");
298        let mut pager = Pager::create(&path).unwrap();
299
300        // A blob that definitely spans multiple pages.
301        let blob: Vec<u8> = (0..10_000).map(|i| (i % 251) as u8).collect();
302        let pages_needed = blob.len().div_ceil(PAYLOAD_PER_PAGE) as u32;
303        let start = 10u32;
304        let next_free = write_overflow_chain(&mut pager, &blob, start).unwrap();
305        assert_eq!(next_free, start + pages_needed);
306
307        pager
308            .commit(crate::sql::pager::header::DbHeader {
309                page_count: next_free,
310                schema_root_page: 1,
311            })
312            .unwrap();
313
314        // Fresh pager to verify we read from disk.
315        drop(pager);
316        let pager = Pager::open(&path).unwrap();
317        let back = read_overflow_chain(&pager, start, blob.len() as u64).unwrap();
318        assert_eq!(back, blob);
319
320        let _ = std::fs::remove_file(&path);
321    }
322
323    #[test]
324    fn read_overflow_chain_rejects_length_mismatch() {
325        let path = tmp_path("mismatch");
326        let mut pager = Pager::create(&path).unwrap();
327        let blob = vec![1u8; 500];
328        let next = write_overflow_chain(&mut pager, &blob, 10).unwrap();
329        pager
330            .commit(crate::sql::pager::header::DbHeader {
331                page_count: next,
332                schema_root_page: 1,
333            })
334            .unwrap();
335
336        // Claim more bytes than the chain actually carries.
337        let err = read_overflow_chain(&pager, 10, 999).unwrap_err();
338        assert!(format!("{err}").contains("overflow chain produced"));
339
340        let _ = std::fs::remove_file(&path);
341    }
342
343    #[test]
344    fn empty_chain_is_rejected() {
345        let path = tmp_path("empty");
346        let mut pager = Pager::create(&path).unwrap();
347        let err = write_overflow_chain(&mut pager, &[], 10).unwrap_err();
348        assert!(format!("{err}").contains("empty overflow chain"));
349        let _ = std::fs::remove_file(&path);
350    }
351
352    #[test]
353    fn overflow_threshold_is_reasonable() {
354        // The threshold should leave room for at least 4 cells per page.
355        assert!(OVERFLOW_THRESHOLD <= PAYLOAD_PER_PAGE / 4);
356        // And it should be comfortably larger than a typical small cell.
357        assert!(OVERFLOW_THRESHOLD > 200);
358    }
359}