1use 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
34pub const OVERFLOW_THRESHOLD: usize = PAYLOAD_PER_PAGE / 4;
38
39#[derive(Debug, Clone, PartialEq, Eq)]
43pub struct OverflowRef {
44 pub rowid: i64,
45 pub total_body_len: u64,
48 pub first_overflow_page: u32,
50}
51
52impl OverflowRef {
53 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#[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 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
159pub fn write_overflow_chain(
168 pager: &mut Pager,
169 bytes: &[u8],
170 alloc: &mut crate::sql::pager::allocator::PageAllocator,
171) -> Result<u32> {
172 if bytes.is_empty() {
173 return Err(SQLRiteError::Internal(
174 "refusing to write an empty overflow chain — caller should inline instead".to_string(),
175 ));
176 }
177 let chunks: Vec<&[u8]> = bytes.chunks(PAYLOAD_PER_PAGE).collect();
180 let pages: Vec<u32> = (0..chunks.len()).map(|_| alloc.allocate()).collect();
181 for (i, chunk) in chunks.iter().enumerate() {
182 let next = if i + 1 < pages.len() { pages[i + 1] } else { 0 };
183 pager.stage_page(pages[i], encode_overflow_page(next, chunk)?);
184 }
185 Ok(pages[0])
186}
187
188pub fn read_overflow_chain(pager: &Pager, first_page: u32, total_body_len: u64) -> Result<Vec<u8>> {
193 let mut out = Vec::with_capacity(total_body_len as usize);
194 let mut current = first_page;
195 while current != 0 {
196 let raw = pager.read_page(current).ok_or_else(|| {
197 SQLRiteError::Internal(format!("overflow chain references missing page {current}"))
198 })?;
199 let ty_byte = raw[0];
200 if ty_byte != PageType::Overflow as u8 {
201 return Err(SQLRiteError::Internal(format!(
202 "page {current} was supposed to be Overflow but is type {ty_byte}"
203 )));
204 }
205 let next = u32::from_le_bytes(raw[1..5].try_into().unwrap());
206 let payload_len = u16::from_le_bytes(raw[5..7].try_into().unwrap()) as usize;
207 if payload_len > PAYLOAD_PER_PAGE {
208 return Err(SQLRiteError::Internal(format!(
209 "overflow page {current} reports payload_len {payload_len} > max"
210 )));
211 }
212 out.extend_from_slice(&raw[PAGE_HEADER_SIZE..PAGE_HEADER_SIZE + payload_len]);
213 current = next;
214 }
215 if out.len() as u64 != total_body_len {
216 return Err(SQLRiteError::Internal(format!(
217 "overflow chain produced {} bytes, OverflowRef claimed {total_body_len}",
218 out.len()
219 )));
220 }
221 Ok(out)
222}
223
224fn encode_overflow_page(next: u32, payload: &[u8]) -> Result<[u8; PAGE_SIZE]> {
227 if payload.len() > PAYLOAD_PER_PAGE {
228 return Err(SQLRiteError::Internal(format!(
229 "overflow page payload {} exceeds max {PAYLOAD_PER_PAGE}",
230 payload.len()
231 )));
232 }
233 let mut buf = [0u8; PAGE_SIZE];
234 buf[0] = PageType::Overflow as u8;
235 buf[1..5].copy_from_slice(&next.to_le_bytes());
236 buf[5..7].copy_from_slice(&(payload.len() as u16).to_le_bytes());
237 buf[PAGE_HEADER_SIZE..PAGE_HEADER_SIZE + payload.len()].copy_from_slice(payload);
238 Ok(buf)
239}
240
241#[cfg(test)]
242mod tests {
243 use super::*;
244 use crate::sql::db::table::Value;
245
246 fn tmp_path(name: &str) -> std::path::PathBuf {
247 let mut p = std::env::temp_dir();
248 let pid = std::process::id();
249 let nanos = std::time::SystemTime::now()
250 .duration_since(std::time::UNIX_EPOCH)
251 .map(|d| d.as_nanos())
252 .unwrap_or(0);
253 p.push(format!("sqlrite-overflow-{pid}-{nanos}-{name}.sqlrite"));
254 p
255 }
256
257 #[test]
258 fn overflow_ref_round_trip() {
259 let r = OverflowRef {
260 rowid: 42,
261 total_body_len: 123_456,
262 first_overflow_page: 7,
263 };
264 let bytes = r.encode();
265 let (back, consumed) = OverflowRef::decode(&bytes, 0).unwrap();
266 assert_eq!(back, r);
267 assert_eq!(consumed, bytes.len());
268 }
269
270 #[test]
271 fn paged_entry_dispatches_on_kind() {
272 let local = Cell::new(1, vec![Some(Value::Integer(10))]);
273 let local_bytes = local.encode().unwrap();
274 let (decoded, _) = PagedEntry::decode(&local_bytes, 0).unwrap();
275 assert_eq!(decoded, PagedEntry::Local(local));
276
277 let overflow = OverflowRef {
278 rowid: 2,
279 total_body_len: 5000,
280 first_overflow_page: 13,
281 };
282 let overflow_bytes = overflow.encode();
283 let (decoded, _) = PagedEntry::decode(&overflow_bytes, 0).unwrap();
284 assert_eq!(decoded, PagedEntry::Overflow(overflow));
285 }
286
287 #[test]
288 fn peek_rowid_works_for_both_kinds() {
289 let local = Cell::new(99, vec![Some(Value::Integer(1))]);
290 let local_bytes = local.encode().unwrap();
291 assert_eq!(Cell::peek_rowid(&local_bytes, 0).unwrap(), 99);
292
293 let overflow = OverflowRef {
294 rowid: -7,
295 total_body_len: 100,
296 first_overflow_page: 42,
297 };
298 let overflow_bytes = overflow.encode();
299 assert_eq!(Cell::peek_rowid(&overflow_bytes, 0).unwrap(), -7);
300 }
301
302 #[test]
303 fn write_then_read_overflow_chain() {
304 let path = tmp_path("chain");
305 let mut pager = Pager::create(&path).unwrap();
306
307 let blob: Vec<u8> = (0..10_000).map(|i| (i % 251) as u8).collect();
309 let pages_needed = blob.len().div_ceil(PAYLOAD_PER_PAGE) as u32;
310 let mut alloc =
311 crate::sql::pager::allocator::PageAllocator::new(std::collections::VecDeque::new(), 10);
312 let start = write_overflow_chain(&mut pager, &blob, &mut alloc).unwrap();
313 assert_eq!(start, 10);
314 assert_eq!(alloc.high_water(), 10 + pages_needed);
316
317 pager
318 .commit(crate::sql::pager::header::DbHeader {
319 page_count: alloc.high_water(),
320 schema_root_page: 1,
321 format_version: crate::sql::pager::header::FORMAT_VERSION_BASELINE,
322 freelist_head: 0,
323 })
324 .unwrap();
325
326 drop(pager);
328 let pager = Pager::open(&path).unwrap();
329 let back = read_overflow_chain(&pager, start, blob.len() as u64).unwrap();
330 assert_eq!(back, blob);
331
332 let _ = std::fs::remove_file(&path);
333 }
334
335 #[test]
336 fn read_overflow_chain_rejects_length_mismatch() {
337 let path = tmp_path("mismatch");
338 let mut pager = Pager::create(&path).unwrap();
339 let blob = vec![1u8; 500];
340 let mut alloc =
341 crate::sql::pager::allocator::PageAllocator::new(std::collections::VecDeque::new(), 10);
342 let start = write_overflow_chain(&mut pager, &blob, &mut alloc).unwrap();
343 assert_eq!(start, 10);
344 pager
345 .commit(crate::sql::pager::header::DbHeader {
346 page_count: alloc.high_water(),
347 schema_root_page: 1,
348 format_version: crate::sql::pager::header::FORMAT_VERSION_BASELINE,
349 freelist_head: 0,
350 })
351 .unwrap();
352
353 let err = read_overflow_chain(&pager, start, 999).unwrap_err();
355 assert!(format!("{err}").contains("overflow chain produced"));
356
357 let _ = std::fs::remove_file(&path);
358 }
359
360 #[test]
361 fn empty_chain_is_rejected() {
362 let path = tmp_path("empty");
363 let mut pager = Pager::create(&path).unwrap();
364 let mut alloc =
365 crate::sql::pager::allocator::PageAllocator::new(std::collections::VecDeque::new(), 10);
366 let err = write_overflow_chain(&mut pager, &[], &mut alloc).unwrap_err();
367 assert!(format!("{err}").contains("empty overflow chain"));
368 let _ = std::fs::remove_file(&path);
369 }
370
371 #[test]
372 fn overflow_threshold_is_reasonable() {
373 assert!(OVERFLOW_THRESHOLD <= PAYLOAD_PER_PAGE / 4);
375 assert!(OVERFLOW_THRESHOLD > 200);
377 }
378}