Craft Anything: understand how any software works, and craft your own.
Rust
Read SQLite WITHOUT ROWID tables, rows older than added columns and capped records correctly (#412)
GGWAecbd519c6a4b
diff --git a/crates/engine/src/tools/database_tools.rs b/crates/engine/src/tools/database_tools.rsindex a1cce090..e8e99673 100644--- a/crates/engine/src/tools/database_tools.rs+++ b/crates/engine/src/tools/database_tools.rs@@ -107,7 +107,7 @@ fn db_sqlite_show(ctx: &mut Ctx<'_>, params: Value) -> Result<ToolOutput, ToolErlet total = rc.count;let shown = page.rows.len() as u64;let next = p.offset as u64 + shown;- let cov = if page.truncated || rc.bounded || next < total {+ let cov = if page.truncated || rc.bounded || next < total || !page.notes.is_empty() {Coverage { status: CoverageStatus::Partial, examined: Some(shown), total: Some(total), next_offset: (next < total).then_some(next) }} else {Coverage { status: CoverageStatus::Complete, examined: Some(shown), total: Some(total), next_offset: None }@@ -219,7 +219,94 @@ mod tests {use crate::Engine;use craft_anything_testkit::sqlite as fx;use craft_anything_testkit::temp_file;- use serde_json::json;+ use serde_json::{Value, json};++ fn check_without_rowid(sql: &str, stored: Vec<Vec<fx::Val>>, expected: Value) {+ let e = Engine::new(crate::testing::session());+ let p = temp_file("rows.db", &fx::without_rowid_db(sql, &stored));+ let count = expected.as_array().unwrap().len();+ let v = call(&e, "db_sqlite_show", json!({"path": p, "table": "t", "limit": count + 1}));+ assert_eq!(v["result"]["tables"][0]["row_count"], count, "WITHOUT ROWID row_count");+ let rows = v["result"]["rows"]["rows"].as_array().unwrap();+ assert_eq!(rows.len(), count);+ for (row, values) in rows.iter().zip(expected.as_array().unwrap()) {+ assert_eq!(row["rowid"], Value::Null);+ assert_eq!(&row["values"], values);+ }+ assert_eq!(v["coverage"]["status"], "complete");+ assert_eq!(v["coverage"]["total"], count);+ assert_eq!(v["coverage"]["next_offset"], Value::Null);+ assert!(v["result"]["rows"]["notes"].as_array().unwrap().is_empty());+ let first = call(&e, "db_sqlite_show", json!({"path": p, "table": "t", "limit": 1}));+ assert_eq!(first["result"]["rows"]["rows"][0]["values"], expected[0]);+ assert_eq!(first["coverage"]["total"], count);+ assert_eq!(first["coverage"]["next_offset"], 1);+ let last = call(&e, "db_sqlite_show", json!({"path": p, "table": "t", "offset": count - 1, "limit": 2}));+ assert_eq!(last["result"]["rows"]["rows"][0]["values"], expected[count - 1]);+ assert_eq!(last["coverage"]["next_offset"], Value::Null);+ assert_eq!(last["coverage"]["status"], "complete");+ }++ #[test]+ fn without_rowid_b1_composite_key() {+ use fx::Val::{Int, Text};+ check_without_rowid(+ "CREATE TABLE t(a TEXT, b INT, PRIMARY KEY(a,b)) WITHOUT ROWID",+ vec![vec![Text("j".into()), Int(2)], vec![Text("k".into()), Int(1)], vec![Text("m".into()), Int(3)]],+ json!([["j", 2], ["k", 1], ["m", 3]]),+ );+ }++ #[test]+ fn without_rowid_b2_interior_rows() {+ use fx::Val::Text;+ let pad = "p".repeat(200);+ let rows = (0..3000).map(|i| vec![Text(format!("k{i:04}")), Text(pad.clone())]).collect();+ let expected = (0..3000).map(|i| json!([format!("k{i:04}"), pad])).collect::<Vec<_>>();+ check_without_rowid("CREATE TABLE t(a TEXT PRIMARY KEY, pad TEXT) WITHOUT ROWID", rows, json!(expected));+ }++ #[test]+ fn without_rowid_b4_integer_key() {+ use fx::Val::{Int, Text};+ check_without_rowid(+ "CREATE TABLE t(id INTEGER PRIMARY KEY, v TEXT) WITHOUT ROWID",+ vec![vec![Int(5), Text("a".into())], vec![Int(9), Text("b".into())]],+ json!([[5, "a"], [9, "b"]]),+ );+ }++ #[test]+ fn without_rowid_b5_declaration_order() {+ use fx::Val::{Int, Text};+ check_without_rowid(+ "CREATE TABLE t(v TEXT, k INT PRIMARY KEY) without\n rowid ;",+ vec![vec![Int(5), Text("a".into())], vec![Int(9), Text("b".into())]],+ json!([["a", 5], ["b", 9]]),+ );+ }++ #[test]+ fn without_rowid_b3_rowid_control() {+ let e = Engine::new(crate::testing::session());+ let p = temp_file("rows.db", &fx::indexed_rowid_db());+ let v = call(&e, "db_sqlite_show", json!({"path": p, "table": "t"}));+ assert_eq!(v["result"]["tables"][0]["row_count"], 2);+ assert_eq!(v["result"]["rows"]["rows"], json!([{"rowid": 1, "values": ["z", 1]}, {"rowid": 2, "values": ["a", 2]}]));+ }++ #[test]+ fn without_rowid_overflow_and_composite_storage_order() {+ use fx::Val::{Int, Text};+ let pad = "x".repeat(2000);+ let rows = (0..5).rev().map(|i| vec![Int(i), Text(format!("k{i}")), Text(pad.clone())]).collect();+ let expected = (0..5).rev().map(|i| json!([pad, format!("k{i}"), i])).collect::<Vec<_>>();+ check_without_rowid(+ "CREATE TABLE t(pad TEXT, \"a key\" TEXT, b INT, CONSTRAINT pk PRIMARY KEY(b DESC, \"a key\" COLLATE BINARY)) WITHOUT ROWID",+ rows,+ json!(expected),+ );+ }#[test]fn inspects_schema_and_rows() {@@ -248,6 +335,20 @@ mod tests {assert_eq!(rows["coverage"]["total"], 3);}+ #[test]+ fn payload_cap_is_disclosed_in_coverage() {+ let e = Engine::new(crate::testing::session());+ for size in [1_000_000, 8_400_000] {+ let bytes = fx::overflow_row_db(&[fx::Val::Int(42), fx::Val::Blob(vec![0x5a; size]), fx::Val::Int(73)]);+ let p = temp_file("overflow.db", &bytes);+ let v = call(&e, "db_sqlite_show", json!({"path": p, "table": "items"}));+ let partial = size == 8_400_000;+ assert_eq!(v["coverage"]["status"], if partial { "partial" } else { "complete" });+ assert_eq!(v["result"]["rows"]["notes"].as_array().unwrap().is_empty(), !partial);+ assert_eq!(v["limitations"].as_array().unwrap().iter().any(|l| l["code"] == "read_notes"), partial);+ }+ }+#[test]fn blob_is_summarised_not_dumped() {let e = Engine::new(crate::testing::session());@@ -284,4 +385,33 @@ mod tests {assert!(v["summary"].as_str().unwrap().contains("WAL"));assert!(v["limitations"].as_array().unwrap().iter().any(|l| l["code"] == "wal_not_read"));}++ #[test]+ fn short_records_include_defaults_and_disclose_expressions() {+ let e = Engine::new(crate::testing::session());+ let bytes = fx::table_db("CREATE TABLE t(n INT, x INT DEFAULT 42, d TEXT DEFAULT (lower('A')))", &[(1, vec![fx::Val::Int(1)])]);+ let p = temp_file("defaults.db", &bytes);+ let v = call(&e, "db_sqlite_show", json!({"path": p, "table": "t"}));+ assert_eq!(v["result"]["rows"]["rows"][0]["values"], json!([1, 42, null]));+ assert!(v["result"]["rows"]["notes"].as_array().unwrap().iter().any(|n| n.as_str().unwrap().contains("unsupported DEFAULT")));+ }++ #[test]+ fn payload_cap_without_rowid_is_disclosed_in_coverage() {+ let e = Engine::new(crate::testing::session());+ let bytes = fx::without_rowid_db(+ "CREATE TABLE t(v BLOB, k INT PRIMARY KEY, tail INT) WITHOUT ROWID",+ &[vec![fx::Val::Int(42), fx::Val::Blob(vec![0x5a; 8_400_000]), fx::Val::Int(73)]],+ );+ let p = temp_file("overflow-index.db", &bytes);+ let v = call(&e, "db_sqlite_show", json!({"path": p, "table": "t"}));+ assert_eq!(v["coverage"]["status"], "partial");+ assert_eq!(+ v["result"]["rows"]["rows"][0]["values"],+ json!([+ {"blob_len": 8_400_000, "truncated": true}, 42, {"not_read": true}+ ])+ );+ assert!(v["limitations"].as_array().unwrap().iter().any(|l| l["code"] == "read_notes"));+ }}diff --git a/crates/formats/src/sqlite.rs b/crates/formats/src/sqlite.rsindex 4a29c318..1207ec9f 100644--- a/crates/formats/src/sqlite.rs+++ b/crates/formats/src/sqlite.rs@@ -119,6 +119,8 @@ pub enum CellValue {Real(f64),Text { text: String, truncated: bool },Blob { len: usize, sha256_prefix: String },+ PartialBlob { len: usize },+ NotRead,}impl Serialize for CellValue {@@ -144,6 +146,17 @@ impl Serialize for CellValue {m.serialize_entry("sha256_prefix", sha256_prefix)?;m.end()}+ CellValue::PartialBlob { len } => {+ let mut m = s.serialize_map(Some(2))?;+ m.serialize_entry("blob_len", len)?;+ m.serialize_entry("truncated", &true)?;+ m.end()+ }+ CellValue::NotRead => {+ let mut m = s.serialize_map(Some(1))?;+ m.serialize_entry("not_read", &true)?;+ m.end()+ }}}}@@ -151,7 +164,8 @@ impl Serialize for CellValue {/// One table row.#[derive(Debug, Clone, Serialize)]pub struct Row {- pub rowid: i64,+ /// Absent for WITHOUT ROWID tables.+ pub rowid: Option<i64>,pub values: Vec<CellValue>,}@@ -178,6 +192,7 @@ pub struct RowCount {/// Accumulator for a bounded b-tree row walk: the rows gathered so far, a visited-page set to/// stop cycles, the remaining page-walk budget, how many rows are wanted, and any notes.struct RowWalk {+ index_tree: bool,visited: Vec<u32>,budget: usize,out: Vec<Row>,@@ -188,7 +203,7 @@ struct RowWalk {impl RowWalk {fn new(want: usize) -> Self {- RowWalk { visited: Vec::new(), budget: MAX_PAGES_WALKED, out: Vec::new(), notes: Vec::new(), want }+ RowWalk { index_tree: false, visited: Vec::new(), budget: MAX_PAGES_WALKED, out: Vec::new(), notes: Vec::new(), want }}}@@ -379,12 +394,17 @@ impl<'a> SqliteDb<'a> {schema.into_iter().find(|o| o.name.eq_ignore_ascii_case(name))}- /// Count the rows of the table rooted at `rootpage` by walking its b-tree leaves.+ fn without_rowid_table(&self, rootpage: u32) -> Option<SchemaObject> {+ self.schema().0.into_iter().find(|obj| obj.obj_type == "table" && obj.rootpage == rootpage && is_without_rowid(&obj.sql))+ }++ /// Count the rows of the table rooted at `rootpage`, including interior index records.pub fn count_rows(&self, rootpage: u32) -> RowCount {let mut count: u64 = 0;let mut visited = Vec::new();let mut budget = MAX_PAGES_WALKED;- let bounded = !self.count_leaf_cells(rootpage, 0, &mut visited, &mut budget, &mut count);+ let index_tree = self.btree_header_off(rootpage).and_then(|hdr| self.data.get(hdr)).is_some_and(|ptype| matches!(*ptype, 0x02 | 0x0a));+ let bounded = !self.count_leaf_cells(rootpage, 0, &mut visited, &mut budget, &mut count, index_tree);RowCount { count, bounded }}@@ -394,23 +414,51 @@ impl<'a> SqliteDb<'a> {// Collect offset+limit rows, then drop the leading `offset`.let want = offset.saturating_add(limit);let mut w = RowWalk::new(want);+ let table = self.without_rowid_table(rootpage);+ w.index_tree = table.is_some();self.collect_table_rows(&mut w, rootpage, 0);+ if let Some(table) = table {+ if let Some(order) = without_rowid_order(&table) {+ for row in &mut w.out {+ row.values = order.iter().map(|&i| row.values.get(i).cloned().unwrap_or(CellValue::Null)).collect();+ }+ } else {+ w.notes.push("Could not determine the primary-key column order; values remain in storage order.".into());+ }+ }let hit_cap = w.out.len() >= want && want > 0;let skipped = offset.min(w.out.len());let mut page: Vec<Row> = w.out.into_iter().skip(offset).take(limit).collect();let (schema, _) = self.schema();- if let Some(index) = schema.iter().find(|o| o.obj_type == "table" && o.rootpage == rootpage).and_then(|o| rowid_alias_index(&o.sql)) {+ if let Some(table) = schema.iter().find(|o| o.obj_type == "table" && o.rootpage == rootpage) {+ let defaults: Vec<_> = column_definitions(&table.sql).into_iter().map(|(_, rest)| column_default(rest)).collect();+ let mut unsupported = vec![false; defaults.len()];for row in &mut page {- if let Some(value @ CellValue::Null) = row.values.get_mut(index) {- *value = CellValue::Int(row.rowid);+ for ((value, supported), disclosed) in defaults.iter().zip(&mut unsupported).skip(row.values.len()) {+ row.values.push(value.clone());+ if !supported {+ *disclosed = true;+ }+ }+ }+ for (i, disclosed) in unsupported.into_iter().enumerate() {+ if disclosed {+ w.notes.push(format!("Column {} has an unsupported DEFAULT expression; missing values were filled as NULL.", i + 1));+ }+ }+ if let Some(index) = rowid_alias_index(&table.sql) {+ for row in &mut page {+ if let (Some(rowid), Some(value @ CellValue::Null)) = (row.rowid, row.values.get_mut(index)) {+ *value = CellValue::Int(rowid);+ }}}}RowPage { rows: page, offset: skipped, truncated: hit_cap, notes: w.notes }}- /// Recursively count leaf cells. Returns false when a budget stopped the walk.- fn count_leaf_cells(&self, pageno: u32, depth: usize, visited: &mut Vec<u32>, budget: &mut usize, count: &mut u64) -> bool {+ /// Recursively count rows. Returns false when a budget stopped the walk.+ fn count_leaf_cells(&self, pageno: u32, depth: usize, visited: &mut Vec<u32>, budget: &mut usize, count: &mut u64, index_tree: bool) -> bool {if depth > MAX_DEPTH || *budget == 0 {return false;}@@ -423,11 +471,18 @@ impl<'a> SqliteDb<'a> {let ptype = *self.data.get(hdr).unwrap_or(&0);let ncells = read_u16_be(self.data, hdr.saturating_add(3)).unwrap_or(0) as usize;match ptype {- 0x0d => {+ 0x0d if !index_tree => {+ *count = count.saturating_add(ncells as u64);+ true+ }+ 0x0a if index_tree => {*count = count.saturating_add(ncells as u64);true}- 0x05 => {+ 0x05 | 0x02 if (ptype == 0x02) == index_tree => {+ if index_tree {+ *count = count.saturating_add(ncells as u64);+ }let mut ok = true;// Child pointers live in each cell; the right-most pointer is in the header.for i in 0..ncells {@@ -435,11 +490,11 @@ impl<'a> SqliteDb<'a> {return false;}if let Some(child) = self.interior_child(pageno, hdr, i) {- ok &= self.count_leaf_cells(child, depth + 1, visited, budget, count);+ ok &= self.count_leaf_cells(child, depth + 1, visited, budget, count, index_tree);}}if let Some(right) = read_u32_be(self.data, hdr.saturating_add(8)) {- ok &= self.count_leaf_cells(right, depth + 1, visited, budget, count);+ ok &= self.count_leaf_cells(right, depth + 1, visited, budget, count, index_tree);}ok}@@ -463,20 +518,21 @@ impl<'a> SqliteDb<'a> {let ncells = read_u16_be(self.data, hdr.saturating_add(3)).unwrap_or(0) as usize;let cell_ptr_base = hdr.saturating_add(if ptype == 0x05 || ptype == 0x02 { 12 } else { 8 });match ptype {- 0x0d => {+ 0x0d | 0x0a if (ptype == 0x0a) == w.index_tree => {for i in 0..ncells {if w.want != 0 && w.out.len() >= w.want {return;}let Some(ptr) = read_u16_be(self.data, cell_ptr_base.saturating_add(i * 2)) else { continue };let cell_off = base.saturating_add(ptr as usize);- match self.read_table_leaf_cell(cell_off, &mut w.notes) {+ let row = if w.index_tree { self.read_index_cell(cell_off, &mut w.notes) } else { self.read_table_leaf_cell(cell_off, &mut w.notes) };+ match row {Some(row) => w.out.push(row),None => w.notes.push(format!("Skipped an unreadable row on page {pageno}.")),}}}- 0x05 => {+ 0x05 | 0x02 if (ptype == 0x02) == w.index_tree => {for i in 0..ncells {if (w.want != 0 && w.out.len() >= w.want) || w.budget == 0 {return;@@ -484,6 +540,19 @@ impl<'a> SqliteDb<'a> {if let Some(child) = self.interior_child(pageno, hdr, i) {self.collect_table_rows(w, child, depth + 1);}+ if w.index_tree {+ if w.want != 0 && w.out.len() >= w.want {+ return;+ }+ let row = read_u16_be(self.data, cell_ptr_base.saturating_add(i * 2))+ .and_then(|ptr| base.checked_add(ptr as usize))+ .and_then(|off| off.checked_add(4))+ .and_then(|off| self.read_index_cell(off, &mut w.notes));+ match row {+ Some(row) => w.out.push(row),+ None => w.notes.push(format!("Skipped an unreadable row on page {pageno}.")),+ }+ }}if let Some(right) = read_u32_be(self.data, hdr.saturating_add(8)) {self.collect_table_rows(w, right, depth + 1);@@ -493,7 +562,7 @@ impl<'a> SqliteDb<'a> {}}- /// The left-child page number of cell `i` on an interior table page.+ /// The left-child page number of cell `i` on an interior page.fn interior_child(&self, pageno: u32, hdr: usize, i: usize) -> Option<u32> {let base = self.page_base(pageno)?;let cell_ptr_base = hdr.checked_add(12)?;@@ -507,11 +576,19 @@ impl<'a> SqliteDb<'a> {let (payload_len, n1) = varint(self.data, cell_off)?;let (rowid, n2) = varint(self.data, cell_off.checked_add(n1)?)?;let body_off = cell_off.checked_add(n1)?.checked_add(n2)?;- let payload_len = (payload_len as usize).min(MAX_CELL_SIZE);+ let payload_len = usize::try_from(payload_len).ok()?;let payload = self.assemble_payload(body_off, payload_len, true, notes)?;let values = parse_record(&payload);let rowid = i64::from_le_bytes(rowid.to_le_bytes());- Some(Row { rowid, values })+ Some(Row { rowid: Some(rowid), values })+ }++ /// Index cells hold a whole row, without a rowid, using the index local-payload formula.+ fn read_index_cell(&self, cell_off: usize, notes: &mut Vec<String>) -> Option<Row> {+ let (payload_len, n) = varint(self.data, cell_off)?;+ let payload_len = usize::try_from(payload_len).ok()?;+ let payload = self.assemble_payload(cell_off.checked_add(n)?, payload_len, false, notes)?;+ Some(Row { rowid: None, values: parse_record(&payload) })}/// Assemble a cell payload: the local part plus any overflow-page chain, capped.@@ -547,16 +624,15 @@ impl<'a> SqliteDb<'a> {let Some(chunk) = self.data.get(pbase.checked_add(4)?..pbase.checked_add(4)?.checked_add(per_page).unwrap_or(pbase)) else {break;};- let remaining = payload_len.saturating_sub(out.len());+ let remaining = payload_len.min(MAX_CELL_SIZE).saturating_sub(out.len());let take = remaining.min(chunk.len());out.extend_from_slice(chunk.get(..take)?);next = read_u32_be(self.data, pbase).unwrap_or(0);- if out.len() >= MAX_CELL_SIZE {- notes.push("A value was cut at the cell-size cap.".into());- break;- }}}+ if out.len() < payload_len {+ notes.push("A cell payload was only partially read; some values are truncated or not read.".into());+ }Some(out)}}@@ -588,19 +664,26 @@ fn parse_record(payload: &[u8]) -> Vec<CellValue> {for st in types {let (val, size) = decode_serial(st, payload, body);out.push(val);- body = match body.checked_add(size) {- Some(v) => v,- None => break,- };- if body > payload.len() {- break;- }+ body = body.saturating_add(size);}out}/// Decode one serial-typed value at `off`; returns the value and its byte size.fn decode_serial(serial: u64, data: &[u8], off: usize) -> (CellValue, usize) {+ let size = match serial {+ 1..=4 => serial as usize,+ 5 => 6,+ 6 | 7 => 8,+ n if n >= 12 => usize::try_from((n - 12) / 2).unwrap_or(usize::MAX),+ _ => 0,+ };+ if off > data.len() || (off == data.len() && size != 0) {+ return (CellValue::NotRead, size);+ }+ if serial < 12 && size > data.len().saturating_sub(off) {+ return (CellValue::NotRead, size);+ }match serial {0 => (CellValue::Null, 0),1 => (int_be(data, off, 1), 1),@@ -617,16 +700,23 @@ fn decode_serial(serial: u64, data: &[u8], off: usize) -> (CellValue, usize) {9 => (CellValue::Int(1), 0),10 | 11 => (CellValue::Null, 0), // reserved for internal use.n if n >= 12 && n % 2 == 0 => {- let len = ((n - 12) / 2) as usize;- let slice = data.get(off..off.saturating_add(len)).unwrap_or(&[]);- (blob_value(slice, len), len)+ let len = size;+ let slice = data.get(off..off.saturating_add(len).min(data.len())).unwrap_or(&[]);+ let value = if slice.len() < len { CellValue::PartialBlob { len } } else { blob_value(slice, len) };+ (value, len)}- n => {+ _ => {// Odd and >= 13: text of (n-13)/2 bytes (encoding handled by the caller's DB header;// decoded here as UTF-8 lossily, which is correct for the common case).- let len = ((n - 13) / 2) as usize;- let slice = data.get(off..off.saturating_add(len)).unwrap_or(&[]);- (text_value(slice), len)+ let len = size;+ let slice = data.get(off..off.saturating_add(len).min(data.len())).unwrap_or(&[]);+ let mut value = text_value(slice);+ if slice.len() < len+ && let CellValue::Text { truncated, .. } = &mut value+ {+ *truncated = true;+ }+ (value, len)}}}@@ -653,26 +743,76 @@ fn blob_value(slice: &[u8], len: usize) -> CellValue {CellValue::Blob { len, sha256_prefix: prefix }}+fn is_without_rowid(sql: &str) -> bool {+ let Some(close) = sql.rfind(')') else { return false };+ sql_tokens(close.checked_add(1).and_then(|start| sql.get(start..)).unwrap_or(""))+ .windows(2)+ .any(|pair| pair.first().is_some_and(|s| s.eq_ignore_ascii_case("WITHOUT")) && pair.get(1).is_some_and(|s| s.eq_ignore_ascii_case("ROWID")))+}++/// Output-column positions in the stored record: PK columns first, then all remaining columns.+fn without_rowid_order(table: &SchemaObject) -> Option<Vec<usize>> {+ let open = table.sql.find('(')?;+ let close = table.sql.rfind(')')?;+ let body = table.sql.get(open.checked_add(1)?..close)?;+ let mut stored = Vec::new();+ for segment in split_top_level(body) {+ let tokens = sql_tokens(segment);+ let Some(pk) = tokens+ .windows(2)+ .position(|pair| pair.first().is_some_and(|s| s.eq_ignore_ascii_case("PRIMARY")) && pair.get(1).is_some_and(|s| s.eq_ignore_ascii_case("KEY")))+ else {+ continue;+ };+ let table_constraint = tokens.first().is_some_and(|s| s.eq_ignore_ascii_case("PRIMARY") || s.eq_ignore_ascii_case("CONSTRAINT"));+ let names: Vec<&str> = if table_constraint {+ let tail = tokens.get(pk.checked_add(3)?..)?;+ let end = tail.iter().position(|s| *s == ")")?;+ tail.get(..end)?.split(|s| *s == ",").filter_map(|part| part.first().copied()).collect()+ } else {+ vec![*tokens.first()?]+ };+ for token in names {+ let (name, _) = take_identifier(token);+ let position = table.columns.iter().position(|column| column.name.eq_ignore_ascii_case(&name))?;+ if !stored.contains(&position) {+ stored.push(position);+ }+ }+ }+ if stored.is_empty() {+ return None;+ }+ for i in 0..table.columns.len() {+ if !stored.contains(&i) {+ stored.push(i);+ }+ }+ (0..table.columns.len()).map(|i| stored.iter().position(|&column| column == i)).collect()+}+/// Parse column names and types from a CREATE TABLE statement (best effort, bounded).pub fn parse_create_columns(sql: &str) -> Vec<Column> {+ column_definitions(sql).into_iter().map(|(column, _)| column).collect()+}++fn column_definitions(sql: &str) -> Vec<(Column, &str)> {let mut cols = Vec::new();// Take the text inside the outermost parentheses.let Some(open) = sql.find('(') else { return cols };let inner = &sql[open + 1..];- let mut depth = 1i32;+ let mut depth = 1usize;let mut end = inner.len();- for (i, c) in inner.char_indices() {- match c {- '(' => depth += 1,- ')' => {- depth -= 1;- if depth == 0 {- end = i;- break;- }- }+ for token in sql_tokens(inner) {+ match token {+ "(" => depth = depth.saturating_add(1),+ ")" => depth = depth.saturating_sub(1),_ => {}}+ if depth == 0 {+ end = (token.as_ptr() as usize).saturating_sub(inner.as_ptr() as usize);+ break;+ }}let body = inner.get(..end).unwrap_or("");for seg in split_top_level(body) {@@ -693,7 +833,7 @@ pub fn parse_create_columns(sql: &str) -> Vec<Column> {continue;}let type_name = extract_type(rest.trim());- cols.push(Column { name, type_name });+ cols.push((Column { name, type_name }, rest));}cols}@@ -803,8 +943,8 @@ fn sql_tokens(mut sql: &str) -> Vec<&str> {}}}- } else if !matches!(first, '(' | ')' | ',') {- end = sql.find(|c: char| c.is_whitespace() || matches!(c, '(' | ')' | ',' | '\'' | '"' | '`' | '[')).unwrap_or(sql.len());+ } else if !matches!(first, '(' | ')' | ',' | '/') {+ end = sql.find(|c: char| c.is_whitespace() || matches!(c, '(' | ')' | ',' | '\'' | '"' | '`' | '[' | '/')).unwrap_or(sql.len());}tokens.push(sql.get(..end).unwrap_or(""));sql = sql.get(end..).unwrap_or("");@@ -812,6 +952,72 @@ fn sql_tokens(mut sql: &str) -> Vec<&str> {tokens}+/// Missing trailing fields use literal defaults; expressions remain explicitly unknown.+fn column_default(rest: &str) -> (CellValue, bool) {+ let tokens = sql_tokens(rest);+ let mut depth = 0usize;+ for (i, token) in tokens.iter().enumerate() {+ if depth == 0 && token.eq_ignore_ascii_case("DEFAULT") {+ return tokens.get(i.saturating_add(1)..).and_then(literal_default).map(|v| (v, true)).unwrap_or((CellValue::Null, false));+ }+ match *token {+ "(" => depth = depth.saturating_add(1),+ ")" => depth = depth.saturating_sub(1),+ _ => {}+ }+ }+ (CellValue::Null, true)+}++fn literal_default(tokens: &[&str]) -> Option<CellValue> {+ let token = *tokens.first()?;+ if token.eq_ignore_ascii_case("NULL") {+ return Some(CellValue::Null);+ }+ if token.eq_ignore_ascii_case("TRUE") || token.eq_ignore_ascii_case("FALSE") {+ return Some(CellValue::Int(i64::from(token.eq_ignore_ascii_case("TRUE"))));+ }+ if token.starts_with('\'') && token.ends_with('\'') && token.len() >= 2 {+ return Some(text_value(token.get(1..token.len().checked_sub(1)?)?.replace("''", "'").as_bytes()));+ }+ if token.eq_ignore_ascii_case("X") {+ let quoted = *tokens.get(1)?;+ if !quoted.starts_with('\'') || !quoted.ends_with('\'') || quoted.len() < 2 {+ return None;+ }+ let hex = quoted.get(1..quoted.len().checked_sub(1)?)?;+ if !hex.len().is_multiple_of(2) {+ return None;+ }+ let bytes: Option<Vec<u8>> = hex+ .as_bytes()+ .as_chunks::<2>()+ .0+ .iter()+ .map(|pair| {+ let high = char::from(*pair.first()?).to_digit(16)?;+ let low = char::from(*pair.get(1)?).to_digit(16)?;+ Some((high * 16 + low) as u8)+ })+ .collect();+ let bytes = bytes?;+ return Some(blob_value(&bytes, bytes.len()));+ }+ let number = if matches!(token, "+" | "-") {+ let value = *tokens.get(1)?;+ format!("{token}{value}")+ } else {+ token.to_owned()+ };+ if !number.bytes().all(|b| b.is_ascii_digit() || matches!(b, b'+' | b'-' | b'.' | b'e' | b'E')) {+ return None;+ }+ if let Ok(n) = number.parse::<i64>() {+ return Some(CellValue::Int(n));+ }+ number.parse::<f64>().ok().filter(|n| n.is_finite()).map(CellValue::Real)+}+/// Split on top-level commas (ignoring commas inside parentheses).fn split_top_level(s: &str) -> Vec<&str> {let mut out = Vec::new();@@ -902,6 +1108,184 @@ fn extract_type(rest: &str) -> String {mod tests {use super::*;+ fn payload_cap_case(case: u8) {+ use craft_anything_testkit::sqlite::{Val, overflow_row_db};+ use sha2::Digest as _;+ let values = match case {+ 1 => vec![Val::Text("x".repeat(8_000_000))],+ 2 => vec![Val::Text("x".repeat(8_400_000))],+ 3 => vec![Val::Blob(vec![0x5a; 8_400_000])],+ 4 => vec![Val::Text("x".repeat(4_300_000)), Val::Blob(vec![0x5a; 4_300_000])],+ 5 => vec![Val::Int(42), Val::Blob(vec![0x5a; 8_400_000]), Val::Int(73)],+ 6 => vec![Val::Blob(vec![0x5a; 1_000_000])],+ _ => panic!("unknown payload-cap case"),+ };+ let bytes = overflow_row_db(&values);+ let db = SqliteDb::parse(&bytes).expect("fixture parses");+ let page = db.read_rows(2, 0, 1);+ assert_eq!(page.rows.len(), 1);+ let row = &page.rows[0];+ assert_eq!(row.values.len(), values.len(), "d{case}: every column is present");+ for (i, source) in values.iter().enumerate() {+ let value = serde_json::to_value(&row.values[i]).expect("serializes");+ match source {+ Val::Text(_) => assert_eq!(value, serde_json::json!({"text": "x".repeat(MAX_TEXT), "truncated": true}), "d{case}: text prefix"),+ Val::Blob(blob) => {+ assert_eq!(value["blob_len"], blob.len(), "d{case}: true blob length");+ if case == 6 {+ let hash: String = sha2::Sha256::digest(blob).iter().take(8).map(|b| format!("{b:02x}")).collect();+ assert_eq!(value, serde_json::json!({"blob_len": blob.len(), "sha256_prefix": hash}));+ } else {+ assert_eq!(value["truncated"], true, "d{case}: partial blob marked");+ assert!(value.get("sha256_prefix").is_none_or(serde_json::Value::is_null), "d{case}: no partial hash");+ }+ }+ Val::Int(n) if i == 0 => assert_eq!(value, *n),+ Val::Int(_) => assert_eq!(value, serde_json::json!({"not_read": true})),+ _ => panic!("unexpected payload-cap fixture value"),+ }+ }+ assert_eq!(page.notes.is_empty(), matches!(case, 1 | 6), "d{case}: cap disclosure");+ }++ #[test]+ fn payload_cap_d1() {+ payload_cap_case(1);+ }+ #[test]+ fn payload_cap_d2() {+ payload_cap_case(2);+ }+ #[test]+ fn payload_cap_d3() {+ payload_cap_case(3);+ }+ #[test]+ fn payload_cap_d4() {+ payload_cap_case(4);+ }+ #[test]+ fn payload_cap_d5() {+ payload_cap_case(5);+ }+ #[test]+ fn payload_cap_d6() {+ payload_cap_case(6);+ }++ #[test]+ fn payload_cap_d7_without_rowid() {+ use craft_anything_testkit::sqlite::{Val, without_rowid_db};+ let bytes = without_rowid_db(+ "CREATE TABLE t(v BLOB, k INT PRIMARY KEY, tail INT) WITHOUT ROWID",+ &[vec![Val::Int(42), Val::Blob(vec![0x5a; 8_400_000]), Val::Int(73)]],+ );+ let page = SqliteDb::parse(&bytes).expect("fixture").read_rows(2, 0, 10);+ assert_eq!(page.rows.len(), 1, "d7: capped index rows must remain present");+ assert_eq!(page.rows[0].rowid, None);+ assert_eq!(+ serde_json::to_value(&page.rows[0].values).unwrap(),+ serde_json::json!([+ {"blob_len": 8_400_000, "truncated": true}, 42, {"not_read": true}+ ])+ );+ assert!(!page.notes.is_empty(), "d7: cap disclosure");+ }++ fn short_record_case(declarations: &str, defaults: Vec<CellValue>, note: bool) {+ use craft_anything_testkit::sqlite::{Val, table_db};+ let mut full = vec![Val::Int(2)];+ full.extend(defaults.iter().map(|v| match v {+ CellValue::Int(n) => Val::Int(*n),+ CellValue::Real(n) => Val::Real(*n),+ CellValue::Text { text, .. } => Val::Text(text.clone()),+ CellValue::Blob { .. } => Val::Blob(vec![0, 255]),+ CellValue::Null => Val::Null,+ _ => panic!("unexpected default fixture value"),+ }));+ let bytes = table_db(&format!("CREATE TABLE t(n INT, {declarations})"), &[(1, vec![Val::Int(1)]), (2, full)]);+ let db = SqliteDb::parse(&bytes).expect("fixture");+ let page = db.read_rows(2, 0, 10);+ let mut expected = vec![CellValue::Int(1)];+ expected.extend(defaults.clone());+ assert_eq!(page.rows[0].values, expected, "old record must include trailing defaults");+ expected[0] = CellValue::Int(2);+ assert_eq!(page.rows[1].values, expected, "full record must stay unchanged");+ assert_eq!(!page.notes.is_empty(), note, "unsupported defaults must be disclosed");+ }++ #[test]+ fn added_columns_c1_integer() {+ short_record_case("x INT DEFAULT 42", vec![CellValue::Int(42)], false);+ }+ #[test]+ fn added_columns_c2_null() {+ short_record_case("x INT", vec![CellValue::Null], false);+ }+ #[test]+ fn added_columns_c3_real_text() {+ short_record_case("x REAL DEFAULT -1.5, y TEXT DEFAULT 'it''s'", vec![CellValue::Real(-1.5), text_value(b"it's")], false);+ }+ #[test]+ fn added_columns_c4_blob() {+ short_record_case("x BLOB DEFAULT X'00ff'", vec![blob_value(&[0, 255], 2)], false);+ }+ #[test]+ fn added_columns_c7_expression() {+ short_record_case("d TEXT DEFAULT (lower('A'))", vec![CellValue::Null], true);+ }+ #[test]+ fn added_columns_c5_rewritten_control() {+ use craft_anything_testkit::sqlite::{Val, table_db};+ let bytes = table_db("CREATE TABLE t(n INT, x INT DEFAULT 42)", &[(1, vec![Val::Int(1), Val::Int(42)])]);+ let page = SqliteDb::parse(&bytes).expect("fixture").read_rows(2, 0, 10);+ assert_eq!(page.rows[0].values, vec![CellValue::Int(1), CellValue::Int(42)]);+ assert!(page.notes.is_empty());+ }++ #[test]+ fn added_columns_literal_forms_and_unknowns() {+ for (declaration, value) in [+ ("x INT DEFAULT +42 NOT NULL", CellValue::Int(42)),+ ("x INT DEFAULT - 42", CellValue::Int(-42)),+ ("x REAL DEFAULT + 1.25e-2", CellValue::Real(0.0125)),+ ("x INT DEFAULT true", CellValue::Int(1)),+ ("x INT DEFAULT FALSE", CellValue::Int(0)),+ ("x DEFAULT null", CellValue::Null),+ ("x TEXT DEFAULT 'a),b''c'", text_value(b"a),b'c")),+ ("x INT CHECK(x <> 'DEFAULT') DEFAULT /* literal */ 7", CellValue::Int(7)),+ ] {+ short_record_case(declaration, vec![value], false);+ }+ for declaration in ["x TEXT DEFAULT CURRENT_TIMESTAMP", "x DEFAULT (42)", "x DEFAULT (lower('A'))", "x DEFAULT X'zz'"] {+ short_record_case(declaration, vec![CellValue::Null], true);+ }+ assert_eq!(blob_value(&[0, 255], 2), CellValue::Blob { len: 2, sha256_prefix: "06eb7d6a69ee19e5".into() });+ assert_eq!(literal_default(&sql_tokens("x''")), Some(blob_value(&[], 0)));+ }++ #[test]+ fn added_columns_preserve_stored_nulls_and_long_records() {+ use craft_anything_testkit::sqlite::{Val, table_db};+ let bytes = table_db("CREATE TABLE t(n INT, x INT DEFAULT 42)", &[(1, vec![Val::Int(1), Val::Null]), (2, vec![Val::Int(2), Val::Int(7), Val::Int(9)])]);+ let page = SqliteDb::parse(&bytes).expect("fixture").read_rows(2, 0, 10);+ assert_eq!(page.rows[0].values, vec![CellValue::Int(1), CellValue::Null]);+ assert_eq!(page.rows[1].values, vec![CellValue::Int(2), CellValue::Int(7), CellValue::Int(9)]);+ assert!(page.notes.is_empty());+ }++ #[test]+ fn added_columns_c6_short_rowid_alias() {+ use craft_anything_testkit::sqlite::{Val, table_db};+ for stored in [vec![Val::Null, Val::Int(10)], vec![]] {+ let bytes = table_db("CREATE TABLE t(id INTEGER PRIMARY KEY, n INT DEFAULT 10, x INT DEFAULT 42)", &[(7, stored)]);+ let page = SqliteDb::parse(&bytes).expect("fixture").read_rows(2, 0, 10);+ assert_eq!(page.rows[0].rowid, Some(7));+ assert_eq!(page.rows[0].values, vec![CellValue::Int(7), CellValue::Int(10), CellValue::Int(42)]);+ assert!(page.notes.is_empty());+ }+ }+#[test]fn version_formatting() {assert_eq!(version_string(3_045_001), "3.45.1");@@ -972,7 +1356,7 @@ mod tests {let page = parsed.read_rows(items.rootpage, 0, 10);assert_eq!(page.rows.len(), 3);- assert_eq!(page.rows[0].rowid, 1);+ assert_eq!(page.rows[0].rowid, Some(1));assert_eq!(page.rows[0].values[0], CellValue::Int(1));assert_eq!(page.rows[0].values[1], CellValue::Text { text: "alpha".into(), truncated: false });assert_eq!(page.rows[0].values[2], CellValue::Real(1.5));@@ -985,7 +1369,7 @@ mod tests {// Paging: offset 1, limit 1 yields the second row only.let mid = parsed.read_rows(items.rootpage, 1, 1);assert_eq!(mid.rows.len(), 1);- assert_eq!(mid.rows[0].rowid, 2);+ assert_eq!(mid.rows[0].rowid, Some(2));// find_object is case-insensitive.assert!(parsed.find_object("ITEMS").is_some());@@ -1017,7 +1401,7 @@ mod tests {let page = db.read_rows(2, 0, 10);assert_eq!(page.rows.len(), 2);for (row, (rowid, _)) in page.rows.iter().zip(&rows) {- assert_eq!(row.rowid, *rowid);+ assert_eq!(row.rowid, Some(*rowid));let mut expected = vec![CellValue::Text { text: "x".into(), truncated: false }; columns.len()];expected[column] = if alias { CellValue::Int(*rowid) } else { CellValue::Null };assert_eq!(row.values, expected, "{declaration}, rowid {rowid}");@@ -1053,11 +1437,9 @@ mod tests {#[test]fn a_without_rowid_table_has_no_rowid_alias() {- // Only test alias classification here; index b-tree reading is a separate defect.- let sql = "CREATE TABLE t(id INTEGER PRIMARY KEY) WITHOUT ROWID";- let bytes = craft_anything_testkit::sqlite::table_db(sql, &[(7, vec![craft_anything_testkit::sqlite::Val::Null])]);- let db = SqliteDb::parse(&bytes).expect("fixture parses");- assert_eq!(db.read_rows(2, 0, 1).rows[0].values, vec![CellValue::Null]);+ // Read through the index b-tree (database_tools `without_rowid_b4_integer_key` covers the rows).+ assert_eq!(rowid_alias_index("CREATE TABLE t(id INTEGER PRIMARY KEY) WITHOUT ROWID"), None);+ assert_eq!(rowid_alias_index("CREATE TABLE t(id INTEGER PRIMARY KEY)"), Some(0));}#[test]@@ -1105,6 +1487,27 @@ mod tests {}}+ #[test]+ fn without_rowid_damaged_pages_never_panic() {+ use craft_anything_testkit::sqlite::{Val, without_rowid_db};+ let rows = (0..9).map(|i| vec![Val::Int(i), Val::Text("x".repeat(2000))]).collect::<Vec<_>>();+ let base = without_rowid_db("CREATE TABLE t(k INT PRIMARY KEY, v TEXT) WITHOUT ROWID", &rows);+ for cut in (100..base.len()).step_by(31) {+ let db = SqliteDb::parse(&base[..cut]).unwrap();+ let _ = db.count_rows(2);+ let _ = db.read_rows(2, 1, 20);+ }+ for off in 4096..4120 {+ for value in [0, 2, 10, 255] {+ let mut bytes = base.clone();+ bytes[off] = value;+ let db = SqliteDb::parse(&bytes).unwrap();+ let _ = db.count_rows(2);+ let _ = db.read_rows(2, 0, 20);+ }+ }+ }+#[test]fn decode_serial_types() {assert_eq!(decode_serial(0, &[], 0).0, CellValue::Null);diff --git a/crates/testkit/src/sqlite.rs b/crates/testkit/src/sqlite.rsindex 80fe1053..b90dbb35 100644--- a/crates/testkit/src/sqlite.rs+++ b/crates/testkit/src/sqlite.rs@@ -196,6 +196,48 @@ pub fn table_db(sql: &str, rows: &[(i64, Vec<Val>)]) -> Vec<u8> {file}+/// Build one table row, spilling its record over a chain of overflow pages.+pub fn overflow_row_db(values: &[Val]) -> Vec<u8> {+ let record = build_record(values);+ let max_local = PAGE_SIZE - 35;+ let min_local = (PAGE_SIZE - 12) * 32 / 255 - 23;+ let candidate = min_local + (record.len().saturating_sub(min_local) % (PAGE_SIZE - 4));+ let local = if record.len() <= max_local {+ record.len()+ } else if candidate <= max_local {+ candidate+ } else {+ min_local+ };+ let overflow = &record[local..];+ let pages = 2 + overflow.len().div_ceil(PAGE_SIZE - 4);+ let mut file = vec![0; pages * PAGE_SIZE];+ write_db_header(&mut file[..PAGE_SIZE], pages as u32);+ let sql = format!("CREATE TABLE items({})", (0..values.len()).map(|i| format!("c{i}")).collect::<Vec<_>>().join(", "));+ let schema = build_record(&[Val::Text("table".into()), Val::Text("items".into()), Val::Text("items".into()), Val::Int(2), Val::Text(sql)]);+ write_table_leaf(&mut file[..PAGE_SIZE], 100, &[(1, schema)]);+ let mut cell = sqlite_varint(record.len() as u64);+ cell.extend(sqlite_varint(1));+ cell.extend_from_slice(&record[..local]);+ if !overflow.is_empty() {+ cell.extend_from_slice(&3u32.to_be_bytes());+ }+ let top = PAGE_SIZE - cell.len();+ let leaf = &mut file[PAGE_SIZE..2 * PAGE_SIZE];+ leaf[0] = 0x0d;+ leaf[3..5].copy_from_slice(&1u16.to_be_bytes());+ leaf[5..7].copy_from_slice(&(top as u16).to_be_bytes());+ leaf[8..10].copy_from_slice(&(top as u16).to_be_bytes());+ leaf[top..].copy_from_slice(&cell);+ for (i, chunk) in overflow.chunks(PAGE_SIZE - 4).enumerate() {+ let base = (i + 2) * PAGE_SIZE;+ let next = if i + 3 < pages { (i + 4) as u32 } else { 0 };+ file[base..base + 4].copy_from_slice(&next.to_be_bytes());+ file[base + 4..base + 4 + chunk.len()].copy_from_slice(chunk);+ }+ file+}+/// A database whose header declares WAL mode (write/read version 2) but no sidecar is present.pub fn wal_mode_db() -> Vec<u8> {let mut db = simple_db();@@ -204,6 +246,115 @@ pub fn wal_mode_db() -> Vec<u8> {db}+/// Build a WITHOUT ROWID table from records already sorted and arranged in storage order.+pub fn without_rowid_db(sql: &str, rows: &[Vec<Val>]) -> Vec<u8> {+ fn cell(file: &mut Vec<u8>, record: &[u8]) -> Vec<u8> {+ let max = (PAGE_SIZE - 12) * 64 / 255 - 23;+ let min = (PAGE_SIZE - 12) * 32 / 255 - 23;+ let local = if record.len() <= max {+ record.len()+ } else {+ let candidate = min + (record.len() - min) % (PAGE_SIZE - 4);+ if candidate <= max { candidate } else { min }+ };+ let mut out = sqlite_varint(record.len() as u64);+ out.extend_from_slice(&record[..local]);+ if local < record.len() {+ out.extend_from_slice(&((file.len() / PAGE_SIZE + 1) as u32).to_be_bytes());+ for (i, chunk) in record[local..].chunks(PAGE_SIZE - 4).enumerate() {+ let base = file.len();+ file.resize(base + PAGE_SIZE, 0);+ if local + (i + 1) * (PAGE_SIZE - 4) < record.len() {+ file[base..base + 4].copy_from_slice(&((base / PAGE_SIZE + 2) as u32).to_be_bytes());+ }+ file[base + 4..base + 4 + chunk.len()].copy_from_slice(chunk);+ }+ }+ out+ }+ fn tree(file: &mut Vec<u8>, rows: &[Vec<Val>], height: u32) -> u32 {+ let base = file.len();+ let page = (base / PAGE_SIZE + 1) as u32;+ file.resize(base + PAGE_SIZE, 0);+ let interior = height > 0;+ let mut cells = Vec::new();+ let mut right = 0;+ if interior {+ // Up to four children; every leaf is at the same depth.+ let children = (rows.len() + 1).div_ceil(4usize.pow(height)).max(2);+ let mut start = 0;+ for i in 0..children {+ let remaining_children = children - i;+ let len = (rows.len() - start - (remaining_children - 1)) / remaining_children;+ let child = tree(file, &rows[start..start + len], height - 1);+ start += len;+ if i + 1 == children {+ right = child;+ } else {+ let mut entry = child.to_be_bytes().to_vec();+ entry.extend_from_slice(&cell(file, &build_record(&rows[start])));+ cells.push(entry);+ start += 1;+ }+ }+ } else {+ for row in rows {+ cells.push(cell(file, &build_record(row)));+ }+ }+ let page_bytes = &mut file[base..base + PAGE_SIZE];+ page_bytes[0] = if interior { 2 } else { 10 };+ page_bytes[3..5].copy_from_slice(&(cells.len() as u16).to_be_bytes());+ let header = if interior { 12 } else { 8 };+ if interior {+ page_bytes[8..12].copy_from_slice(&right.to_be_bytes());+ }+ let mut top = PAGE_SIZE;+ for (i, entry) in cells.iter().enumerate() {+ top -= entry.len();+ page_bytes[top..top + entry.len()].copy_from_slice(entry);+ page_bytes[header + 2 * i..header + 2 * i + 2].copy_from_slice(&(top as u16).to_be_bytes());+ }+ page_bytes[5..7].copy_from_slice(&(top as u16).to_be_bytes());+ page+ }+ let mut file = vec![0; PAGE_SIZE];+ let mut height = 0;+ let mut capacity = 3;+ while rows.len() > capacity {+ height += 1;+ capacity = capacity * 4 + 3;+ }+ let root = tree(&mut file, rows, height);+ let schema = build_record(&[Val::Text("table".into()), Val::Text("t".into()), Val::Text("t".into()), Val::Int(root.into()), Val::Text(sql.into())]);+ let pages = (file.len() / PAGE_SIZE) as u32;+ write_db_header(&mut file[..PAGE_SIZE], pages);+ write_table_leaf(&mut file[..PAGE_SIZE], 100, &[(1, schema)]);+ file+}++/// A rowid table with a separate secondary index (the index must not contribute rows).+pub fn indexed_rowid_db() -> Vec<u8> {+ let mut file = vec![0; PAGE_SIZE * 3];+ write_db_header(&mut file[..PAGE_SIZE], 3);+ let schema: Vec<_> = [("table", "t", 2, "CREATE TABLE t(a TEXT, b INT)"), ("index", "ti", 3, "CREATE INDEX ti ON t(a)")]+ .into_iter()+ .enumerate()+ .map(|(i, (kind, name, root, sql))| {+ (i as i64 + 1, build_record(&[Val::Text(kind.into()), Val::Text(name.into()), Val::Text("t".into()), Val::Int(root), Val::Text(sql.into())]))+ })+ .collect();+ write_table_leaf(&mut file[..PAGE_SIZE], 100, &schema);+ let rows = [(1, build_record(&[Val::Text("z".into()), Val::Int(1)])), (2, build_record(&[Val::Text("a".into()), Val::Int(2)]))];+ write_table_leaf(&mut file[PAGE_SIZE..PAGE_SIZE * 2], 0, &rows);+ let index = without_rowid_db(+ "CREATE TABLE t(a TEXT PRIMARY KEY) WITHOUT ROWID",+ &[vec![Val::Text("a".into()), Val::Int(2)], vec![Val::Text("z".into()), Val::Int(1)]],+ );+ file[PAGE_SIZE * 2..].copy_from_slice(&index[PAGE_SIZE..PAGE_SIZE * 2]);+ file+}+#[cfg(test)]mod tests {use super::*;diff --git a/docs/ROADMAP.md b/docs/ROADMAP.mdindex 97187a69..b26fea13 100644--- a/docs/ROADMAP.md+++ b/docs/ROADMAP.md@@ -141,7 +141,10 @@ No `deny.toml` exists. The survey found no GPL, AGPL or SSPL crates, and only MP### R0.5 Small correctness items from the surveyOwner: open · Status: done (branch chore/r0.5-cleanups)+- [x] Disclosed partially read SQLite cell payloads, preserved column positions, and withheld hashes of incomplete BLOBs.+- [x] Filled missing trailing SQLite record fields from literal column defaults and disclosed unsupported defaults as NULL.- [x] Restored rowid aliases in SQLite INTEGER primary-key columns while preserving stored values and non-alias keys.+- [x] Read and counted WITHOUT ROWID table records from leaf and interior index pages, restored declaration column order, and reported absent rowids as null.- [x] Decode Objective-C chained pointer offsets past file-empty PAGEZERO mappings (#296).- [x] Recognise root-relative macOS bundles and nested XPC services in Apple app graphs (#282).- [x] Checked arithmetic on file offsets in `elf.rs`: `va_to_off` adds a segment's file offset to andiff --git a/docs/STATUS.md b/docs/STATUS.mdindex b4c36d96..95ae98c7 100644--- a/docs/STATUS.md+++ b/docs/STATUS.md@@ -8,6 +8,8 @@ workspace clippy, layers, fmt and the secret scan of all history were clean. Chi| Area | State | Verified by ||---|---|---|+| SQLite payload limits | Capped records retain column positions, disclose partial TEXT and BLOB values, omit incomplete BLOB hashes, and report partial coverage with read notes | Hand-built overflow-page regressions for five oversized records (including WITHOUT ROWID in declaration order) and two controls; table and index engine coverage and limitation regressions |+| SQLite added columns | Short records include missing trailing fields using literal column defaults, or NULL when absent; unsupported default expressions produce NULL with a row note. Stored fields and records longer than the schema retain their values. Defaults are filled before restoring rowid aliases | Nine hand-built parser regressions and an engine tool test cover added-column defaults, rewritten records and short records with a rowid alias, including a missing alias field || Mach-O Objective-C pointers | Chained offsets mapped only into file-empty `__PAGEZERO` reach the image-base fallback; pointer candidates must be backed by file bytes | Synthetic thin and fat Mach-O regression, plain-pointer and authenticated-rebase controls, null and unmapped-pointer checks. Real binaries were not checked for this correction || Apple app graphs | Selecting a macOS bundle recognises its root-relative `Contents/Info.plist` and retains its service/extension type; nested XPC bundles appear in `services` and as `xpc-service` graph nodes, including their executables when hosted in frameworks | Synthetic inventory tests, including parent-directory and flat bundle layouts, selected services/extensions, framework-hosted service executables, and bare-program controls. Ordinary selected directories with `Contents/Info.plist` need an Apple bundle suffix; archives retain layout-based recognition. Framework libraries and dylibs stay excluded from executables. Real app bundles were not checked for this correction || Chinese UI | Simplified (`zh-hans`) and Traditional (`zh-hant`) Chinese in Settings → General → Language; System chooses a supported OS language, otherwise English. Both catalogs cover UI controls and tool titles; translated titles are searchable. Raw tool data, AI text, logs, CLI/MCP and the separate browser viewer keep their original text. See [localisation](localization.md). | Catalog integrity and locale-resolution tests; `cargo xtask i18n-coverage`; isolated UI language-switch test. Platform visual checks are recorded separately. |@@ -35,6 +37,7 @@ workspace clippy, layers, fmt and the secret scan of all history were clean. Chi| Desktop app | Simple mode: sidebar with New project and the project history (kept across restarts); New project either makes something or just looks inside an app or file, a website or a game's files; a Game files screen (a game's archives; pictures from Unreal paks, Unity .assets files and Unity bundles saved as PNG after the person confirms they may unpack the game; uncompressed textures and the block formats DXT1, DXT5 and BC4–BC7), make prompt with picture attachments and, for anything recreated, a Clean room / Deep choice (also in the title bar; in Clean room, Just look inside, Game files, opening a file and the workbench ask for Deep mode instead), project screen (steps with the time spent and the AI cost and tokens of every build, saved in the project's usage.json by the run (a coding agent's figure is shown as an estimate at API prices, not the bill), what the build is on now and its activity as it arrives (kept in `build-activity.log`), pinned builder checklist, feed, question and approval cards, a Continue card when a build was paused or stopped part-way (the app or computer closed; the project shows Interrupted) that carries on the builder's own session instead of starting over, and "It's done" beside Continue or Try again to keep the build as it is (`project_build_finish`), checks with screenshots and the requirements not met yet, the builder's open questions, preview, play, folder, follow-ups while it builds, which Claude Code takes at its next step; Up in the prompt box takes back the last note still waiting). Projects can start in a folder the person picks, whose files are either the app, edited in place, or material to start from (asked, or the answer remembered in Settings), and are listed from any number of folders (`project_folders`, `project_list`, `rebuild --project-folder`). Make says which AI builds ("Built by": automatic, or any AI that can build, by name); a pick stays with the project and builds its later changes. With nothing to build with, Start offers the coding agents found on the computer. Settings → AI turns an AI off or removes it, and sets how hard the Claude API or Claude Code thinks (every Claude level, low to max; also `ai effort` in the CLI). In the prompt box, Up at the very start and Down at the very end go through earlier prompts when no note is waiting. Questions about a build ("Just ask" under the prompt box, or a message starting with `/btw`, the first slash command; `rebuild_question_ask`) are answered in the conversation, where each folds away and is kept in the project, without a build or a round and changing nothing: Claude Code answers from a read-only copy of the builder's own session. Under each project's prompt box, "Builder's questions: Ask me / Decide yourself" chooses whether the builder's questions come to the person as cards or are decided by the builder, which says what it chose (`project_questions_set`; the default is in Settings and follows Auto mode until picked). Projects can be renamed, duplicated and deleted (right-click in the sidebar, or the project's page; a delete keeps the person's own files). A build can be pinned (Pin this build on its page, or `project_pin_*` from the CLI and MCP): a frozen copy in the project's pinned/ folder (the default) or a light one that shares dependencies and media with the project through hard links (each one's size shown first), opened from the sidebar's collapsible Pinned section (icons with a running dot when folded); a pin or Play runs once per folder unless another copy is asked for, and a start that quits at once says so with its last output. Typed drafts survive a restart. In a narrow window the sidebar folds to icons and the project's details move above its feed; messages float over the screen and errors stay until dismissed. Advanced mode: workbench with every panel wired to real tools, as a screen beside the projects (builds and their questions stay a click away) | UI unit and smoke tests (egui_kittest), offscreen snapshots of every screen || CLI | Every tool, `--deep` or `--clean-room` for one run (never saved), `rebuild` (including `--continue-in`, and `--resume` to carry on a stopped build), `mcp --inbox`, `ai`, `setup`, `doctor`, `report` | CLI integration tests || SQLite database files (`db_sqlite_show`) | A rowid alias column (`INTEGER PRIMARY KEY`, including the table-constraint form) shows the rowid; `DESC`, non-`INTEGER` and composite keys keep their stored values | Hand-built fixtures; generated files compared with the official SQLite library |+| SQLite WITHOUT ROWID tables | Read from the index b-tree, interior records and overflow included; rows in primary-key order, values in declaration order, `rowid` null | Hand-built fixtures; generated files compared with the official SQLite library |### Bun stored-text encoding