Plan, apply and roll back changes to a production ontology, with a blast radius report and a proof an auditor can re-check.
Rust ai-nativedescription-logicsformal-verificationinfrastructure-as-codeisabelle-languageknowledge-graphleanlean4mcpmcp-serverontologyowlowl2reasoningrustshaclsparqltheorem-proving
feat: add ingest module supporting CSV, JSON, NDJSON, YAML, XML, XLSX, Parquet
FABIOTESS1c512e851f16
diff --git a/Cargo.lock b/Cargo.lockindex e1453031..bc5a3013 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -214,6 +214,19 @@ dependencies = ["num",]+[[package]]+name = "arrow-ipc"+version = "54.3.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "62ff528658b521e33905334723b795ee56b393dbe9cf76c8b1f64b648c65a60c"+dependencies = [+ "arrow-array",+ "arrow-buffer",+ "arrow-data",+ "arrow-schema",+ "flatbuffers",+]+[[package]]name = "arrow-json"version = "54.3.1"@@ -343,7 +356,7 @@ version = "0.71.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "5f58bf3d7db68cfbac37cfc485a8d711e87e064c3d0fe0435b92f7a407f9d6b3"dependencies = [- "bitflags",+ "bitflags 2.11.0","cexpr","clang-sys","itertools",@@ -357,6 +370,12 @@ dependencies = ["syn",]+[[package]]+name = "bitflags"+version = "1.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a"+[[package]]name = "bitflags"version = "2.11.0"@@ -760,6 +779,16 @@ version = "0.1.9"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "5baebc0774151f905a1a2cc41989300b1e6fbb29aff0ceffa1064fdd3088d582"+[[package]]+name = "flatbuffers"+version = "24.12.23"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4f1baf0dbf96932ec9a3038d57900329c015b0bfb7b63d904f3bc27e2b02a096"+dependencies = [+ "bitflags 1.3.2",+ "rustc_version",+]+[[package]]name = "flate2"version = "1.1.9"@@ -1701,7 +1730,7 @@ version = "0.10.75"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "08838db121398ad17ab8531ce9de97b244589089e290a384c900cb9ff7434328"dependencies = [- "bitflags",+ "bitflags 2.11.0","cfg-if","foreign-types","libc",@@ -1900,6 +1929,14 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "bfb15796ac6f56b429fd99e33ba133783ad75b27c36b4b5ce06f1f82cc97754e"dependencies = ["ahash",+ "arrow-array",+ "arrow-buffer",+ "arrow-cast",+ "arrow-data",+ "arrow-ipc",+ "arrow-schema",+ "arrow-select",+ "base64","bytes","chrono","half",@@ -2089,7 +2126,7 @@ version = "0.5.18"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d"dependencies = [- "bitflags",+ "bitflags 2.11.0",][[package]]@@ -2236,7 +2273,7 @@ version = "0.32.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "7753b721174eb8ff87a9a0e799e2d7bc3749323e773db92e0984debb00019d6e"dependencies = [- "bitflags",+ "bitflags 2.11.0","fallible-iterator","fallible-streaming-iterator","hashlink",@@ -2250,13 +2287,22 @@ version = "2.1.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "357703d41365b4b27c590e3ed91eabb1b663f07c4c084095e60cbed4362dff0d"+[[package]]+name = "rustc_version"+version = "0.4.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cfcb3a22ef46e85b45de6ee7e79d063319ebb6594faafcf1c225ea92ab6e9b92"+dependencies = [+ "semver",+]+[[package]]name = "rustix"version = "1.1.4"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "b6fe4565b9518b83ef4f91bb47ce29620ca828bd32cb7e408f0062e9930ba190"dependencies = [- "bitflags",+ "bitflags 2.11.0","errno","libc","linux-raw-sys",@@ -2355,7 +2401,7 @@ version = "3.7.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "b7f4bc775c73d9a02cde8bf7b2ec4c9d12743edf609006c7facc23998404cd1d"dependencies = [- "bitflags",+ "bitflags 2.11.0","core-foundation 0.10.1","core-foundation-sys","libc",@@ -2681,7 +2727,7 @@ version = "0.7.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "a13f3d0daba03132c0aa9767f98351b3488edc2c100cda2d2ec2b04f3d8d3c8b"dependencies = [- "bitflags",+ "bitflags 2.11.0","core-foundation 0.9.4","system-configuration-sys",]@@ -2891,7 +2937,7 @@ version = "0.6.8"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "d4e6559d53cc268e5031cd8429d05415bc4cb4aefc4aa5d6cc35fbf5b924a1f8"dependencies = [- "bitflags",+ "bitflags 2.11.0","bytes","futures-util","http",@@ -3184,7 +3230,7 @@ version = "0.244.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "47b807c72e1bac69382b3a6fb3dbe8ea4c0ed87ff5629b8685ae6b9a611028fe"dependencies = [- "bitflags",+ "bitflags 2.11.0","hashbrown 0.15.5","indexmap","semver",@@ -3419,7 +3465,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "9d66ea20e9553b30172b5e831994e35fbde2d165325bec84fc43dbf6f4eb9cb2"dependencies = ["anyhow",- "bitflags",+ "bitflags 2.11.0","indexmap","log","serde",diff --git a/Cargo.toml b/Cargo.tomlindex 053fa49f..a49b6ba0 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -30,7 +30,7 @@ quick-xml = { version = "0.37", features = ["serialize"] }serde_yaml = "0.9"calamine = "0.26"arrow = { version = "54", default-features = false, features = ["csv", "json"] }-parquet = { version = "54", default-features = false }+parquet = { version = "54", default-features = false, features = ["arrow"] }[dev-dependencies]tempfile = "3"diff --git a/src/ingest.rs b/src/ingest.rsnew file mode 100644index 00000000..31fdcb64--- /dev/null+++ b/src/ingest.rs@@ -0,0 +1,422 @@+use anyhow::{Context, Result};+use std::collections::HashMap;+use std::fs;++/// Data ingester that parses structured data files into rows of key-value pairs.+pub struct DataIngester;++/// Convert a serde_json::Value to a flat string representation.+fn json_value_to_string(v: &serde_json::Value) -> String {+ match v {+ serde_json::Value::String(s) => s.clone(),+ serde_json::Value::Number(n) => n.to_string(),+ serde_json::Value::Bool(b) => b.to_string(),+ serde_json::Value::Null => String::new(),+ other => other.to_string(),+ }+}++impl DataIngester {+ /// Detect the file format from the file extension.+ /// Returns one of: "csv", "json", "ndjson", "xml", "yaml", "xlsx", "parquet".+ /// Defaults to "csv" if the extension is unrecognised.+ pub fn detect_format(path: &str) -> &'static str {+ let ext = std::path::Path::new(path)+ .extension()+ .and_then(|e| e.to_str())+ .unwrap_or("")+ .to_lowercase();+ match ext.as_str() {+ "csv" => "csv",+ "json" => "json",+ "jsonl" | "ndjson" => "ndjson",+ "xml" => "xml",+ "yaml" | "yml" => "yaml",+ "xlsx" => "xlsx",+ "parquet" => "parquet",+ _ => "csv",+ }+ }++ /// Parse CSV content with headers into rows.+ pub fn parse_csv(content: &str) -> Result<Vec<HashMap<String, String>>> {+ let mut reader = csv::Reader::from_reader(content.as_bytes());+ let headers: Vec<String> = reader+ .headers()+ .context("Failed to read CSV headers")?+ .iter()+ .map(|h| h.to_string())+ .collect();++ let mut rows = Vec::new();+ for result in reader.records() {+ let record = result.context("Failed to read CSV record")?;+ let mut row = HashMap::new();+ for (i, value) in record.iter().enumerate() {+ if let Some(key) = headers.get(i) {+ row.insert(key.clone(), value.to_string());+ }+ }+ rows.push(row);+ }+ Ok(rows)+ }++ /// Parse a JSON string. Accepts a JSON array of objects or a single object.+ pub fn parse_json(content: &str) -> Result<Vec<HashMap<String, String>>> {+ let value: serde_json::Value =+ serde_json::from_str(content).context("Failed to parse JSON")?;+ match value {+ serde_json::Value::Array(arr) => {+ let mut rows = Vec::new();+ for item in &arr {+ if let serde_json::Value::Object(map) = item {+ let row: HashMap<String, String> = map+ .iter()+ .map(|(k, v)| (k.clone(), json_value_to_string(v)))+ .collect();+ rows.push(row);+ }+ }+ Ok(rows)+ }+ serde_json::Value::Object(map) => {+ let row: HashMap<String, String> = map+ .iter()+ .map(|(k, v)| (k.clone(), json_value_to_string(v)))+ .collect();+ Ok(vec![row])+ }+ _ => Ok(Vec::new()),+ }+ }++ /// Parse newline-delimited JSON (NDJSON / JSON Lines).+ pub fn parse_ndjson(content: &str) -> Result<Vec<HashMap<String, String>>> {+ let mut rows = Vec::new();+ for line in content.lines() {+ let trimmed = line.trim();+ if trimmed.is_empty() {+ continue;+ }+ let value: serde_json::Value =+ serde_json::from_str(trimmed).context("Failed to parse NDJSON line")?;+ if let serde_json::Value::Object(map) = value {+ let row: HashMap<String, String> = map+ .iter()+ .map(|(k, v)| (k.clone(), json_value_to_string(v)))+ .collect();+ rows.push(row);+ }+ }+ Ok(rows)+ }++ /// Parse a YAML string containing an array of objects.+ pub fn parse_yaml(content: &str) -> Result<Vec<HashMap<String, String>>> {+ let value: serde_yaml::Value =+ serde_yaml::from_str(content).context("Failed to parse YAML")?;+ match value {+ serde_yaml::Value::Sequence(seq) => {+ let mut rows = Vec::new();+ for item in &seq {+ if let serde_yaml::Value::Mapping(map) = item {+ let mut row = HashMap::new();+ for (k, v) in map {+ let key = match k {+ serde_yaml::Value::String(s) => s.clone(),+ other => format!("{other:?}"),+ };+ let val = match v {+ serde_yaml::Value::String(s) => s.clone(),+ serde_yaml::Value::Number(n) => n.to_string(),+ serde_yaml::Value::Bool(b) => b.to_string(),+ serde_yaml::Value::Null => String::new(),+ other => format!("{other:?}"),+ };+ row.insert(key, val);+ }+ rows.push(row);+ }+ }+ Ok(rows)+ }+ _ => Ok(Vec::new()),+ }+ }++ /// Parse XML with a `<root><record>...</record></root>` structure.+ /// Depth 1 = root element, depth 2 = record boundary, depth 3 = field elements.+ pub fn parse_xml(content: &str) -> Result<Vec<HashMap<String, String>>> {+ use quick_xml::events::Event;+ use quick_xml::reader::Reader;++ let mut reader = Reader::from_str(content);+ reader.config_mut().trim_text(true);++ let mut rows: Vec<HashMap<String, String>> = Vec::new();+ let mut current_row: Option<HashMap<String, String>> = None;+ let mut current_field: Option<String> = None;+ let mut depth: u32 = 0;++ loop {+ match reader.read_event() {+ Ok(Event::Start(e)) => {+ depth += 1;+ match depth {+ 1 => {+ // Root element — nothing to do+ }+ 2 => {+ // Record start+ current_row = Some(HashMap::new());+ }+ 3 => {+ // Field element start+ let name = String::from_utf8_lossy(e.name().as_ref()).to_string();+ current_field = Some(name);+ }+ _ => {}+ }+ }+ Ok(Event::Text(e)) => {+ if depth == 3 {+ if let (Some(row), Some(field)) =+ (&mut current_row, ¤t_field)+ {+ let text = e.unescape().unwrap_or_default().to_string();+ row.insert(field.clone(), text);+ }+ }+ }+ Ok(Event::End(_)) => {+ match depth {+ 2 => {+ // Record end — push row+ if let Some(row) = current_row.take() {+ rows.push(row);+ }+ }+ 3 => {+ current_field = None;+ }+ _ => {}+ }+ depth -= 1;+ }+ Ok(Event::Eof) => break,+ Err(e) => return Err(anyhow::anyhow!("XML parse error: {e}")),+ _ => {}+ }+ }+ Ok(rows)+ }++ /// Parse an Excel (.xlsx) file. First row is treated as headers.+ pub fn parse_xlsx_file(path: &str) -> Result<Vec<HashMap<String, String>>> {+ use calamine::{open_workbook, Reader, Xlsx};++ let mut workbook: Xlsx<_> =+ open_workbook(path).context("Failed to open XLSX workbook")?;++ let sheet_names = workbook.sheet_names().to_vec();+ let first_sheet = sheet_names+ .first()+ .context("XLSX workbook has no sheets")?+ .clone();++ let range = workbook+ .worksheet_range(&first_sheet)+ .context("Failed to read XLSX worksheet")?;++ let mut row_iter = range.rows();+ let header_row = row_iter.next().context("XLSX file has no rows")?;++ let headers: Vec<String> = header_row+ .iter()+ .map(|cell| Self::calamine_cell_to_string(cell))+ .collect();++ let mut rows = Vec::new();+ for data_row in row_iter {+ let mut row = HashMap::new();+ for (i, cell) in data_row.iter().enumerate() {+ if let Some(key) = headers.get(i) {+ row.insert(key.clone(), Self::calamine_cell_to_string(cell));+ }+ }+ rows.push(row);+ }+ Ok(rows)+ }++ /// Convert a calamine Data cell to a string.+ fn calamine_cell_to_string(cell: &calamine::Data) -> String {+ match cell {+ calamine::Data::Int(i) => i.to_string(),+ calamine::Data::Float(f) => f.to_string(),+ calamine::Data::String(s) => s.clone(),+ calamine::Data::Bool(b) => b.to_string(),+ calamine::Data::DateTime(dt) => dt.to_string(),+ calamine::Data::DateTimeIso(s) => s.clone(),+ calamine::Data::DurationIso(s) => s.clone(),+ calamine::Data::Error(e) => format!("{e:?}"),+ calamine::Data::Empty => String::new(),+ }+ }++ /// Parse a Parquet file into rows.+ pub fn parse_parquet_file(path: &str) -> Result<Vec<HashMap<String, String>>> {+ use parquet::arrow::arrow_reader::ParquetRecordBatchReaderBuilder;+ use std::fs::File;++ let file = File::open(path).context("Failed to open Parquet file")?;+ let builder = ParquetRecordBatchReaderBuilder::try_new(file)+ .context("Failed to create Parquet reader builder")?;++ let reader = builder.build().context("Failed to build Parquet reader")?;++ let mut rows = Vec::new();+ for batch_result in reader {+ let batch: arrow::array::RecordBatch =+ batch_result.context("Failed to read Parquet record batch")?;+ let schema = batch.schema();+ let num_rows = batch.num_rows();+ let num_cols = batch.num_columns();++ for row_idx in 0..num_rows {+ let mut row = HashMap::new();+ for col_idx in 0..num_cols {+ let field = schema.field(col_idx);+ let col = batch.column(col_idx);+ let value = if col.is_null(row_idx) {+ String::new()+ } else {+ Self::arrow_array_value_to_string(col.as_ref(), row_idx, field.data_type())+ };+ row.insert(field.name().clone(), value);+ }+ rows.push(row);+ }+ }+ Ok(rows)+ }++ /// Convert an Arrow array value at a given index to a string.+ fn arrow_array_value_to_string(+ array: &dyn arrow::array::Array,+ idx: usize,+ data_type: &arrow::datatypes::DataType,+ ) -> String {+ use arrow::array::*;+ use arrow::datatypes::DataType as ArrowType;++ match data_type {+ ArrowType::Boolean => {+ let a = array.as_any().downcast_ref::<BooleanArray>().unwrap();+ a.value(idx).to_string()+ }+ ArrowType::Int8 => {+ let a = array.as_any().downcast_ref::<Int8Array>().unwrap();+ a.value(idx).to_string()+ }+ ArrowType::Int16 => {+ let a = array.as_any().downcast_ref::<Int16Array>().unwrap();+ a.value(idx).to_string()+ }+ ArrowType::Int32 => {+ let a = array.as_any().downcast_ref::<Int32Array>().unwrap();+ a.value(idx).to_string()+ }+ ArrowType::Int64 => {+ let a = array.as_any().downcast_ref::<Int64Array>().unwrap();+ a.value(idx).to_string()+ }+ ArrowType::UInt8 => {+ let a = array.as_any().downcast_ref::<UInt8Array>().unwrap();+ a.value(idx).to_string()+ }+ ArrowType::UInt16 => {+ let a = array.as_any().downcast_ref::<UInt16Array>().unwrap();+ a.value(idx).to_string()+ }+ ArrowType::UInt32 => {+ let a = array.as_any().downcast_ref::<UInt32Array>().unwrap();+ a.value(idx).to_string()+ }+ ArrowType::UInt64 => {+ let a = array.as_any().downcast_ref::<UInt64Array>().unwrap();+ a.value(idx).to_string()+ }+ ArrowType::Float32 => {+ let a = array.as_any().downcast_ref::<Float32Array>().unwrap();+ a.value(idx).to_string()+ }+ ArrowType::Float64 => {+ let a = array.as_any().downcast_ref::<Float64Array>().unwrap();+ a.value(idx).to_string()+ }+ ArrowType::Utf8 => {+ let a = array.as_any().downcast_ref::<StringArray>().unwrap();+ a.value(idx).to_string()+ }+ ArrowType::LargeUtf8 => {+ let a = array.as_any().downcast_ref::<LargeStringArray>().unwrap();+ a.value(idx).to_string()+ }+ _ => format!("{array:?}[{idx}]"),+ }+ }++ /// Dispatch to the correct parser based on detected format.+ /// For text formats, reads the file content first.+ pub fn parse_file(path: &str) -> Result<Vec<HashMap<String, String>>> {+ let format = Self::detect_format(path);+ match format {+ "csv" => {+ let content = fs::read_to_string(path)+ .with_context(|| format!("Failed to read file: {path}"))?;+ Self::parse_csv(&content)+ }+ "json" => {+ let content = fs::read_to_string(path)+ .with_context(|| format!("Failed to read file: {path}"))?;+ Self::parse_json(&content)+ }+ "ndjson" => {+ let content = fs::read_to_string(path)+ .with_context(|| format!("Failed to read file: {path}"))?;+ Self::parse_ndjson(&content)+ }+ "yaml" => {+ let content = fs::read_to_string(path)+ .with_context(|| format!("Failed to read file: {path}"))?;+ Self::parse_yaml(&content)+ }+ "xml" => {+ let content = fs::read_to_string(path)+ .with_context(|| format!("Failed to read file: {path}"))?;+ Self::parse_xml(&content)+ }+ "xlsx" => Self::parse_xlsx_file(path),+ "parquet" => Self::parse_parquet_file(path),+ _ => {+ let content = fs::read_to_string(path)+ .with_context(|| format!("Failed to read file: {path}"))?;+ Self::parse_csv(&content)+ }+ }+ }++ /// Collect unique keys from all rows, sorted alphabetically.+ pub fn extract_headers(rows: &[HashMap<String, String>]) -> Vec<String> {+ let mut keys: Vec<String> = rows+ .iter()+ .flat_map(|row| row.keys().cloned())+ .collect::<std::collections::HashSet<String>>()+ .into_iter()+ .collect();+ keys.sort();+ keys+ }+}diff --git a/src/lib.rs b/src/lib.rsindex f8014f67..2360e036 100644--- a/src/lib.rs+++ b/src/lib.rs@@ -1,5 +1,7 @@pub mod config;pub mod graph;+pub mod ingest;+pub mod mapping;pub mod ontology;pub mod server;pub mod state;diff --git a/tests/ingest_test.rs b/tests/ingest_test.rsnew file mode 100644index 00000000..b57af3ff--- /dev/null+++ b/tests/ingest_test.rs@@ -0,0 +1,65 @@+use open_ontologies::ingest::DataIngester;++#[test]+fn test_parse_csv() {+ let csv_content = "id,name,category\nb1,Tower Bridge,Landmark\nb2,Big Ben,Landmark\n";+ let rows = DataIngester::parse_csv(csv_content).unwrap();+ assert_eq!(rows.len(), 2);+ assert_eq!(rows[0]["name"], "Tower Bridge");+ assert_eq!(rows[1]["id"], "b2");+}++#[test]+fn test_parse_json_array() {+ let json = r#"[{"id":"b1","name":"Tower Bridge"},{"id":"b2","name":"Big Ben"}]"#;+ let rows = DataIngester::parse_json(json).unwrap();+ assert_eq!(rows.len(), 2);+ assert_eq!(rows[0]["name"], "Tower Bridge");+}++#[test]+fn test_parse_ndjson() {+ let ndjson = "{\"id\":\"b1\",\"name\":\"Tower Bridge\"}\n{\"id\":\"b2\",\"name\":\"Big Ben\"}\n";+ let rows = DataIngester::parse_ndjson(ndjson).unwrap();+ assert_eq!(rows.len(), 2);+ assert_eq!(rows[1]["name"], "Big Ben");+}++#[test]+fn test_parse_yaml() {+ let yaml = "- id: b1\n name: Tower Bridge\n- id: b2\n name: Big Ben\n";+ let rows = DataIngester::parse_yaml(yaml).unwrap();+ assert_eq!(rows.len(), 2);+ assert_eq!(rows[0]["name"], "Tower Bridge");+}++#[test]+fn test_parse_xml_records() {+ let xml = r#"<records><record><id>b1</id><name>Tower Bridge</name></record><record><id>b2</id><name>Big Ben</name></record></records>"#;+ let rows = DataIngester::parse_xml(xml).unwrap();+ assert_eq!(rows.len(), 2);+ assert_eq!(rows[0]["id"], "b1");+}++#[test]+fn test_detect_format() {+ assert_eq!(DataIngester::detect_format("data.csv"), "csv");+ assert_eq!(DataIngester::detect_format("data.json"), "json");+ assert_eq!(DataIngester::detect_format("data.jsonl"), "ndjson");+ assert_eq!(DataIngester::detect_format("data.ndjson"), "ndjson");+ assert_eq!(DataIngester::detect_format("data.xml"), "xml");+ assert_eq!(DataIngester::detect_format("data.yaml"), "yaml");+ assert_eq!(DataIngester::detect_format("data.yml"), "yaml");+ assert_eq!(DataIngester::detect_format("data.xlsx"), "xlsx");+ assert_eq!(DataIngester::detect_format("data.parquet"), "parquet");+}++#[test]+fn test_extract_headers() {+ let csv_content = "id,name,category\nb1,Tower Bridge,Landmark\n";+ let rows = DataIngester::parse_csv(csv_content).unwrap();+ let headers = DataIngester::extract_headers(&rows);+ assert!(headers.contains(&"id".to_string()));+ assert!(headers.contains(&"name".to_string()));+ assert!(headers.contains(&"category".to_string()));+}