From 668ae1bd9db918b97d5c0229948ffe44bb9defe9 Mon Sep 17 00:00:00 2001 From: Ishan Jain Date: Wed, 20 Jul 2022 15:11:10 +0530 Subject: [PATCH] read table row count --- src/main.rs | 45 ++++++++++++++++++++++++++++++++++++++++++--- src/schema.rs | 2 +- 2 files changed, 43 insertions(+), 4 deletions(-) diff --git a/src/main.rs b/src/main.rs index 379502e..d73b1d6 100644 --- a/src/main.rs +++ b/src/main.rs @@ -12,7 +12,7 @@ fn main() -> Result<()> { match args.len() { 0 | 1 => bail!("Missing and "), 2 => bail!("Missing "), - _ => {} + _ => (), } // Read database file into database @@ -85,8 +85,47 @@ fn main() -> Result<()> { print!("{} ", schema.name); } } - _ => bail!("Missing or invalid command passed: {}", command), - } + v => { + // Assume it's valid SQL + let table_name = v.split_whitespace().last().unwrap(); + + let db_page_size = u16::from_be_bytes([database[16], database[17]]); + + // Parse page header from database + let page_header = PageHeader::parse(&database[100..108])?; + + // Obtain all cell pointers + let cell_pointers = database[108..] + .chunks_exact(2) + .take(page_header.number_of_cells.into()) + .map(|bytes| u16::from_be_bytes(bytes.try_into().unwrap())); + + // Obtain all records from column 5 + #[allow(unused_variables)] + let schemas = cell_pointers + .into_iter() + .map(|cell_pointer| { + let stream = &database[cell_pointer as usize..]; + let (_, offset) = parse_varint(stream); + let (rowid, read_bytes) = parse_varint(&stream[offset..]); + + parse_record(&stream[offset + read_bytes..], 5) + .map(|record| Schema::parse(record).expect("Invalid record")) + }) + .collect::>>()?; + + let schema = schemas + .into_iter() + .find(|schema| schema.table_name == table_name) + .unwrap(); + + let table_page_offset = db_page_size as usize * (schema.root_page as usize - 1); + let page_header = + PageHeader::parse(&database[table_page_offset..table_page_offset + 8]).unwrap(); + + println!("{}", page_header.number_of_cells); + } + } Ok(()) } diff --git a/src/schema.rs b/src/schema.rs index 120c0b0..e157886 100644 --- a/src/schema.rs +++ b/src/schema.rs @@ -3,7 +3,7 @@ pub struct Schema { pub kind: String, pub name: String, pub table_name: String, - root_page: u8, + pub root_page: u8, sql: String, }