Skip to content

Plan, apply and roll back changes to a production ontology, with a blast radius report and a proof an auditor can re-check.

feat: DuckDB SQL backbone alongside Postgres (PR #11)

FABIOTESS8cf4780226a5
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 7a684f97..f8358d8b 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -2,6 +2,21 @@
All notable changes to Open Ontologies are documented here.
+## [Unreleased]
+
+### Added
+- **DuckDB SQL data backbone**. New optional `duckdb` Cargo feature (and `sql` umbrella combining `postgres` + `duckdb`) wires DuckDB in alongside PostgreSQL as a *data integration* backbone — not as a SPARQL parser. DuckDB's extensions (`httpfs`, `parquet`, `csv`, `json`, `postgres_scanner`, `iceberg`, `delta`, …) let one SQL query federate over remote files, object stores, and other databases; rows then flow into the existing mapping/SHACL/reason pipeline.
+- **New MCP tool `onto_sql_ingest`** — runs a SQL `SELECT` against PostgreSQL or DuckDB and ingests result rows into the triple store using the same `MappingConfig` shape as `onto_ingest`. Connection-string scheme is auto-detected (`postgres://`, `postgresql://`, `duckdb://`, `:memory:`, or a `*.duckdb` / `*.ddb` file path).
+- **New CLI command `sql-ingest`** mirroring the MCP tool, with `--mapping`, `--inline-mapping`, `--base-iri`, and `-` (stdin) for the SQL.
+- **`onto_import_schema` extended to DuckDB**. The same MCP tool / `import-schema` CLI now dispatches on the connection-string scheme: PostgreSQL via `sqlx`, DuckDB via the `duckdb` crate's `information_schema` + `duckdb_constraints()` introspection. The generated OWL is identical in shape (classes, datatype/object properties, NOT NULL → `owl:minCardinality 1`).
+- **New `sql` tool group** in `[tools]` filter (`@sql` expands to `onto_import_schema` + `onto_sql_ingest`).
+- **`SchemaIntrospector::sql_to_xsd` extended** to handle DuckDB-native types (HUGEINT, U{TINY,SMALL,}INT, DOUBLE, parameterised DECIMAL/VARCHAR, DATETIME, UUID, TIME).
+- New tests: `tests/sqlsource_test.rs` (driver detection, no features required) and `tests/duckdb_test.rs` (introspection + query → row extraction, gated by the `duckdb` feature).
+
+### Documentation
+- `docs/data-pipeline.md` rewritten to cover both file-based and SQL-based ingest paths, the supported connection-string forms, federation examples (Parquet on S3 + Postgres scanner + remote CSV in one query), and a build matrix for the new feature flags.
+- `SKILL.md`, `skills/ontology-engineering/SKILL.md`, `skills/ontology-engineer.md`, and `CLAUDE.md` Tool Reference tables expanded to cover the SQL backbone tools and previously-missing tools (`onto_status`, `onto_marketplace`, `onto_unload`, `onto_recompile`, `onto_cache_status`, `onto_cache_list`, `onto_cache_remove`, `onto_repo_list`, `onto_repo_load`, `onto_embed`, `onto_search`, `onto_similarity`, `onto_dl_explain`, `onto_dl_check`, `onto_import_schema`, `onto_sql_ingest`).
+
## [0.1.13] - 2026-05-01
### Added
diff --git a/CLAUDE.md b/CLAUDE.md
index 6d2021e9..d6e777e4 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -66,11 +66,12 @@ Claude dynamically decides the next tool call based on what the previous tool re
| `onto_history` | To list saved version snapshots |
| `onto_rollback` | To restore a previous version if something goes wrong |
| `onto_ingest` | To parse structured data (CSV, JSON, NDJSON, XML, YAML, XLSX, Parquet) into RDF and load into the store |
+| `onto_sql_ingest` | To run a SQL `SELECT` against PostgreSQL or DuckDB and ingest the result rows into RDF (uses the same mapping format as `onto_ingest`). DuckDB acts as a federation backbone via its `httpfs`/`parquet`/`csv`/`postgres_scanner`/`iceberg` extensions. Connection strings: `postgres://…`, `duckdb:///path.duckdb`, `:memory:`, or `*.duckdb` file path. |
| `onto_map` | To generate a mapping config from data schema + loaded ontology for review |
| `onto_shacl` | To validate loaded data against SHACL shapes (cardinality, datatypes, classes) |
| `onto_reason` | To run RDFS or OWL-RL inference, materializing inferred triples |
| `onto_extend` | To run the full pipeline: ingest → SHACL validate → reason in one call |
-| `onto_import_schema` | To import a PostgreSQL database schema as an OWL ontology (requires postgres feature) |
+| `onto_import_schema` | To import a PostgreSQL or DuckDB database schema as an OWL ontology (requires `postgres` and/or `duckdb` features). Auto-dispatches on connection-string scheme. |
| `onto_plan` | Before applying changes — shows added/removed classes, blast radius, risk score |
| `onto_apply` | After plan + enforce — applies changes in `safe` or `migrate` mode |
| `onto_lock` | To protect production IRIs from removal |
diff --git a/Cargo.lock b/Cargo.lock
index 07447a74..454d7e31 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -8,6 +8,17 @@ version = "2.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa"
+[[package]]
+name = "ahash"
+version = "0.7.8"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "891477e0c6a8957309ee5c45a6368af3ae14bb510732d2684ffa19af310920f9"
+dependencies = [
+ "getrandom 0.2.17",
+ "once_cell",
+ "version_check",
+]
+
[[package]]
name = "ahash"
version = "0.8.12"
@@ -124,24 +135,48 @@ dependencies = [
"derive_arbitrary",
]
+[[package]]
+name = "arrayvec"
+version = "0.7.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7c02d123df017efcdfbd739ef81735b36c5ba83ec3c59c80a9d7ecc718f92e50"
+
[[package]]
name = "arrow"
version = "54.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b5ec52ba94edeed950e4a41f75d35376df196e8cb04437f7280a5aa49f20f796"
dependencies = [
- "arrow-arith",
- "arrow-array",
- "arrow-buffer",
- "arrow-cast",
+ "arrow-arith 54.3.1",
+ "arrow-array 54.3.1",
+ "arrow-buffer 54.3.1",
+ "arrow-cast 54.3.1",
"arrow-csv",
- "arrow-data",
+ "arrow-data 54.3.1",
"arrow-json",
- "arrow-ord",
- "arrow-row",
- "arrow-schema",
- "arrow-select",
- "arrow-string",
+ "arrow-ord 54.3.1",
+ "arrow-row 54.3.1",
+ "arrow-schema 54.3.1",
+ "arrow-select 54.3.1",
+ "arrow-string 54.3.1",
+]
+
+[[package]]
+name = "arrow"
+version = "58.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d441fdda254b65f3e9025910eb2c2066b6295d9c8ed409522b8d2ace1ff8574c"
+dependencies = [
+ "arrow-arith 58.1.0",
+ "arrow-array 58.1.0",
+ "arrow-buffer 58.1.0",
+ "arrow-cast 58.1.0",
+ "arrow-data 58.1.0",
+ "arrow-ord 58.1.0",
+ "arrow-row 58.1.0",
+ "arrow-schema 58.1.0",
+ "arrow-select 58.1.0",
+ "arrow-string 58.1.0",
]
[[package]]
@@ -150,30 +185,62 @@ version = "54.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8fc766fdacaf804cb10c7c70580254fcdb5d55cdfda2bc57b02baf5223a3af9e"
dependencies = [
- "arrow-array",
- "arrow-buffer",
- "arrow-data",
- "arrow-schema",
+ "arrow-array 54.3.1",
+ "arrow-buffer 54.3.1",
+ "arrow-data 54.3.1",
+ "arrow-schema 54.3.1",
"chrono",
"num",
]
+[[package]]
+name = "arrow-arith"
+version = "58.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ced5406f8b720cc0bc3aa9cf5758f93e8593cda5490677aa194e4b4b383f9a59"
+dependencies = [
+ "arrow-array 58.1.0",
+ "arrow-buffer 58.1.0",
+ "arrow-data 58.1.0",
+ "arrow-schema 58.1.0",
+ "chrono",
+ "num-traits",
+]
+
[[package]]
name = "arrow-array"
version = "54.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a12fcdb3f1d03f69d3ec26ac67645a8fe3f878d77b5ebb0b15d64a116c212985"
dependencies = [
- "ahash",
- "arrow-buffer",
- "arrow-data",
- "arrow-schema",
+ "ahash 0.8.12",
+ "arrow-buffer 54.3.1",
+ "arrow-data 54.3.1",
+ "arrow-schema 54.3.1",
"chrono",
"half",
"hashbrown 0.15.5",
"num",
]
+[[package]]
+name = "arrow-array"
+version = "58.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "772bd34cacdda8baec9418d80d23d0fb4d50ef0735685bd45158b83dfeb6e62d"
+dependencies = [
+ "ahash 0.8.12",
+ "arrow-buffer 58.1.0",
+ "arrow-data 58.1.0",
+ "arrow-schema 58.1.0",
+ "chrono",
+ "half",
+ "hashbrown 0.16.1",
+ "num-complex",
+ "num-integer",
+ "num-traits",
+]
+
[[package]]
name = "arrow-buffer"
version = "54.3.1"
@@ -185,17 +252,29 @@ dependencies = [
"num",
]
+[[package]]
+name = "arrow-buffer"
+version = "58.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "898f4cf1e9598fdb77f356fdf2134feedfd0ee8d5a4e0a5f573e7d0aec16baa4"
+dependencies = [
+ "bytes",
+ "half",
+ "num-bigint",
+ "num-traits",
+]
+
[[package]]
name = "arrow-cast"
version = "54.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ede6175fbc039dfc946a61c1b6d42fd682fcecf5ab5d148fbe7667705798cac9"
dependencies = [
- "arrow-array",
- "arrow-buffer",
- "arrow-data",
- "arrow-schema",
- "arrow-select",
+ "arrow-array 54.3.1",
+ "arrow-buffer 54.3.1",
+ "arrow-data 54.3.1",
+ "arrow-schema 54.3.1",
+ "arrow-select 54.3.1",
"atoi",
"base64 0.22.1",
"chrono",
@@ -205,15 +284,37 @@ dependencies = [
"ryu",
]
+[[package]]
+name = "arrow-cast"
+version = "58.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b0127816c96533d20fc938729f48c52d3e48f99717e7a0b5ade77d742510736d"
+dependencies = [
+ "arrow-array 58.1.0",
+ "arrow-buffer 58.1.0",
+ "arrow-data 58.1.0",
+ "arrow-ord 58.1.0",
+ "arrow-schema 58.1.0",
+ "arrow-select 58.1.0",
+ "atoi",
+ "base64 0.22.1",
+ "chrono",
+ "comfy-table",
+ "half",
+ "lexical-core",
+ "num-traits",
+ "ryu",
+]
+
[[package]]
name = "arrow-csv"
version = "54.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1644877d8bc9a0ef022d9153dc29375c2bda244c39aec05a91d0e87ccf77995f"
dependencies = [
- "arrow-array",
- "arrow-cast",
- "arrow-schema",
+ "arrow-array 54.3.1",
+ "arrow-cast 54.3.1",
+ "arrow-schema 54.3.1",
"chrono",
"csv",
"csv-core",
@@ -227,22 +328,35 @@ version = "54.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "61cfdd7d99b4ff618f167e548b2411e5dd2c98c0ddebedd7df433d34c20a4429"
dependencies = [
- "arrow-buffer",
- "arrow-schema",
+ "arrow-buffer 54.3.1",
+ "arrow-schema 54.3.1",
"half",
"num",
]
+[[package]]
+name = "arrow-data"
+version = "58.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "42d10beeab2b1c3bb0b53a00f7c944a178b622173a5c7bcabc3cb45d90238df4"
+dependencies = [
+ "arrow-buffer 58.1.0",
+ "arrow-schema 58.1.0",
+ "half",
+ "num-integer",
+ "num-traits",
+]
+
[[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",
+ "arrow-array 54.3.1",
+ "arrow-buffer 54.3.1",
+ "arrow-data 54.3.1",
+ "arrow-schema 54.3.1",
"flatbuffers",
]
@@ -252,11 +366,11 @@ version = "54.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0ee5b4ca98a7fb2efb9ab3309a5d1c88b5116997ff93f3147efdc1062a6158e9"
dependencies = [
- "arrow-array",
- "arrow-buffer",
- "arrow-cast",
- "arrow-data",
- "arrow-schema",
+ "arrow-array 54.3.1",
+ "arrow-buffer 54.3.1",
+ "arrow-cast 54.3.1",
+ "arrow-data 54.3.1",
+ "arrow-schema 54.3.1",
"chrono",
"half",
"indexmap",
@@ -274,11 +388,24 @@ version = "54.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f0a3334a743bd2a1479dbc635540617a3923b4b2f6870f37357339e6b5363c21"
dependencies = [
- "arrow-array",
- "arrow-buffer",
- "arrow-data",
- "arrow-schema",
- "arrow-select",
+ "arrow-array 54.3.1",
+ "arrow-buffer 54.3.1",
+ "arrow-data 54.3.1",
+ "arrow-schema 54.3.1",
+ "arrow-select 54.3.1",
+]
+
+[[package]]
+name = "arrow-ord"
+version = "58.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "763a7ba279b20b52dad300e68cfc37c17efa65e68623169076855b3a9e941ca5"
+dependencies = [
+ "arrow-array 58.1.0",
+ "arrow-buffer 58.1.0",
+ "arrow-data 58.1.0",
+ "arrow-schema 58.1.0",
+ "arrow-select 58.1.0",
]
[[package]]
@@ -287,10 +414,23 @@ version = "54.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8d1d7a7291d2c5107e92140f75257a99343956871f3d3ab33a7b41532f79cb68"
dependencies = [
- "arrow-array",
- "arrow-buffer",
- "arrow-data",
- "arrow-schema",
+ "arrow-array 54.3.1",
+ "arrow-buffer 54.3.1",
+ "arrow-data 54.3.1",
+ "arrow-schema 54.3.1",
+ "half",
+]
+
+[[package]]
+name = "arrow-row"
+version = "58.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e14fe367802f16d7668163ff647830258e6e0aeea9a4d79aaedf273af3bdcd3e"
+dependencies = [
+ "arrow-array 58.1.0",
+ "arrow-buffer 58.1.0",
+ "arrow-data 58.1.0",
+ "arrow-schema 58.1.0",
"half",
]
@@ -300,37 +440,77 @@ version = "54.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "39cfaf5e440be44db5413b75b72c2a87c1f8f0627117d110264048f2969b99e9"
+[[package]]
+name = "arrow-schema"
+version = "58.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c30a1365d7a7dc50cc847e54154e6af49e4c4b0fddc9f607b687f29212082743"
+dependencies = [
+ "bitflags 2.11.0",
+]
+
[[package]]
name = "arrow-select"
version = "54.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "69efcd706420e52cd44f5c4358d279801993846d1c2a8e52111853d61d55a619"
dependencies = [
- "ahash",
- "arrow-array",
- "arrow-buffer",
- "arrow-data",
- "arrow-schema",
+ "ahash 0.8.12",
+ "arrow-array 54.3.1",
+ "arrow-buffer 54.3.1",
+ "arrow-data 54.3.1",
+ "arrow-schema 54.3.1",
"num",
]
+[[package]]
+name = "arrow-select"
+version = "58.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "78694888660a9e8ac949853db393af2a8b8fc82c19ce333132dfa2e72cc1a7fe"
+dependencies = [
+ "ahash 0.8.12",
+ "arrow-array 58.1.0",
+ "arrow-buffer 58.1.0",
+ "arrow-data 58.1.0",
+ "arrow-schema 58.1.0",
+ "num-traits",
+]
+
[[package]]
name = "arrow-string"
version = "54.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a21546b337ab304a32cfc0770f671db7411787586b45b78b4593ae78e64e2b03"
dependencies = [
- "arrow-array",
- "arrow-buffer",
- "arrow-data",
- "arrow-schema",
- "arrow-select",
+ "arrow-array 54.3.1",
+ "arrow-buffer 54.3.1",
+ "arrow-data 54.3.1",
+ "arrow-schema 54.3.1",
+ "arrow-select 54.3.1",
"memchr",
"num",
"regex",
"regex-syntax",
]
+[[package]]
+name = "arrow-string"
+version = "58.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "61e04a01f8bb73ce54437514c5fd3ee2aa3e8abe4c777ee5cc55853b1652f79e"
+dependencies = [
+ "arrow-array 58.1.0",
+ "arrow-buffer 58.1.0",
+ "arrow-data 58.1.0",
+ "arrow-schema 58.1.0",
+ "arrow-select 58.1.0",
+ "memchr",
+ "num-traits",
+ "regex",
+ "regex-syntax",
+]
+
[[package]]
name = "async-trait"
version = "0.1.89"
@@ -474,6 +654,18 @@ version = "2.11.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "843867be96c8daad0d758b57df9392b6d8d271134fce549de6ce169ff98a92af"
+[[package]]
+name = "bitvec"
+version = "1.0.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1bc2832c24239b0141d5674bb9174f9d68a8b5b3f2753311927c172ca46f7e9c"
+dependencies = [
+ "funty",
+ "radium",
+ "tap",
+ "wyz",
+]
+
[[package]]
name = "block-buffer"
version = "0.10.4"
@@ -483,12 +675,58 @@ dependencies = [
"generic-array",
]
+[[package]]
+name = "borsh"
+version = "1.6.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cfd1e3f8955a5d7de9fab72fc8373fade9fb8a703968cb200ae3dc6cf08e185a"
+dependencies = [
+ "borsh-derive",
+ "bytes",
+ "cfg_aliases",
+]
+
+[[package]]
+name = "borsh-derive"
+version = "1.6.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "bfcfdc083699101d5a7965e49925975f2f55060f94f9a05e7187be95d530ca59"
+dependencies = [
+ "once_cell",
+ "proc-macro-crate",
+ "proc-macro2",
+ "quote",
+ "syn 2.0.117",
+]
+
[[package]]
name = "bumpalo"
version = "3.20.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5d20789868f4b01b2f2caec9f5c4e0213b41e3e5702a50157d699ae31ced2fcb"
+[[package]]
+name = "bytecheck"
+version = "0.6.12"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "23cdc57ce23ac53c931e88a43d06d070a6fd142f2617be5855eb75efc9beb1c2"
+dependencies = [
+ "bytecheck_derive",
+ "ptr_meta",
+ "simdutf8",
+]
+
+[[package]]
+name = "bytecheck_derive"
+version = "0.6.12"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3db406d29fbcd95542e92559bed4d8ad92636d1ca8b3b72ede10b4bcc010e659"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 1.0.109",
+]
+
[[package]]
name = "byteorder"
version = "1.5.0"
@@ -513,9 +751,15 @@ dependencies = [
"log",
"quick-xml 0.31.0",
"serde",
- "zip",
+ "zip 2.4.2",
]
+[[package]]
+name = "cast"
+version = "0.3.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "37b2a672a2cb129a2e41c10b1224bb368f9f37a2b16b612598138befd7b37eb5"
+
[[package]]
name = "castaway"
version = "0.2.4"
@@ -552,6 +796,12 @@ version = "1.0.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801"
+[[package]]
+name = "cfg_aliases"
+version = "0.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "613afe47fcd5fac7ccf1db93babcb082c5994d996f20b8b159f2ad1658eb5724"
+
[[package]]
name = "chacha20"
version = "0.10.0"
@@ -643,6 +893,17 @@ version = "1.0.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b05b61dc5112cbb17e4b6cd61790d9845d13888356391624cbe7e41efeac1e75"
+[[package]]
+name = "comfy-table"
+version = "7.1.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4a65ebfec4fb190b6f90e944a817d60499ee0744e582530e2c9900a22e591d9a"
+dependencies = [
+ "crossterm",
+ "unicode-segmentation",
+ "unicode-width",
+]
+
[[package]]
name = "compact_str"
version = "0.9.0"
@@ -789,6 +1050,28 @@ version = "0.8.21"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d0a5c400df2834b80a4c3327b3aad3a4c4cd4de0629063962b03235697506a28"
+[[package]]
+name = "crossterm"
+version = "0.28.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "829d955a0bb380ef178a640b91779e3987da38c9aea133b20614cfed8cdea9c6"
+dependencies = [
+ "bitflags 2.11.0",
+ "crossterm_winapi",
+ "parking_lot",
+ "rustix 0.38.44",
+ "winapi",
+]
+
+[[package]]
+name = "crossterm_winapi"
+version = "0.9.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "acdd7c62a3665c7f6830a51635d9ac9b23ed385797f70a83bb8bafe9c572ab2b"
+dependencies = [
+ "winapi",
+]
+
[[package]]
name = "crunchy"
version = "0.2.4"
@@ -1041,6 +1324,24 @@ version = "1.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "75b325c5dbd37f80359721ad39aca5a29fb04c89279657cffdda8736d0c0b9d2"
+[[package]]
+name = "duckdb"
+version = "1.10502.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0fdc796383b176dd5a45353fbb5e64583c0ee4da12cb62c9e510b785324b2488"
+dependencies = [
+ "arrow 58.1.0",
+ "cast",
+ "comfy-table",
+ "fallible-iterator",
+ "fallible-streaming-iterator",
+ "hashlink 0.10.0",
+ "libduckdb-sys",
+ "num-integer",
+ "rust_decimal",
+ "strum",
+]
+
[[package]]
name = "dyn-clone"
version = "1.0.20"
@@ -1168,6 +1469,7 @@ checksum = "843fba2746e448b37e26a819579957415c8cef339bf08564fe8b7ddbd959573c"
dependencies = [
"crc32fast",
"miniz_oxide",
+ "zlib-rs",
]
[[package]]
@@ -1206,6 +1508,12 @@ dependencies = [
"percent-encoding",
]
+[[package]]
+name = "funty"
+version = "2.0.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e6d5a32815ae3f33302d95fdcb2ce17862f8c65363dcfd29360480ba1001fc9c"
+
[[package]]
name = "futures"
version = "0.3.32"
@@ -1322,8 +1630,10 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0"
dependencies = [
"cfg-if",
+ "js-sys",
"libc",
"wasi",
+ "wasm-bindgen",
]
[[package]]
@@ -1333,9 +1643,11 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd"
dependencies = [
"cfg-if",
+ "js-sys",
"libc",
"r-efi 5.3.0",
"wasip2",
+ "wasm-bindgen",
]
[[package]]
@@ -1389,13 +1701,22 @@ dependencies = [
"zerocopy",
]
+[[package]]
+name = "hashbrown"
+version = "0.12.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8a9ee70c43aaf417c914396645a0fa852624801b24ebb7ae78fe8272889ac888"
+dependencies = [
+ "ahash 0.7.8",
+]
+
[[package]]
name = "hashbrown"
version = "0.14.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e5274423e17b7c9fc20b6e7e208532f9b19825d82dfd615708b70edd83df41f1"
dependencies = [
- "ahash",
+ "ahash 0.8.12",
]
[[package]]
@@ -1554,6 +1875,7 @@ dependencies = [
"tokio",
"tokio-rustls",
"tower-service",
+ "webpki-roots",
]
[[package]]
@@ -1928,6 +2250,23 @@ version = "0.2.183"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b5b646652bf6661599e1da8901b3b9522896f01e736bad5f723fe7a3a27f899d"
+[[package]]
+name = "libduckdb-sys"
+version = "1.10502.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8d7401630ae2abcff642f7156294289e50f2d222e061c026ad797b01bf20c215"
+dependencies = [
+ "cc",
+ "flate2",
+ "pkg-config",
+ "reqwest",
+ "serde",
+ "serde_json",
+ "tar",
+ "vcpkg",
+ "zip 6.0.0",
+]
+
[[package]]
name = "libloading"
version = "0.8.9"
@@ -1967,6 +2306,12 @@ dependencies = [
"vcpkg",
]
+[[package]]
+name = "linux-raw-sys"
+version = "0.4.15"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d26c52dbd32dccf2d10cac7725f8eae5296885fb5703b261f7d0a0739ec807ab"
+
[[package]]
name = "linux-raw-sys"
version = "0.12.1"
@@ -2051,6 +2396,12 @@ version = "0.4.29"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5e5032e24019045c762d3c0f28f5b6b8bbf38563a65908389bf7978758920897"
+[[package]]
+name = "lru-slab"
+version = "0.1.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "112b39cec0b298b6c1999fee3e31427f74f676e4cb9879ed1a121b43661a4154"
+
[[package]]
name = "macro_rules_attribute"
version = "0.2.2"
@@ -2348,13 +2699,14 @@ name = "open-ontologies"
version = "0.1.11"
dependencies = [
"anyhow",
- "arrow",
+ "arrow 54.3.1",
"axum",
"calamine",
"chrono",
"clap",
"csv",
"dirs",
+ "duckdb",
"oxigraph",
"parquet",
"quick-xml 0.37.5",
@@ -2596,14 +2948,14 @@ version = "54.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bfb15796ac6f56b429fd99e33ba133783ad75b27c36b4b5ce06f1f82cc97754e"
dependencies = [
- "ahash",
- "arrow-array",
- "arrow-buffer",
- "arrow-cast",
- "arrow-data",
+ "ahash 0.8.12",
+ "arrow-array 54.3.1",
+ "arrow-buffer 54.3.1",
+ "arrow-cast 54.3.1",
+ "arrow-data 54.3.1",
"arrow-ipc",
- "arrow-schema",
- "arrow-select",
+ "arrow-schema 54.3.1",
+ "arrow-select 54.3.1",
"base64 0.22.1",
"bytes",
"chrono",
@@ -2787,6 +3139,15 @@ dependencies = [
"num-integer",
]
+[[package]]
+name = "proc-macro-crate"
+version = "3.5.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e67ba7e9b2b56446f1d419b1d807906278ffa1a658a8a5d8a39dcb1f5a78614f"
+dependencies = [
+ "toml_edit 0.25.11+spec-1.1.0",
+]
+
[[package]]
name = "proc-macro2"
version = "1.0.106"
@@ -2819,6 +3180,26 @@ dependencies = [
"syn 1.0.109",
]
+[[package]]
+name = "ptr_meta"
+version = "0.1.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0738ccf7ea06b608c10564b31debd4f5bc5e197fc8bfe088f68ae5ce81e7a4f1"
+dependencies = [
+ "ptr_meta_derive",
+]
+
+[[package]]
+name = "ptr_meta_derive"
+version = "0.1.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "16b845dbfca988fa33db069c0e230574d15a3088f147a87b64c7589eb662c9ac"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 1.0.109",
+]
+
[[package]]
name = "quick-xml"
version = "0.31.0"
@@ -2839,6 +3220,61 @@ dependencies = [
"serde",
]
+[[package]]
+name = "quinn"
+version = "0.11.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b9e20a958963c291dc322d98411f541009df2ced7b5a4f2bd52337638cfccf20"
+dependencies = [
+ "bytes",
+ "cfg_aliases",
+ "pin-project-lite",
+ "quinn-proto",
+ "quinn-udp",
+ "rustc-hash",
+ "rustls",
+ "socket2",
+ "thiserror",
+ "tokio",
+ "tracing",
+ "web-time",
+]
+
+[[package]]
+name = "quinn-proto"
+version = "0.11.14"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "434b42fec591c96ef50e21e886936e66d3cc3f737104fdb9b737c40ffb94c098"
+dependencies = [
+ "bytes",
+ "getrandom 0.3.4",
+ "lru-slab",
+ "rand 0.9.2",
+ "ring",
+ "rustc-hash",
+ "rustls",
+ "rustls-pki-types",
+ "slab",
+ "thiserror",
+ "tinyvec",
+ "tracing",
+ "web-time",
+]
+
+[[package]]
+name = "quinn-udp"
+version = "0.5.14"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "addec6a0dcad8a8d96a771f815f0eaf55f9d1805756410b39f5fa81332574cbd"
+dependencies = [
+ "cfg_aliases",
+ "libc",
+ "once_cell",
+ "socket2",
+ "tracing",
+ "windows-sys 0.52.0",
+]
+
[[package]]
name = "quote"
version = "1.0.45"
@@ -2860,6 +3296,12 @@ version = "6.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf"
+[[package]]
+name = "radium"
+version = "0.7.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "dc33ff2d4973d518d823d61aa239014831e521c75da58e3df4840d3f47749d09"
+
[[package]]
name = "rand"
version = "0.8.5"
@@ -3061,6 +3503,15 @@ version = "0.8.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dc897dd8d9e8bd1ed8cdad82b5966c3e0ecae09fb1907d58efaa013543185d0a"
+[[package]]
+name = "rend"
+version = "0.4.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "71fe3824f5629716b1589be05dacd749f6aa084c87e00e016714a8cdfccc997c"
+dependencies = [
+ "bytecheck",
+]
+
[[package]]
name = "reqwest"
version = "0.12.28"
@@ -3070,7 +3521,9 @@ dependencies = [
"base64 0.22.1",
"bytes",
"encoding_rs",
+ "futures-channel",
"futures-core",
+ "futures-util",
"h2",
"http",
"http-body",
@@ -3085,6 +3538,8 @@ dependencies = [
"native-tls",
"percent-encoding",
"pin-project-lite",
+ "quinn",
+ "rustls",
"rustls-pki-types",
"serde",
"serde_json",
@@ -3092,6 +3547,7 @@ dependencies = [
"sync_wrapper",
"tokio",
"tokio-native-tls",
+ "tokio-rustls",
"tower",
"tower-http",
"tower-service",
@@ -3099,6 +3555,7 @@ dependencies = [
"wasm-bindgen",
"wasm-bindgen-futures",
"web-sys",
+ "webpki-roots",
]
[[package]]
@@ -3115,6 +3572,35 @@ dependencies = [
"windows-sys 0.52.0",
]
+[[package]]
+name = "rkyv"
+version = "0.7.46"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2297bf9c81a3f0dc96bc9521370b88f054168c29826a75e89c55ff196e7ed6a1"
+dependencies = [
+ "bitvec",
+ "bytecheck",
+ "bytes",
+ "hashbrown 0.12.3",
+ "ptr_meta",
+ "rend",
+ "rkyv_derive",
+ "seahash",
+ "tinyvec",
+ "uuid",
+]
+
+[[package]]
+name = "rkyv_derive"
+version = "0.7.46"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "84d7b42d4b8d06048d3ac8db0eb31bcb942cbeb709f0b5f2b2ebde398d3038f5"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 1.0.109",
+]
+
[[package]]
name = "rmcp"
version = "1.1.1"
@@ -3173,6 +3659,23 @@ dependencies = [
"smallvec",
]
+[[package]]
+name = "rust_decimal"
+version = "1.41.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2ce901f9a19d251159075a4c37af514c3b8ef99c22e02dd8c19161cf397ee94a"
+dependencies = [
+ "arrayvec",
+ "borsh",
+ "bytes",
+ "num-traits",
+ "rand 0.8.5",
+ "rkyv",
+ "serde",
+ "serde_json",
+ "wasm-bindgen",
+]
+
[[package]]
name = "rustc-hash"
version = "2.1.1"
@@ -3202,6 +3705,19 @@ dependencies = [
"transpose",
]
+[[package]]
+name = "rustix"
+version = "0.38.44"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "fdb5bc1ae2baa591800df16c9ca78619bf65c0488b41b96ccec5d11220d8c154"
+dependencies = [
+ "bitflags 2.11.0",
+ "errno",
+ "libc",
+ "linux-raw-sys 0.4.15",
+ "windows-sys 0.52.0",
+]
+
[[package]]
name = "rustix"
version = "1.1.4"
@@ -3211,7 +3727,7 @@ dependencies = [
"bitflags 2.11.0",
"errno",
"libc",
- "linux-raw-sys",
+ "linux-raw-sys 0.12.1",
"windows-sys 0.61.2",
]
@@ -3222,6 +3738,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "758025cb5fccfd3bc2fd74708fd4682be41d99e5dff73c377c0646c6012c73a4"
dependencies = [
"once_cell",
+ "ring",
"rustls-pki-types",
"rustls-webpki",
"subtle",
@@ -3234,6 +3751,7 @@ version = "1.14.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "be040f8b0a225e40375822a563fa9524378b9d63112f53e19ffff34df5d33fdd"
dependencies = [
+ "web-time",
"zeroize",
]
@@ -3319,6 +3837,12 @@ version = "1.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49"
+[[package]]
+name = "seahash"
+version = "4.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1c107b6f4780854c8b126e228ea8869f4d7b71260f962fefb57b996b8959ba6b"
+
[[package]]
name = "security-framework"
version = "3.7.0"
@@ -3799,6 +4323,27 @@ version = "0.11.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f"
+[[package]]
+name = "strum"
+version = "0.27.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "af23d6f6c1a224baef9d3f61e287d2761385a5b88fdab4eb4c6f11aeb54c4bcf"
+dependencies = [
+ "strum_macros",
+]
+
+[[package]]
+name = "strum_macros"
+version = "0.27.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7695ce3845ea4b33927c055a39dc438a45b059f7c1b3d91d38d10355fb8cbca7"
+dependencies = [
+ "heck",
+ "proc-macro2",
+ "quote",
+ "syn 2.0.117",
+]
+
[[package]]
name = "subtle"
version = "2.6.1"
@@ -3868,6 +4413,12 @@ dependencies = [
"libc",
]
+[[package]]
+name = "tap"
+version = "1.0.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "55937e1799185b12863d447f42597ed69d9928686b8d88a1df17376a097d8369"
+
[[package]]
name = "tar"
version = "0.4.45"
@@ -3888,7 +4439,7 @@ dependencies = [
"fastrand",
"getrandom 0.4.2",
"once_cell",
- "rustix",
+ "rustix 1.1.4",
"windows-sys 0.61.2",
]
@@ -4003,7 +4554,7 @@ version = "0.21.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a620b996116a59e184c2fa2dfd8251ea34a36d0a514758c6f966386bd2e03476"
dependencies = [
- "ahash",
+ "ahash 0.8.12",
"aho-corasick",
"compact_str",
"dary_heap",
@@ -4110,8 +4661,8 @@ checksum = "dc1beb996b9d83529a9e75c17a1686767d148d70663143c7854d8b4a09ced362"
dependencies = [
"serde",
"serde_spanned",
- "toml_datetime",
- "toml_edit",
+ "toml_datetime 0.6.11",
+ "toml_edit 0.22.27",
]
[[package]]
@@ -4123,6 +4674,15 @@ dependencies = [
"serde",
]
+[[package]]
+name = "toml_datetime"
+version = "1.1.1+spec-1.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3165f65f62e28e0115a00b2ebdd37eb6f3b641855f9d636d3cd4103767159ad7"
+dependencies = [
+ "serde_core",
+]
+
[[package]]
name = "toml_edit"
version = "0.22.27"
@@ -4132,9 +4692,30 @@ dependencies = [
"indexmap",
"serde",
"serde_spanned",
- "toml_datetime",
+ "toml_datetime 0.6.11",
"toml_write",
- "winnow",
+ "winnow 0.7.15",
+]
+
+[[package]]
+name = "toml_edit"
+version = "0.25.11+spec-1.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0b59c4d22ed448339746c59b905d24568fcbb3ab65a500494f7b8c3e97739f2b"
+dependencies = [
+ "indexmap",
+ "toml_datetime 1.1.1+spec-1.1.0",
+ "toml_parser",
+ "winnow 1.0.2",
+]
+
+[[package]]
+name = "toml_parser"
+version = "1.1.2+spec-1.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a2abe9b86193656635d2411dc43050282ca48aa31c2451210f4202550afb7526"
+dependencies = [
+ "winnow 1.0.2",
]
[[package]]
@@ -4481,6 +5062,12 @@ version = "1.12.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f6ccf251212114b54433ec949fd6a7841275f9ada20dddd2f29e9ceea4501493"
+[[package]]
+name = "unicode-width"
+version = "0.2.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b4ac048d71ede7ee76d585517add45da530660ef4390e49b098733c6e897f254"
+
[[package]]
name = "unicode-xid"
version = "0.2.6"
@@ -4616,6 +5203,7 @@ dependencies = [
"cfg-if",
"once_cell",
"rustversion",
+ "serde",
"wasm-bindgen-macro",
"wasm-bindgen-shared",
]
@@ -4710,6 +5298,25 @@ dependencies = [
"wasm-bindgen",
]
+[[package]]
+name = "web-time"
+version = "1.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5a6580f308b1fad9207618087a65c04e7a10bc77e02c8e84e9b00dd4b12fa0bb"
+dependencies = [
+ "js-sys",
+ "wasm-bindgen",
+]
+
+[[package]]
+name = "webpki-roots"
+version = "1.0.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "52f5ee44c96cf55f1b349600768e3ece3a8f26010c05265ab73f945bb1a2eb9d"
+dependencies = [
+ "rustls-pki-types",
+]
+
[[package]]
name = "whoami"
version = "1.6.1"
@@ -4720,6 +5327,22 @@ dependencies = [
"wasite",
]
+[[package]]
+name = "winapi"
+version = "0.3.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419"
+dependencies = [
+ "winapi-i686-pc-windows-gnu",
+ "winapi-x86_64-pc-windows-gnu",
+]
+
+[[package]]
+name = "winapi-i686-pc-windows-gnu"
+version = "0.4.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6"
+
[[package]]
name = "winapi-util"
version = "0.1.11"
@@ -4729,6 +5352,12 @@ dependencies = [
"windows-sys 0.61.2",
]
+[[package]]
+name = "winapi-x86_64-pc-windows-gnu"
+version = "0.4.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f"
+
[[package]]
name = "windows-core"
version = "0.62.2"
@@ -4956,6 +5585,15 @@ dependencies = [
"memchr",
]
+[[package]]
+name = "winnow"
+version = "1.0.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2ee1708bef14716a11bae175f579062d4554d95be2c6829f518df847b7b3fdd0"
+dependencies = [
+ "memchr",
+]
+
[[package]]
name = "wit-bindgen"
version = "0.51.0"
@@ -5050,6 +5688,15 @@ version = "0.6.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9edde0db4769d2dc68579893f2306b26c6ecfbe0ef499b013d731b7b9247e0b9"
+[[package]]
+name = "wyz"
+version = "0.5.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "05f360fc0b24296329c78fda852a1e9ae82de9cf7b27dae4b7f62f118f77b9ed"
+dependencies = [
+ "tap",
+]
+
[[package]]
name = "xattr"
version = "1.6.1"
@@ -5057,7 +5704,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "32e45ad4206f6d2479085147f02bc2ef834ac85886624a23575ae137c8aa8156"
dependencies = [
"libc",
- "rustix",
+ "rustix 1.1.4",
]
[[package]]
@@ -5180,6 +5827,26 @@ dependencies = [
"zopfli",
]
+[[package]]
+name = "zip"
+version = "6.0.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "eb2a05c7c36fde6c09b08576c9f7fb4cda705990f73b58fe011abf7dfb24168b"
+dependencies = [
+ "arbitrary",
+ "crc32fast",
+ "flate2",
+ "indexmap",
+ "memchr",
+ "zopfli",
+]
+
+[[package]]
+name = "zlib-rs"
+version = "0.6.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3be3d40e40a133f9c916ee3f9f4fa2d9d63435b5fbe1bfc6d9dae0aa0ada1513"
+
[[package]]
name = "zmij"
version = "1.0.21"
diff --git a/Cargo.toml b/Cargo.toml
index a4c79662..c986e2eb 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -37,6 +37,7 @@ calamine = "0.26"
arrow = { version = "54", default-features = false, features = ["csv", "json"] }
parquet = { version = "54", default-features = false, features = ["arrow"] }
sqlx = { version = "0.8", default-features = false, features = ["runtime-tokio", "postgres"], optional = true }
+duckdb = { version = "1", optional = true, features = ["bundled"] }
tract-onnx = { version = "0.21", optional = true }
tokenizers = { version = "0.21", optional = true, default-features = false, features = ["onig"] }
dirs = "6"
@@ -45,6 +46,8 @@ shell-words = "1"
[features]
default = []
postgres = ["sqlx"]
+duckdb = ["dep:duckdb"]
+sql = ["postgres", "duckdb"]
embeddings = ["tract-onnx", "tokenizers"]
[dev-dependencies]
diff --git a/SKILL.md b/SKILL.md
index 715cd1d6..513bac16 100644
--- a/SKILL.md
+++ b/SKILL.md
@@ -2,10 +2,11 @@
name: open-ontologies
version: "0.5.1"
description: >
- AI-native ontology engineering using 39+ MCP tools backed by an in-memory Oxigraph triple store.
+ AI-native ontology engineering using 50+ MCP tools backed by an in-memory Oxigraph triple store.
Build, validate, query, and govern RDF/OWL ontologies with a generate-validate-iterate loop.
Use when building ontologies, knowledge graphs, RDF data, SPARQL queries, BORO/4D modeling,
- SHACL validation, clinical terminology mapping, or Terraform-style ontology lifecycle management.
+ SHACL validation, clinical terminology mapping, ingesting from CSV/JSON/Parquet/XLSX or
+ SQL backbones (PostgreSQL, DuckDB), or Terraform-style ontology lifecycle management.
tags:
- ontology
- rdf
@@ -184,6 +185,15 @@ For aligning two ontologies:
| `onto_cache_remove` | Remove a cached ontology by `name` (pass `delete_file=false` to keep the on-disk N-Triples) |
| `onto_repo_list` | List RDF/OWL files in configured `[general] ontology_dirs` directories |
| `onto_repo_load` | Load an ontology from a configured repo by bare name, relative path, or absolute path |
+| `onto_status` | Server health / loaded triple count |
+| `onto_marketplace` | Browse / install standard ontologies from the curated catalogue |
+| `onto_dl_check` | Check `subClass ⊑ superClass` via DL tableaux |
+| `onto_dl_explain` | Explain why a class is unsatisfiable (DL clash trace) |
+| `onto_embed` | Generate text + Poincaré structural embeddings for all classes |
+| `onto_search` | Natural-language query → most-similar classes |
+| `onto_similarity` | Cosine + Poincaré distance between two IRIs |
+| `onto_import_schema` | Introspect PostgreSQL or DuckDB schema → generate OWL classes/properties/cardinality |
+| `onto_sql_ingest` | Run SQL `SELECT` against PostgreSQL or DuckDB → RDF (DuckDB enables federation over CSV/Parquet/JSON/HTTPFS/postgres-scanner via its extensions) |
## Usage Examples
diff --git a/docs/data-pipeline.md b/docs/data-pipeline.md
index da60a3ba..d3b62831 100644
--- a/docs/data-pipeline.md
+++ b/docs/data-pipeline.md
@@ -1,17 +1,21 @@
# Data Pipeline
-Take any structured data — CSV, JSON, Parquet, XLSX, XML, YAML — and terraform it into a validated, reasoned knowledge graph.
+Take any structured data — CSV, JSON, Parquet, XLSX, XML, YAML, **or rows
+returned by a SQL query against PostgreSQL or DuckDB** — and terraform it into
+a validated, reasoned knowledge graph.
```mermaid
flowchart LR
- Data["CSV / JSON / XLSX / ..."]
+ File["File: CSV / JSON / XLSX / Parquet / ..."]
+ SQL["SQL backbone: Postgres / DuckDB"]
Map["onto_map — generate mapping"]
- Ingest["onto_ingest — parse to RDF"]
+ Ingest["onto_ingest / onto_sql_ingest — parse to RDF"]
Validate["onto_shacl — check constraints"]
Reason["onto_reason — infer new facts"]
Query["onto_query — ask questions"]
- Data --> Map
+ File --> Map
+ SQL --> Map
Map --> Ingest
Ingest --> Validate
Validate -->|violations| Map
@@ -19,30 +23,72 @@ flowchart LR
Reason --> Query
```
-| Manual process | Open Ontologies equivalent |
-| -------------- | ------------------------- |
-| Domain expert defines classes by hand | `import-schema` or Claude generates OWL |
-| Analyst maps spreadsheet columns to ontology | `map` auto-generates mapping config |
-| Data engineer writes ETL to RDF | `ingest` parses CSV/JSON/Parquet/XLSX → RDF |
-| Ontologist validates data constraints | `shacl` checks cardinality, datatypes, classes |
-| Reasoner classifies instances (Protege + HermiT) | `reason` runs native OWL2-DL classification |
-| Quality reviewer checks consistency | `enforce` + `lint` + `monitor` |
+| Manual process | Open Ontologies equivalent |
+| ------------------------------------------------ | --------------------------------------------------- |
+| Domain expert defines classes by hand | `import-schema` or Claude generates OWL |
+| Analyst maps spreadsheet columns to ontology | `onto_map` auto-generates mapping config |
+| Data engineer writes ETL to RDF | `onto_ingest` parses CSV/JSON/Parquet/XLSX → RDF |
+| Data engineer writes ETL from a database | `onto_sql_ingest` runs a SQL query → RDF |
+| Ontologist validates data constraints | `onto_shacl` checks cardinality, datatypes, classes |
+| Reasoner classifies instances (Protege + HermiT) | `onto_reason` runs native OWL reasoning |
+| Quality reviewer checks consistency | `onto_enforce` + `onto_lint` + `onto_monitor` |
-## Supported Formats
+## Two ways to feed the pipeline
-| Format | Extension |
-| ------ | --------- |
-| CSV | `.csv` |
-| JSON | `.json` |
-| NDJSON | `.ndjson` |
-| XML | `.xml` |
-| YAML | `.yaml` |
-| Excel | `.xlsx` |
-| Parquet | `.parquet` |
+The pipeline accepts data from **two sources** that converge on the same
+mapping/ingest/SHACL/reason loop:
-## Mapping Config
+1. **File-based** — a single file in any of the supported formats below.
+ Use `onto_ingest` (MCP) or `ingest` (CLI).
+2. **SQL-based** — a SQL `SELECT` against a relational backbone (PostgreSQL
+ or DuckDB). Use `onto_sql_ingest` (MCP) or `sql-ingest` (CLI). Rows
+ returned by the query become "virtual records" that flow through the
+ exact same mapping config.
-The mapping bridges tabular data and RDF:
+In both cases the *same* `MappingConfig` is used, so a mapping written for a
+CSV can be re-used verbatim against the SQL row stream, and vice versa.
+
+## Supported file formats
+
+| Format | Extension |
+| ------- | ----------- |
+| CSV | `.csv` |
+| JSON | `.json` |
+| NDJSON | `.ndjson` |
+| XML | `.xml` |
+| YAML | `.yaml` |
+| Excel | `.xlsx` |
+| Parquet | `.parquet` |
+
+## Supported SQL backbones
+
+`onto_sql_ingest` and `onto_import_schema` accept a connection string and
+auto-dispatch on its scheme:
+
+| Connection string | Driver | Cargo feature |
+| ------------------------------------------ | ------------ | -------------------------- |
+| `postgres://user:pass@host/db` | PostgreSQL | `--features postgres` |
+| `postgresql://user:pass@host/db` | PostgreSQL | `--features postgres` |
+| `duckdb:///absolute/path/to/file.duckdb` | DuckDB | `--features duckdb` |
+| `duckdb:./relative/path.ddb` | DuckDB | `--features duckdb` |
+| `:memory:` | DuckDB | `--features duckdb` |
+| `/abs/file.duckdb` *(bare path)* | DuckDB | `--features duckdb` |
+
+Use the umbrella `--features sql` to enable both at once. By default the
+binary is built with **no** SQL features so the dependency footprint stays
+small; consumers opt in only to what they need.
+
+> **Why DuckDB?** DuckDB is *not* used as a SPARQL parser — that role is
+> already filled by Oxigraph. DuckDB is wired in as a **data integration
+> backbone**: a single embedded process that can `SELECT` over CSV, Parquet,
+> JSON, S3/HTTPFS, PostgreSQL, SQLite, Iceberg, and Delta tables through its
+> extension ecosystem. One SQL query becomes one RDF feed, and the rest of
+> the pipeline (`onto_shacl`, `onto_reason`, `onto_query`) is unchanged.
+
+## Mapping config
+
+The mapping bridges tabular data and RDF. The exact same JSON config is
+accepted by `onto_ingest` (file rows) and `onto_sql_ingest` (SQL rows).
```json
{
@@ -50,26 +96,193 @@ The mapping bridges tabular data and RDF:
"id_field": "name",
"class": "http://www.co-ode.org/ontologies/pizza/pizza.owl#NamedPizza",
"mappings": [
- { "field": "base", "predicate": "pizza:hasBase", "lookup": true },
+ { "field": "base", "predicate": "pizza:hasBase", "lookup": true },
{ "field": "topping1", "predicate": "pizza:hasTopping", "lookup": true },
- { "field": "price", "predicate": "pizza:hasPrice", "datatype": "xsd:decimal" }
+ { "field": "price", "predicate": "pizza:hasPrice", "datatype": "xsd:decimal" }
]
}
```
-- **`lookup: true`** — IRI reference (links to another entity)
-- **`datatype`** — typed literal (decimal, integer, date)
-- **Neither** — plain string literal
+- **`lookup: true`** — IRI reference (links to another entity).
+- **`datatype`** — typed literal (decimal, integer, date, …).
+- **Neither** — plain string literal.
+- **`id_field`** — column whose value is appended to `base_iri` to mint the
+ subject IRI.
+
+When a mapping is omitted, `onto_ingest` / `onto_sql_ingest` auto-generate one
+from the column names so you can iterate fast and refine later.
+
+## SQL ingest in three modes
+
+### 1. Pull from PostgreSQL
+
+```bash
+# Run a query over a live Postgres database
+open-ontologies sql-ingest \
+ postgres://demo:demo@localhost/shop \
+ "SELECT id AS name, base, price FROM pizza WHERE active" \
+ --mapping ./mapping.pizza.json \
+ --base-iri http://example.org/data/
+```
+
+### 2. Pull from DuckDB (file-backed warehouse)
+
+```bash
+# Materialised analytical store — fast columnar reads, zero infra
+open-ontologies sql-ingest \
+ duckdb:///data/warehouse.duckdb \
+ "SELECT customer_id AS name, region, lifetime_value FROM customer_summary" \
+ --mapping ./mapping.customer.json
+```
+
+### 3. Federated SQL via DuckDB extensions (in-memory)
+
+DuckDB's strength is *federation*: a single SQL query can read remote files,
+object stores, and other databases. `onto_sql_ingest` simply runs the query —
+the federation is handled inside DuckDB.
+
+```bash
+# Federate Parquet on S3, a CSV on HTTPS, and a Postgres scanner — all in one
+# SQL query — then ingest the result.
+open-ontologies sql-ingest :memory: "
+INSTALL httpfs; LOAD httpfs;
+INSTALL postgres_scanner; LOAD postgres_scanner;
+ATTACH 'host=localhost dbname=shop user=demo' AS shop (TYPE postgres);
+
+SELECT
+ o.order_id AS name,
+ c.country_code AS country,
+ o.total AS price,
+ p.category AS category
+FROM read_parquet('s3://datalake/orders/*.parquet') o
+JOIN shop.customers c USING (customer_id)
+JOIN read_csv_auto('https://example.com/products.csv') p USING (product_id)
+WHERE o.created_at >= '2026-01-01'
+" --mapping ./mapping.orders.json
+```
+
+The same query runs identically as MCP from Claude:
+
+```jsonc
+{
+ "tool": "onto_sql_ingest",
+ "arguments": {
+ "connection": ":memory:",
+ "sql": "INSTALL httpfs; LOAD httpfs; SELECT … FROM read_parquet('s3://…')",
+ "mapping": "./mapping.orders.json",
+ "base_iri": "http://example.org/data/"
+ }
+}
+```
+
+> 🛈 The `httpfs`, `postgres_scanner`, `iceberg`, `delta`, `aws`, `azure`, and
+> `gcp` DuckDB extensions are loaded inside the SQL itself with `INSTALL …;
+> LOAD …;` — they live entirely in DuckDB and require no special handling
+> from Open Ontologies. Credentials are passed via DuckDB's standard
+> `CREATE SECRET` / environment-variable mechanism, never written to RDF.
+
+## Schema → ontology in 3 commands
-## Demo: Database to Ontology in 3 Commands
+`onto_import_schema` introspects a database, generates OWL, and loads it into
+the triple store. The same command works against PostgreSQL **and** DuckDB —
+only the connection string changes.
```bash
-# Import a PostgreSQL schema as OWL
+# Import a PostgreSQL schema as OWL (requires --features postgres)
open-ontologies import-schema postgres://demo:demo@localhost/shop
-# Classify with native OWL2-DL reasoner
-open-ontologies reason --profile owl-dl
+# Import a DuckDB schema as OWL (requires --features duckdb)
+open-ontologies import-schema duckdb:///data/warehouse.duckdb
+
+# In-memory DuckDB — useful for unit tests / one-off CSV → OWL conversion
+open-ontologies import-schema :memory:
+```
+
+DuckDB's `CREATE TABLE … FROM read_csv(…)` lets you turn a directory of CSVs
+into a relational schema and then into OWL with a single pipeline:
+
+```bash
+duckdb /tmp/staging.duckdb <<'SQL'
+CREATE TABLE customers AS SELECT * FROM read_csv_auto('customers.csv');
+CREATE TABLE orders AS SELECT * FROM read_csv_auto('orders.csv');
+ALTER TABLE orders ADD CONSTRAINT fk_cust FOREIGN KEY (customer_id) REFERENCES customers(id);
+SQL
+
+open-ontologies import-schema duckdb:///tmp/staging.duckdb
+open-ontologies reason --profile owl-rl
+open-ontologies query "SELECT ?c ?label WHERE { ?c a owl:Class ; rdfs:label ?label }"
+```
+
+## Putting it together: the end-to-end loop
+
+```bash
+# 1. Generate or import the ontology
+open-ontologies import-schema duckdb:///data/warehouse.duckdb
+
+# 2. Generate a starter mapping from sample data (file or SQL — both work)
+open-ontologies map ./sample.csv --save mapping.json
+
+# 3. Ingest from SQL using that mapping
+open-ontologies sql-ingest duckdb:///data/warehouse.duckdb \
+ "SELECT * FROM customer_summary" --mapping mapping.json
-# Query the result
-open-ontologies query "SELECT ?c ?label WHERE { ?c a owl:Class . ?c rdfs:label ?label }"
+# 4. Validate, reason, query
+open-ontologies shacl ./shapes.ttl
+open-ontologies reason --profile rdfs
+open-ontologies query "SELECT ?c WHERE { ?c a :Customer }"
```
+
+Or, in MCP, use the convenience pipeline `onto_extend` for file-based data
+(it composes ingest + SHACL + reason in one call). The SQL equivalent is to
+call `onto_sql_ingest` followed by `onto_shacl` and `onto_reason`.
+
+## Tool reference
+
+| Tool | Purpose |
+| --------------------- | ----------------------------------------------------------------------------- |
+| `onto_map` | Inspect a data file, propose a mapping config |
+| `onto_ingest` | Parse a file (CSV/JSON/NDJSON/XML/YAML/XLSX/Parquet) → RDF and load |
+| `onto_sql_ingest` | Run SQL against Postgres or DuckDB → RDF and load (uses same mapping format) |
+| `onto_import_schema` | Introspect Postgres or DuckDB → OWL classes/properties/cardinality |
+| `onto_shacl` | Validate loaded data against SHACL shapes |
+| `onto_reason` | Materialise inferred triples (rdfs / owl-rl) |
+| `onto_extend` | File-based convenience: `onto_ingest` + `onto_shacl` + `onto_reason` |
+
+## Build matrix
+
+| Build command | Postgres | DuckDB | Embeddings |
+| ------------------------------------ | -------- | ------ | ---------- |
+| `cargo build` | ✗ | ✗ | ✗ |
+| `cargo build --features postgres` | ✓ | ✗ | ✗ |
+| `cargo build --features duckdb` | ✗ | ✓ | ✗ |
+| `cargo build --features sql` | ✓ | ✓ | ✗ |
+| `cargo build --features sql,embeddings` | ✓ | ✓ | ✓ |
+
+The `duckdb` crate is vendored with the `bundled` feature flag — no system
+DuckDB install is required, but the C++ source compile adds a few minutes to
+a clean build. Subsequent incremental builds are fast.
+
+## FAQ
+
+**Why not let DuckDB run SPARQL too?** DuckDB does not natively understand
+SPARQL or RDF, and Oxigraph already handles those. The split keeps each
+engine doing what it is best at: DuckDB owns *tabular SQL over heterogeneous
+sources*, Oxigraph owns *graph queries and reasoning*.
+
+**Can I use DuckDB to read a remote Parquet file directly without saving it
+locally?** Yes — `INSTALL httpfs; LOAD httpfs;` inside the SQL string passed
+to `onto_sql_ingest`. The remote bytes never touch disk; rows flow into RDF
+in one pass.
+
+**Does `onto_sql_ingest` support transactions?** No — it is read-only. The
+query may be a multi-statement script (e.g. `INSTALL httpfs; LOAD httpfs;
+SELECT …;`) and only the *final* `SELECT`'s rows are ingested.
+
+**How are NULLs handled?** They become empty strings in the row map. Use
+`datatype` mappings or SHACL to enforce typing where it matters.
+
+**Where do credentials go?** Connection strings are passed through verbatim
+to the underlying driver. For DuckDB, prefer `CREATE SECRET` (DuckDB's
+built-in secret manager) or environment variables (`AWS_…`, `AZURE_…`) over
+inlining secrets into SQL. For Postgres, prefer `~/.pgpass` or the standard
+`PGPASSWORD` env var.
diff --git a/skills/ontology-engineer.md b/skills/ontology-engineer.md
index 8201a876..623b0f6b 100644
--- a/skills/ontology-engineer.md
+++ b/skills/ontology-engineer.md
@@ -5,7 +5,7 @@ description: Use when building, modifying, or validating ontologies. Orchestrate
# Ontology Engineer
-AI-native ontology engineering using OpenCheir's `onto_*` MCP tools.
+AI-native ontology engineering using OpenCheir's `onto_*` MCP tools (50+ tools).
## When to Use
@@ -13,6 +13,8 @@ AI-native ontology engineering using OpenCheir's `onto_*` MCP tools.
- User asks to validate, lint, or query an existing ontology
- User mentions OWL, RDF, Turtle, SPARQL, BORO, 4D modeling, IES4
- User wants to compare ontologies or run competency questions
+- User needs to ingest tabular data, SQL query results, or a database schema into RDF
+- User wants to run reasoning (RDFS / OWL-RL) or DL satisfiability checks
## Prerequisites
@@ -28,12 +30,13 @@ Claude dynamically decides which tool to call next based on results. This is NOT
- What methodology? (standard OWL, BORO/4D, SKOS, etc.)
- What are the competency questions? (what should the ontology be able to answer?)
- Is there a reference ontology to compare against?
+- Is the source data a file, a SQL database (Postgres / DuckDB), or a federated SQL query?
-### Phase 2: Generate
+### Phase 2: Generate or Import
-- Generate Turtle/OWL directly from domain knowledge
-- Claude knows OWL, RDF, BORO, 4D modeling, every methodology natively
-- For complex methodologies, ask the user for background documents or constraints
+- For greenfield: generate Turtle/OWL directly from domain knowledge.
+- For an existing relational schema: call `onto_import_schema` with a Postgres or DuckDB connection string — it generates OWL classes, datatype/object properties, and cardinality from tables/columns/PKs/FKs.
+- For an existing on-disk corpus: configure `[general] ontology_dirs` and use `onto_repo_list` / `onto_repo_load` to discover and load.
### Phase 3: Validate (loop until clean)
@@ -47,18 +50,30 @@ onto_lint → issues found? → fix labels/domains/ranges, re-load
### Phase 4: Verify (loop until correct)
```
-onto_query → run SPARQL to check:
- - all expected classes present?
- - subclass hierarchies correct?
- - competency questions answerable?
-onto_diff → if reference exists, compare and report gaps
+onto_query → run SPARQL to check structure / competency questions
+onto_diff → compare vs a reference if one exists
+onto_dl_check → spot-check tricky subClass relations via DL tableaux
+onto_dl_explain → if a class is unsatisfiable, get the clash trace
```
-### Phase 5: Persist
+### Phase 5: Apply Data (optional)
+
+```
+onto_map → auto-generate a mapping from sample data + ontology
+onto_ingest → file-based: CSV/JSON/NDJSON/XML/YAML/XLSX/Parquet → RDF
+onto_sql_ingest → SQL-based: SELECT against Postgres or DuckDB → RDF
+onto_shacl → validate ingested data against shapes
+onto_reason → materialise inferred triples (rdfs / owl-rl)
+onto_extend → file-based shortcut: ingest + SHACL + reason in one call
+```
+
+### Phase 6: Persist + Govern
```
onto_version → save snapshot before finalizing
onto_save → write to .ttl file
+onto_plan / onto_enforce / onto_apply / onto_monitor / onto_drift
+ → Terraform-style lifecycle for evolving ontologies
```
## Key Rules
@@ -68,11 +83,15 @@ onto_save → write to .ttl file
3. **Always lint after loading** — `onto_lint` catches missing labels and domains
4. **Version before pushing** — `onto_version` before `onto_push` (enforcer rule)
5. **Iterate, don't declare done** — if any check fails, fix and re-run from Phase 3
+6. **Use embeddings for semantic search and alignment** — call `onto_embed` once after `onto_load`, then `onto_search` / `onto_similarity` work, and `onto_align` automatically uses embeddings as a 7th signal.
+7. **Cache, don't re-parse** — when juggling several `.ttl` files, use `onto_cache_list` / `onto_repo_load` to leverage the on-disk N-Triples cache.
## Tool Quick Reference
+### Core ontology
| Tool | Purpose |
| ---- | ------- |
+| `onto_status` | Server health and loaded triple count |
| `onto_validate` | Check OWL/RDF syntax (file or inline Turtle) |
| `onto_load` | Load into Oxigraph triple store |
| `onto_stats` | Class/property/triple counts |
@@ -82,9 +101,63 @@ onto_save → write to .ttl file
| `onto_save` | Persist to file |
| `onto_convert` | Format conversion |
| `onto_clear` | Reset the store |
-| `onto_pull` | Fetch from URL or SPARQL endpoint |
-| `onto_push` | Push to SPARQL endpoint |
-| `onto_import` | Resolve owl:imports |
-| `onto_version` | Save named snapshot |
-| `onto_history` | List snapshots |
-| `onto_rollback` | Restore previous version |
+
+### Cache and multi-file loading
+| Tool | Purpose |
+| ---- | ------- |
+| `onto_unload` | Drop the active (or named) ontology from memory |
+| `onto_recompile` | Re-parse the source, ignoring the cache |
+| `onto_cache_status` / `onto_cache_list` | Inspect compile cache |
+| `onto_cache_remove` | Drop a cached entry |
+| `onto_repo_list` | Enumerate `.ttl/.owl/.nt/.rdf/.nq/.trig/.jsonld` files in `[general] ontology_dirs` |
+| `onto_repo_load` | Load by name / relative path / absolute path inside a repo dir |
+
+### Remote and lifecycle
+| Tool | Purpose |
+| ---- | ------- |
+| `onto_pull` / `onto_push` | Fetch from / send to a remote URL or SPARQL endpoint |
+| `onto_marketplace` | Browse / install standard ontologies |
+| `onto_import` | Resolve `owl:imports` |
+| `onto_version` / `onto_history` / `onto_rollback` | Snapshots |
+| `onto_plan` / `onto_enforce` / `onto_apply` / `onto_lock` / `onto_drift` / `onto_monitor` / `onto_monitor_clear` / `onto_lineage` | Terraform-style lifecycle |
+| `onto_lint_feedback` / `onto_enforce_feedback` / `onto_align_feedback` | Self-calibrating suppression |
+
+### Data pipeline (file + SQL)
+| Tool | Purpose |
+| ---- | ------- |
+| `onto_map` | Generate mapping from data + ontology |
+| `onto_ingest` | File → RDF (CSV/JSON/NDJSON/XML/YAML/XLSX/Parquet) |
+| `onto_sql_ingest` | SQL `SELECT` against Postgres or DuckDB → RDF (same mapping format) |
+| `onto_import_schema` | Postgres or DuckDB schema → OWL |
+| `onto_shacl` | SHACL validation |
+| `onto_reason` | RDFS / OWL-RL inference |
+| `onto_extend` | File-based: ingest + SHACL + reason |
+| `onto_dl_check` / `onto_dl_explain` | DL tableaux subsumption / unsat explanation |
+
+### Clinical and alignment
+| Tool | Purpose |
+| ---- | ------- |
+| `onto_crosswalk` / `onto_enrich` / `onto_validate_clinical` | ICD-10 / SNOMED / MeSH crosswalks |
+| `onto_align` | Cross-ontology alignment (uses embeddings if loaded) |
+
+### Embeddings and semantic search
+| Tool | Purpose |
+| ---- | ------- |
+| `onto_embed` | Generate text + Poincaré structural embeddings for all classes |
+| `onto_search` | Natural-language query → most-similar classes |
+| `onto_similarity` | Cosine + Poincaré distance between two IRIs |
+
+## SQL Backbone Notes
+
+`onto_sql_ingest` and `onto_import_schema` accept any of:
+
+- `postgres://user:pass@host/db` (requires the `postgres` Cargo feature)
+- `duckdb:///path/to/file.duckdb`, `:memory:`, or a bare `*.duckdb` / `*.ddb` file path (requires the `duckdb` Cargo feature)
+
+DuckDB is wired in as a *data integration backbone*, not as a SPARQL parser:
+its `httpfs`, `parquet`, `csv`, `json`, `postgres_scanner`, `iceberg`, and
+`delta` extensions let one SQL query federate over remote files, object
+stores, and other databases — all of which then flow into the same mapping +
+SHACL + reasoning pipeline used for plain CSV/Parquet inputs. See
+`docs/data-pipeline.md` for full examples.
+
diff --git a/skills/ontology-engineering/SKILL.md b/skills/ontology-engineering/SKILL.md
index bde11328..cfdde2b6 100644
--- a/skills/ontology-engineering/SKILL.md
+++ b/skills/ontology-engineering/SKILL.md
@@ -5,7 +5,7 @@ description: Build, validate, and govern RDF/OWL ontologies using the Open Ontol
# Ontology Engineering Workflow
-You have access to the Open Ontologies MCP server, which provides 39+ tools for AI-native ontology engineering backed by an in-memory Oxigraph triple store.
+You have access to the Open Ontologies MCP server, which provides 50+ tools for AI-native ontology engineering backed by an in-memory Oxigraph triple store.
## Core Workflow
@@ -19,7 +19,7 @@ When building or modifying ontologies, follow this workflow. Decide which tools
### 2. Validate and Load
- Call `onto_validate` on the generated Turtle -- if it fails, fix syntax errors and re-validate
-- Call `onto_load` to load into the Oxigraph triple store
+- Call `onto_load` to load into the Oxigraph triple store. For repos that mount a folder of `.ttl` files via `[general] ontology_dirs`, prefer `onto_repo_load` so the same compile-cache / TTL-eviction path is exercised. Use `onto_repo_list` to discover candidate files.
- Call `onto_stats` to verify class count, property count, triple count match expectations
### 3. Verify
@@ -38,66 +38,115 @@ When building or modifying ontologies, follow this workflow. Decide which tools
- Call `onto_save` to write the final ontology to a .ttl file
- Call `onto_version` to save a named snapshot for rollback
+## Cache and Multi-Ontology Loading
+
+The server keeps a single *active* ontology in memory plus an on-disk N-Triples
+compile cache for everything it has parsed. Switch between several ontologies
+without paying re-parse costs:
+
+- `onto_repo_list` — enumerate `.ttl` / `.owl` / `.nt` / `.rdf` / `.nq` / `.trig` / `.jsonld` files configured under `[general] ontology_dirs`. Container-friendly: mount a host folder of TTL files and discover them at runtime without hardcoded paths.
+- `onto_repo_load` — load by bare file stem, relative path, or absolute path inside a configured repo dir. Reuses the same compile-cache / TTL-eviction path as `onto_load`.
+- `onto_cache_status` / `onto_cache_list` — inspect what is cached, what is currently active, and the effective `[cache]` configuration (TTL, auto_refresh, dir).
+- `onto_cache_remove` — drop a cached entry by name (pass `delete_file=false` to keep the on-disk N-Triples for a later reload).
+- `onto_unload` — drop the active ontology (or a specific cached entry by name) from memory; the on-disk cache is preserved unless `delete_cache=true`.
+- `onto_recompile` — force a re-parse from source, ignoring the cache. Without `name`, recompiles the active ontology and reloads it; with `name`, rebuilds a non-active entry without disturbing the active in-memory store.
+
## Ontology Lifecycle (Terraform-style)
For evolving ontologies in production:
-1. **Plan** -- `onto_plan` shows added/removed classes, blast radius, risk score. Check `onto_lock` for protected IRIs.
-2. **Enforce** -- `onto_enforce` with a rule pack (`generic`, `boro`, `value_partition`) checks design pattern compliance.
-3. **Apply** -- `onto_apply` with mode `safe` (clear + reload) or `migrate` (add equivalentClass bridges).
-4. **Monitor** -- `onto_monitor` runs SPARQL watchers with threshold alerts. Use `onto_monitor_clear` if blocked.
-5. **Drift** -- `onto_drift` compares versions with rename detection and self-calibrating confidence.
+1. **Plan** — `onto_plan` shows added/removed classes, blast radius, risk score. Check `onto_lock` for protected IRIs.
+2. **Enforce** — `onto_enforce` with a rule pack (`generic`, `boro`, `value_partition`, `hierarchy`) checks design pattern compliance.
+3. **Apply** — `onto_apply` with mode `safe` (clear + reload) or `migrate` (add equivalentClass bridges).
+4. **Monitor** — `onto_monitor` runs SPARQL watchers with threshold alerts. Use `onto_monitor_clear` if blocked.
+5. **Drift** — `onto_drift` compares versions with rename detection and self-calibrating confidence.
+6. **Lineage** — `onto_lineage` shows the full plan → enforce → apply → monitor → drift trail for the current session.
## Data Extension Workflow
When applying an ontology to external data:
-1. `onto_map` -- generate mapping config from data schema + loaded ontology
-2. `onto_ingest` -- parse structured data (CSV, JSON, NDJSON, XML, YAML, XLSX, Parquet) into RDF
-3. `onto_shacl` -- validate against SHACL shapes
-4. `onto_reason` -- run RDFS or OWL-RL inference
-5. Or use `onto_extend` to run the full pipeline in one call
+1. `onto_map` — generate mapping config from data schema + loaded ontology
+2. `onto_ingest` — parse a structured *file* (CSV, JSON, NDJSON, XML, YAML, XLSX, Parquet) into RDF
+3. `onto_sql_ingest` — run a SQL query against PostgreSQL or DuckDB (via `postgres://`, `duckdb:///path.duckdb`, `:memory:`, or a `*.duckdb` file path) and ingest result rows. Use this when the source data lives in a database, or when you want to use DuckDB as a federation layer over remote Parquet/CSV/JSON via the `httpfs`, `postgres_scanner`, `iceberg`, etc. extensions.
+4. `onto_import_schema` — introspect a PostgreSQL or DuckDB schema and generate OWL classes/properties/cardinality from tables/columns/PKs/FKs.
+5. `onto_shacl` — validate against SHACL shapes
+6. `onto_reason` — run RDFS or OWL-RL inference
+7. Or use `onto_extend` to run the full file-based pipeline (ingest + SHACL + reason) in one call
+
+## Reasoning and DL Explanation
+
+- `onto_reason` — RDFS / OWL-RL forward-chaining materialisation
+- `onto_dl_check` — check `subClass ⊑ superClass` using DL tableaux
+- `onto_dl_explain` — return the clash trace explaining why a class is unsatisfiable
+
+## Semantic Search and Embeddings
+
+After loading, generate embeddings to enable natural-language search:
+
+- `onto_embed` — generate text + Poincaré structural embeddings for every class. Honours `[embeddings] provider = "local" | "openai"` and the `OPEN_ONTOLOGIES_EMBEDDINGS_*` env vars.
+- `onto_search` — natural-language query → most-similar classes (`mode: "text" | "structure" | "product"`).
+- `onto_similarity` — compute cosine + Poincaré distance between two specific IRIs.
+
+When embeddings exist, `onto_align` automatically uses them as a 7th alignment signal, catching semantically equivalent classes whose labels differ.
## Tool Reference
| Tool | When to use |
| ---- | ----------- |
+| `onto_status` | Check that the server is running and how many triples are loaded |
| `onto_validate` | After generating or modifying Turtle -- always validate first |
-| `onto_load` | After validation passes -- loads into triple store |
-| `onto_stats` | After loading -- sanity check on counts |
-| `onto_lint` | After loading -- catches missing labels, domains, ranges |
+| `onto_load` | Load Turtle/N-Triples/RDF-XML into the triple store |
+| `onto_stats` | Sanity-check class / property / triple counts |
+| `onto_lint` | Catch missing labels, comments, domains, ranges |
| `onto_query` | Verify structure, answer competency questions |
| `onto_diff` | Compare against a reference or previous version |
-| `onto_save` | Persist ontology to a file |
-| `onto_convert` | Convert between formats (Turtle, N-Triples, RDF/XML, N-Quads, TriG) |
-| `onto_clear` | Reset the store before loading a different ontology |
+| `onto_save` | Persist the active ontology to a file |
+| `onto_convert` | Convert between Turtle, N-Triples, RDF/XML, N-Quads, TriG |
+| `onto_clear` | Reset the in-memory store |
| `onto_pull` | Fetch ontology from a remote URL or SPARQL endpoint |
-| `onto_push` | Push ontology to a SPARQL endpoint |
-| `onto_import` | Resolve and load owl:imports chains |
+| `onto_push` | Push triples to a SPARQL endpoint |
+| `onto_import` | Resolve and load `owl:imports` chains |
+| `onto_marketplace` | Browse / install standard ontologies from the curated catalogue |
| `onto_version` | Save a named snapshot before making changes |
-| `onto_history` | List saved version snapshots |
-| `onto_rollback` | Restore a previous version |
-| `onto_ingest` | Parse structured data into RDF and load into store |
-| `onto_map` | Generate mapping config from data schema + ontology |
-| `onto_shacl` | Validate data against SHACL shapes |
+| `onto_history` | List saved snapshots |
+| `onto_rollback` | Restore a previous snapshot |
+| `onto_unload` | Drop the active (or named) ontology from memory |
+| `onto_recompile` | Re-parse the source, ignoring the on-disk compile cache |
+| `onto_cache_status` | Inspect compile cache: active slot, all entries, `[cache]` config |
+| `onto_cache_list` | Lighter version of cache status — list cached ontologies with metadata |
+| `onto_cache_remove` | Remove a cached ontology by name |
+| `onto_repo_list` | Enumerate RDF/OWL files in configured `[general] ontology_dirs` |
+| `onto_repo_load` | Load by name / relative path / absolute path inside a configured repo dir |
+| `onto_ingest` | Parse a file (CSV, JSON, NDJSON, XML, YAML, XLSX, Parquet) into RDF |
+| `onto_sql_ingest` | **NEW** — SQL `SELECT` against PostgreSQL or DuckDB → RDF (uses the same mapping format as `onto_ingest`). DuckDB acts as a federation layer over CSV/Parquet/JSON/HTTPFS/postgres scanner via its extensions. |
+| `onto_import_schema` | Introspect PostgreSQL or DuckDB schema → generate OWL |
+| `onto_map` | Auto-generate mapping config from data schema + loaded ontology |
+| `onto_shacl` | Validate against SHACL shapes |
| `onto_reason` | Run RDFS or OWL-RL inference |
-| `onto_extend` | Full pipeline: ingest, SHACL validate, reason |
+| `onto_extend` | File-based convenience: ingest + SHACL + reason |
+| `onto_dl_check` | Check `subClass ⊑ superClass` via DL tableaux |
+| `onto_dl_explain` | Explain why a class is unsatisfiable (DL clash trace) |
| `onto_plan` | Show added/removed classes, blast radius, risk score |
-| `onto_apply` | Apply changes in safe or migrate mode |
+| `onto_apply` | Apply changes in `safe` or `migrate` mode |
| `onto_lock` | Protect production IRIs from removal |
| `onto_drift` | Compare versions with rename detection |
-| `onto_enforce` | Design pattern checks |
+| `onto_enforce` | Design pattern checks (`generic`, `boro`, `value_partition`, `hierarchy`) |
| `onto_monitor` | Run SPARQL watchers with threshold alerts |
| `onto_monitor_clear` | Clear blocked state after resolving alerts |
+| `onto_lineage` | View session lineage trail |
| `onto_crosswalk` | Look up clinical terminology mappings (ICD-10, SNOMED, MeSH) |
-| `onto_enrich` | Add skos:exactMatch triples linking to clinical codes |
-| `onto_validate_clinical` | Check class labels against clinical terminology |
-| `onto_align` | Detect alignment candidates between two ontologies |
+| `onto_enrich` | Add `skos:exactMatch` triples linking classes to clinical codes |
+| `onto_validate_clinical` | Check class labels against clinical crosswalk terminology |
+| `onto_align` | Detect alignment candidates between two ontologies (uses embeddings if loaded) |
| `onto_align_feedback` | Accept/reject alignment candidates for self-calibrating weights |
-| `onto_lineage` | View session lineage trail |
-| `onto_lint_feedback` | Accept/dismiss lint issues to teach suppression |
-| `onto_enforce_feedback` | Accept/dismiss enforce violations to teach suppression |
+| `onto_lint_feedback` | Accept/dismiss a lint issue (teaches lint to suppress repeated false positives) |
+| `onto_enforce_feedback` | Accept/dismiss an enforce violation (same self-calibration mechanism) |
+| `onto_embed` | Generate text + Poincaré structural embeddings for all classes |
+| `onto_search` | Natural-language query → most-similar classes (text / structure / product) |
+| `onto_similarity` | Cosine + Poincaré distance between two IRIs |
## Key Principle
Dynamically decide the next tool call based on what the previous tool returned. If `onto_validate` fails, fix and retry. If `onto_stats` shows wrong counts, regenerate. If `onto_lint` finds missing labels, add them. The MCP tools are individual operations -- you are the orchestrator.
+
diff --git a/src/inputs.rs b/src/inputs.rs
index 2b455ea2..d771de6e 100644
--- a/src/inputs.rs
+++ b/src/inputs.rs
@@ -318,12 +318,34 @@ pub struct OntoLineageInput {
#[derive(Deserialize, JsonSchema)]
pub struct OntoImportSchemaInput {
- /// Database connection string (e.g. postgres://user:pass@host/db)
+ /// Database connection string. Supported:
+ /// - `postgres://user:pass@host/db` (requires `postgres` feature)
+ /// - `duckdb:///path/to/file.duckdb` or bare `/path/to/file.duckdb` (requires `duckdb` feature)
+ /// - `:memory:` for an in-memory DuckDB database (requires `duckdb` feature)
pub connection: String,
/// Base IRI for generated classes (default: http://example.org/db/)
pub base_iri: Option<String>,
}
+#[derive(Deserialize, JsonSchema)]
+pub struct OntoSqlIngestInput {
+ /// Database connection string. Same forms as `onto_import_schema`:
+ /// `postgres://…`, `duckdb:///path/to.duckdb`, `:memory:`, or a bare
+ /// `*.duckdb` file path.
+ pub connection: String,
+ /// SQL SELECT statement to run. Returned rows are converted to RDF using
+ /// the supplied mapping (or an auto-generated one).
+ pub sql: String,
+ /// Mapping config as JSON string or path to a mapping JSON file.
+ /// Same shape as `onto_ingest`. Optional — if omitted, an auto-mapping
+ /// is generated from the column names.
+ pub mapping: Option<String>,
+ /// If true, treat `mapping` as inline JSON (default: false = file path).
+ pub inline_mapping: Option<bool>,
+ /// Base IRI for generated instances (default: http://example.org/data/)
+ pub base_iri: Option<String>,
+}
+
#[derive(Deserialize, JsonSchema)]
pub struct OntoAlignInput {
/// Source ontology: inline Turtle content or file path
diff --git a/src/lib.rs b/src/lib.rs
index a8e8419a..139fa774 100644
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -26,6 +26,7 @@ pub mod shacl;
pub mod state;
pub mod schema;
pub mod socket;
+pub mod sqlsource;
pub mod tableaux;
pub mod toolfilter;
#[cfg(feature = "embeddings")]
diff --git a/src/main.rs b/src/main.rs
index 26b4c28d..4869ceed 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -487,13 +487,34 @@ enum Commands {
ValidateClinical,
// ─── Schema import ────────────────────────────────────────────
- /// Import database schema as OWL ontology
+ /// Import database schema as OWL ontology (Postgres or DuckDB)
ImportSchema {
- /// Connection string (e.g. postgres://user:pass@host/db)
+ /// Connection string. Supported:
+ /// postgres://user:pass@host/db (requires --features postgres)
+ /// duckdb:///path/to/file.duckdb or *.duckdb file path (requires --features duckdb)
+ /// :memory: for an in-memory DuckDB database
connection: String,
#[arg(long, default_value = "http://example.org/db/")]
base_iri: String,
},
+ /// Run a SQL query against a relational backbone (Postgres or DuckDB)
+ /// and ingest the result rows into the triple store as RDF.
+ SqlIngest {
+ /// Connection string (see import-schema for forms)
+ connection: String,
+ /// SQL SELECT to execute. Use `-` to read from stdin.
+ sql: String,
+ /// Path to mapping JSON, or inline JSON when --inline-mapping is set.
+ /// If omitted, an auto-mapping is generated from the column names.
+ #[arg(long)]
+ mapping: Option<String>,
+ /// Treat the value of --mapping as inline JSON instead of a file path.
+ #[arg(long)]
+ inline_mapping: bool,
+ /// Base IRI for generated instances
+ #[arg(long, default_value = "http://example.org/data/")]
+ base_iri: String,
+ },
}
fn setup(data_dir: &str) -> anyhow::Result<(StateDb, Arc<GraphStore>)> {
@@ -1625,10 +1646,46 @@ async fn main() -> anyhow::Result<()> {
}
// ─── Schema import ─────────────────────────────────────────
- #[cfg(feature = "postgres")]
+ #[allow(unreachable_code, unused_variables)]
Commands::ImportSchema { connection, base_iri } => {
let (_db, graph) = setup(&cli.data_dir)?;
- let tables = open_ontologies::schema::SchemaIntrospector::introspect_postgres(&connection).await?;
+ let driver = match open_ontologies::sqlsource::detect_driver(&connection) {
+ Ok(d) => d,
+ Err(e) => {
+ output_json(&serde_json::json!({"error": e.to_string()}), cli.pretty);
+ std::process::exit(1);
+ }
+ };
+
+ let tables: Vec<open_ontologies::schema::TableInfo> = match driver {
+ open_ontologies::sqlsource::SqlDriver::Postgres => {
+ #[cfg(feature = "postgres")]
+ {
+ open_ontologies::schema::SchemaIntrospector::introspect_postgres(&connection).await?
+ }
+ #[cfg(not(feature = "postgres"))]
+ {
+ output_json(&serde_json::json!({"error": "import-schema for postgres requires the 'postgres' feature (compile with --features postgres)"}), cli.pretty);
+ std::process::exit(1);
+ }
+ }
+ open_ontologies::sqlsource::SqlDriver::DuckDb => {
+ #[cfg(feature = "duckdb")]
+ {
+ let target = open_ontologies::sqlsource::duckdb_target(&connection);
+ tokio::task::spawn_blocking(move || {
+ open_ontologies::schema::SchemaIntrospector::introspect_duckdb(&target)
+ })
+ .await??
+ }
+ #[cfg(not(feature = "duckdb"))]
+ {
+ output_json(&serde_json::json!({"error": "import-schema for duckdb requires the 'duckdb' feature (compile with --features duckdb)"}), cli.pretty);
+ std::process::exit(1);
+ }
+ }
+ };
+
let turtle = open_ontologies::schema::SchemaIntrospector::generate_turtle(&tables, &base_iri);
// Validate + load
@@ -1637,16 +1694,72 @@ async fn main() -> anyhow::Result<()> {
output_json(&serde_json::json!({
"ok": true,
+ "driver": driver.as_str(),
"tables": tables.len(),
"classes": tables.len(),
"triples": count,
"base_iri": base_iri,
}), cli.pretty);
}
- #[cfg(not(feature = "postgres"))]
- Commands::ImportSchema { .. } => {
- output_json(&serde_json::json!({"error": "import-schema requires the 'postgres' feature (compile with --features postgres)"}), cli.pretty);
- std::process::exit(1);
+ Commands::SqlIngest { connection, sql, mapping, inline_mapping, base_iri } => {
+ use open_ontologies::ingest::DataIngester;
+ use open_ontologies::mapping::MappingConfig;
+
+ let (_db, graph) = setup(&cli.data_dir)?;
+
+ // Allow stdin via `-`.
+ let sql = if sql == "-" {
+ use std::io::Read;
+ let mut buf = String::new();
+ std::io::stdin().read_to_string(&mut buf)?;
+ buf
+ } else {
+ sql
+ };
+
+ let driver = match open_ontologies::sqlsource::detect_driver(&connection) {
+ Ok(d) => d,
+ Err(e) => {
+ output_json(&serde_json::json!({"error": e.to_string()}), cli.pretty);
+ std::process::exit(1);
+ }
+ };
+
+ let rows = open_ontologies::sqlsource::query_rows(&connection, &sql).await?;
+
+ if rows.is_empty() {
+ output_json(&serde_json::json!({
+ "ok": true,
+ "driver": driver.as_str(),
+ "triples_loaded": 0,
+ "rows_processed": 0,
+ "warnings": ["Query returned no rows"],
+ }), cli.pretty);
+ return Ok(());
+ }
+
+ let mapping_cfg = if let Some(ref m) = mapping {
+ if inline_mapping {
+ serde_json::from_str::<MappingConfig>(m)?
+ } else {
+ let content = std::fs::read_to_string(m)?;
+ serde_json::from_str::<MappingConfig>(&content)?
+ }
+ } else {
+ let headers = DataIngester::extract_headers(&rows);
+ MappingConfig::from_headers(&headers, &base_iri, &format!("{}Thing", base_iri))
+ };
+
+ let ntriples = mapping_cfg.rows_to_ntriples(&rows);
+ let count = graph.load_ntriples(&ntriples)?;
+
+ output_json(&serde_json::json!({
+ "ok": true,
+ "driver": driver.as_str(),
+ "triples_loaded": count,
+ "rows_processed": rows.len(),
+ "mapping_fields": mapping_cfg.mappings.len(),
+ }), cli.pretty);
}
Commands::Align { source, target, min_confidence, dry_run } => {
let (db, graph) = setup(&cli.data_dir)?;
diff --git a/src/schema.rs b/src/schema.rs
index 549baf0f..3dda57f3 100644
--- a/src/schema.rs
+++ b/src/schema.rs
@@ -22,14 +22,30 @@ pub struct SchemaIntrospector;
impl SchemaIntrospector {
/// Convert SQL type name to XSD datatype.
+ ///
+ /// Recognises common Postgres and DuckDB type names. Parameterised types
+ /// like `DECIMAL(18,2)` or `VARCHAR(255)` are normalised by stripping the
+ /// `(...)` suffix before matching.
pub fn sql_to_xsd(sql_type: &str) -> &'static str {
- match sql_type.to_lowercase().as_str() {
- "integer" | "int" | "bigint" | "smallint" | "int4" | "int8" | "int2" | "serial" | "bigserial" => "xsd:integer",
- "numeric" | "decimal" | "real" | "double precision" | "float4" | "float8" => "xsd:decimal",
+ let lower = sql_type.to_lowercase();
+ // Strip parameters: "decimal(18,2)" → "decimal", "varchar(255)" → "varchar".
+ let base = match lower.find('(') {
+ Some(idx) => lower[..idx].trim().to_string(),
+ None => lower.trim().to_string(),
+ };
+ match base.as_str() {
+ "integer" | "int" | "bigint" | "smallint" | "tinyint" | "hugeint"
+ | "int4" | "int8" | "int2" | "int1" | "serial" | "bigserial"
+ | "smallserial" | "ubigint" | "uinteger" | "usmallint" | "utinyint" => "xsd:integer",
+ "numeric" | "decimal" | "real" | "double precision" | "double"
+ | "float" | "float4" | "float8" => "xsd:decimal",
"boolean" | "bool" => "xsd:boolean",
"date" => "xsd:date",
- "timestamp" | "timestamptz" | "timestamp without time zone" | "timestamp with time zone" => "xsd:dateTime",
+ "timestamp" | "timestamptz" | "timestamp without time zone"
+ | "timestamp with time zone" | "datetime" => "xsd:dateTime",
+ "time" | "time without time zone" | "time with time zone" => "xsd:time",
"bytea" | "blob" => "xsd:hexBinary",
+ "uuid" => "xsd:string",
_ => "xsd:string",
}
}
@@ -163,4 +179,121 @@ impl SchemaIntrospector {
pool.close().await;
Ok(tables)
}
+
+ /// Connect to a DuckDB database (file or in-memory), introspect schema,
+ /// return TableInfo vec. Reads from the SQL-standard
+ /// `information_schema.tables` / `information_schema.columns` and the
+ /// DuckDB-specific `duckdb_constraints()` table function for primary and
+ /// foreign keys.
+ #[cfg(feature = "duckdb")]
+ pub fn introspect_duckdb(target: &str) -> anyhow::Result<Vec<TableInfo>> {
+ use duckdb::Connection;
+
+ let conn = if target == ":memory:" {
+ Connection::open_in_memory()?
+ } else {
+ Connection::open(target)?
+ };
+
+ // Tables in the default schema (`main`). User tables only — exclude
+ // system schemas.
+ let mut stmt = conn.prepare(
+ "SELECT table_name FROM information_schema.tables \
+ WHERE table_schema = 'main' AND table_type = 'BASE TABLE' \
+ ORDER BY table_name",
+ )?;
+ let table_names: Vec<String> = stmt
+ .query_map([], |row| row.get::<_, String>(0))?
+ .collect::<Result<Vec<_>, _>>()?;
+ drop(stmt);
+
+ let mut tables = Vec::new();
+ for table_name in &table_names {
+ // Columns
+ let mut col_stmt = conn.prepare(
+ "SELECT column_name, data_type, is_nullable FROM information_schema.columns \
+ WHERE table_schema = 'main' AND table_name = ? ORDER BY ordinal_position",
+ )?;
+ let col_rows: Vec<(String, String, String)> = col_stmt
+ .query_map([table_name], |row| {
+ Ok((row.get::<_, String>(0)?, row.get::<_, String>(1)?, row.get::<_, String>(2)?))
+ })?
+ .collect::<Result<Vec<_>, _>>()?;
+ drop(col_stmt);
+
+ // Primary keys via duckdb_constraints(). The constraint_column_names
+ // column is a list of column names. Convert it to a comma-separated
+ // string in SQL because the duckdb-rs crate does not implement
+ // `FromSql` for `Vec<String>`.
+ let mut pk_stmt = conn.prepare(
+ "SELECT array_to_string(constraint_column_names, ',') AS cols \
+ FROM duckdb_constraints() \
+ WHERE schema_name = 'main' AND table_name = ? AND constraint_type = 'PRIMARY KEY'",
+ )?;
+ let pk_strings: Vec<String> = pk_stmt
+ .query_map([table_name], |row| row.get::<_, String>(0))?
+ .collect::<Result<Vec<_>, _>>()?;
+ drop(pk_stmt);
+ let pk_cols: Vec<String> = pk_strings
+ .into_iter()
+ .flat_map(|s| s.split(',').map(|p| p.trim().to_string()).collect::<Vec<_>>())
+ .filter(|s| !s.is_empty())
+ .collect();
+
+ // Foreign keys via duckdb_constraints(). Same trick: project list
+ // columns to comma-separated strings.
+ let mut fk_stmt = conn.prepare(
+ "SELECT array_to_string(constraint_column_names, ',') AS child_cols, \
+ referenced_table, \
+ array_to_string(referenced_column_names, ',') AS parent_cols \
+ FROM duckdb_constraints() \
+ WHERE schema_name = 'main' AND table_name = ? AND constraint_type = 'FOREIGN KEY'",
+ )?;
+ let fk_rows: Vec<(String, String, String)> = fk_stmt
+ .query_map([table_name], |row| {
+ Ok((
+ row.get::<_, String>(0)?,
+ row.get::<_, String>(1)?,
+ row.get::<_, String>(2)?,
+ ))
+ })?
+ .collect::<Result<Vec<_>, _>>()?;
+ drop(fk_stmt);
+
+ let mut foreign_keys = Vec::new();
+ for (child_cols, parent_table, parent_cols) in fk_rows {
+ let children: Vec<&str> =
+ child_cols.split(',').map(|s| s.trim()).filter(|s| !s.is_empty()).collect();
+ let parents: Vec<&str> =
+ parent_cols.split(',').map(|s| s.trim()).filter(|s| !s.is_empty()).collect();
+ for (i, child) in children.iter().enumerate() {
+ if let Some(parent) = parents.get(i) {
+ foreign_keys.push(ForeignKey {
+ column: (*child).to_string(),
+ parent_table: parent_table.clone(),
+ parent_column: (*parent).to_string(),
+ });
+ }
+ }
+ }
+
+ let columns: Vec<ColumnInfo> = col_rows
+ .into_iter()
+ .map(|(name, data_type, nullable)| ColumnInfo {
+ is_primary_key: pk_cols.contains(&name),
+ name,
+ data_type,
+ is_nullable: nullable.eq_ignore_ascii_case("YES"),
+ })
+ .collect();
+
+ tables.push(TableInfo {
+ name: table_name.clone(),
+ columns,
+ foreign_keys,
+ });
+ }
+
+ Ok(tables)
+ }
}
diff --git a/src/server.rs b/src/server.rs
index b2c04876..def7e039 100644
--- a/src/server.rs
+++ b/src/server.rs
@@ -1172,18 +1172,56 @@ impl OpenOntologiesServer {
}).to_string()
}
- #[tool(name = "onto_import_schema", description = "Import a PostgreSQL database schema as an OWL ontology. Introspects tables, columns, primary keys, and foreign keys, then generates OWL classes, datatype/object properties, and cardinality restrictions.")]
+ #[tool(name = "onto_import_schema", description = "Import a relational database schema as an OWL ontology. Supports PostgreSQL (postgres://…) and DuckDB (duckdb:///path.duckdb, :memory:, or *.duckdb file path). Introspects tables, columns, primary keys, and foreign keys, then generates OWL classes, datatype/object properties, and cardinality restrictions.")]
+ #[allow(unreachable_code, unused_variables, unused_assignments)]
async fn onto_import_schema(&self, Parameters(input): Parameters<OntoImportSchemaInput>) -> String {
- #[cfg(not(feature = "postgres"))]
- { let _ = input; return r#"{"error":"Compiled without postgres feature. Rebuild with --features postgres"}"#.to_string(); }
- #[cfg(feature = "postgres")]
- {
use crate::schema::SchemaIntrospector;
+ use crate::sqlsource;
+
let base_iri = input.base_iri.as_deref().unwrap_or("http://example.org/db/");
- let tables = match SchemaIntrospector::introspect_postgres(&input.connection).await {
- Ok(t) => t,
- Err(e) => return format!(r#"{{"error":"Connection failed: {}"}}"#, e),
+ // Dispatch by connection-string scheme. Both backbones land in the
+ // same OWL generator so the downstream pipeline (validate + load)
+ // is identical.
+ let driver = match sqlsource::detect_driver(&input.connection) {
+ Ok(d) => d,
+ Err(e) => return format!(r#"{{"error":"{}"}}"#, e),
+ };
+
+ let tables: Vec<crate::schema::TableInfo> = match driver {
+ crate::sqlsource::SqlDriver::Postgres => {
+ #[cfg(feature = "postgres")]
+ {
+ match SchemaIntrospector::introspect_postgres(&input.connection).await {
+ Ok(t) => t,
+ Err(e) => return format!(r#"{{"error":"Postgres connection failed: {}"}}"#, e),
+ }
+ }
+ #[cfg(not(feature = "postgres"))]
+ {
+ return r#"{"error":"Compiled without postgres feature. Rebuild with --features postgres"}"#.to_string();
+ }
+ }
+ crate::sqlsource::SqlDriver::DuckDb => {
+ #[cfg(feature = "duckdb")]
+ {
+ let target = sqlsource::duckdb_target(&input.connection);
+ // DuckDB introspection is sync; offload to blocking pool.
+ match tokio::task::spawn_blocking(move || {
+ SchemaIntrospector::introspect_duckdb(&target)
+ })
+ .await
+ {
+ Ok(Ok(t)) => t,
+ Ok(Err(e)) => return format!(r#"{{"error":"DuckDB introspection failed: {}"}}"#, e),
+ Err(e) => return format!(r#"{{"error":"DuckDB worker panicked: {}"}}"#, e),
+ }
+ }
+ #[cfg(not(feature = "duckdb"))]
+ {
+ return r#"{"error":"Compiled without duckdb feature. Rebuild with --features duckdb"}"#.to_string();
+ }
+ }
};
let turtle = SchemaIntrospector::generate_turtle(&tables, base_iri);
@@ -1196,6 +1234,7 @@ impl OpenOntologiesServer {
match self.graph.load_turtle(&turtle, Some(base_iri)) {
Ok(count) => serde_json::json!({
"ok": true,
+ "driver": driver.as_str(),
"tables": tables.len(),
"classes": tables.len(),
"triples": count,
@@ -1203,7 +1242,71 @@ impl OpenOntologiesServer {
}).to_string(),
Err(e) => format!(r#"{{"error":"Failed to load: {}"}}"#, e),
}
- } // cfg(feature = "postgres")
+ }
+
+ #[tool(name = "onto_sql_ingest", description = "Run a SQL query against a relational backbone (PostgreSQL or DuckDB) and ingest the resulting rows into the triple store as RDF. DuckDB is recommended as a federation layer: with its httpfs/parquet/csv/postgres_scanner extensions one query can union remote files, object stores, and other databases. The mapping config has the same shape as onto_ingest.")]
+ async fn onto_sql_ingest(&self, Parameters(input): Parameters<OntoSqlIngestInput>) -> String {
+ use crate::ingest::DataIngester;
+ use crate::mapping::MappingConfig;
+ use crate::sqlsource;
+
+ let base_iri = input.base_iri.as_deref().unwrap_or("http://example.org/data/");
+
+ // Validate connection scheme up front so we fail fast with a clear error.
+ let driver = match sqlsource::detect_driver(&input.connection) {
+ Ok(d) => d,
+ Err(e) => return format!(r#"{{"error":"{}"}}"#, e),
+ };
+
+ let rows = match sqlsource::query_rows(&input.connection, &input.sql).await {
+ Ok(r) => r,
+ Err(e) => return format!(r#"{{"error":"SQL query failed: {}"}}"#, e),
+ };
+
+ if rows.is_empty() {
+ return serde_json::json!({
+ "ok": true,
+ "driver": driver.as_str(),
+ "triples_loaded": 0,
+ "rows_processed": 0,
+ "warnings": ["Query returned no rows"],
+ })
+ .to_string();
+ }
+
+ // Resolve mapping (inline JSON / file path / auto from columns).
+ let mapping = if let Some(ref mapping_str) = input.mapping {
+ if input.inline_mapping.unwrap_or(false) {
+ match serde_json::from_str::<MappingConfig>(mapping_str) {
+ Ok(m) => m,
+ Err(e) => return format!(r#"{{"error":"Invalid mapping JSON: {}"}}"#, e),
+ }
+ } else {
+ match std::fs::read_to_string(mapping_str) {
+ Ok(content) => match serde_json::from_str::<MappingConfig>(&content) {
+ Ok(m) => m,
+ Err(e) => return format!(r#"{{"error":"Invalid mapping file: {}"}}"#, e),
+ },
+ Err(e) => return format!(r#"{{"error":"Cannot read mapping file: {}"}}"#, e),
+ }
+ }
+ } else {
+ let headers = DataIngester::extract_headers(&rows);
+ MappingConfig::from_headers(&headers, base_iri, &format!("{}Thing", base_iri))
+ };
+
+ let ntriples = mapping.rows_to_ntriples(&rows);
+ match self.graph.load_ntriples(&ntriples) {
+ Ok(count) => serde_json::json!({
+ "ok": true,
+ "driver": driver.as_str(),
+ "triples_loaded": count,
+ "rows_processed": rows.len(),
+ "mapping_fields": mapping.mappings.len(),
+ })
+ .to_string(),
+ Err(e) => format!(r#"{{"error":"Failed to load triples: {}"}}"#, e),
+ }
}
#[tool(name = "onto_align", description = "Detect alignment candidates (owl:equivalentClass, skos:exactMatch, rdfs:subClassOf) between two ontologies using label similarity, property overlap, parent overlap, instance overlap, restriction patterns, and graph neighborhood. Auto-applies high-confidence matches above threshold.")]
diff --git a/src/sqlsource.rs b/src/sqlsource.rs
new file mode 100644
index 00000000..34eba219
--- /dev/null
+++ b/src/sqlsource.rs
@@ -0,0 +1,337 @@
+//! Unified SQL data source abstraction.
+//!
+//! Provides a single entry point for the data pipeline to talk to multiple SQL
+//! backbones. A connection string is dispatched to the matching driver based
+//! on its scheme/prefix:
+//!
+//! | Prefix | Driver | Feature flag |
+//! | ---------------------------------------- | ------------ | ------------ |
+//! | `postgres://` / `postgresql://` | PostgreSQL | `postgres` |
+//! | `duckdb://` / `duckdb:` / `:memory:` | DuckDB | `duckdb` |
+//! | `*.duckdb` / `*.ddb` (file path) | DuckDB | `duckdb` |
+//!
+//! The abstraction has two responsibilities:
+//!
+//! 1. **Schema introspection** — return [`crate::schema::TableInfo`] entries
+//! so the OWL generator can build classes, datatype/object properties,
+//! and cardinality restrictions from a relational schema. This powers
+//! `onto_import_schema` / `import-schema`.
+//!
+//! 2. **Row extraction via SQL query** — run a user-supplied SELECT and
+//! return rows as `Vec<HashMap<String,String>>`, exactly the shape the
+//! existing [`crate::ingest::DataIngester`] returns. This powers
+//! `onto_sql_ingest` / `sql-ingest` and lets the rest of the pipeline
+//! (mapping → N-Triples → SHACL → reason) stay unchanged.
+//!
+//! DuckDB is intentionally placed alongside Postgres rather than used as a
+//! SPARQL parser. It is a *data integration backbone*: DuckDB's extensions
+//! (httpfs, parquet, csv, json, postgres_scanner, sqlite_scanner, iceberg,
+//! delta, …) let one SQL query federate over remote files, object stores,
+//! and other databases — all of which then flow into RDF through the same
+//! mapping layer used for CSV/Parquet/XLSX inputs today.
+
+use anyhow::{anyhow, Result};
+use std::collections::HashMap;
+
+use crate::schema::TableInfo;
+
+/// Recognised SQL backbone drivers.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum SqlDriver {
+ Postgres,
+ DuckDb,
+}
+
+impl SqlDriver {
+ pub fn as_str(&self) -> &'static str {
+ match self {
+ SqlDriver::Postgres => "postgres",
+ SqlDriver::DuckDb => "duckdb",
+ }
+ }
+}
+
+/// Detect which SQL driver should handle a given connection string.
+///
+/// Recognised forms:
+/// * `postgres://…` / `postgresql://…` → Postgres
+/// * `duckdb://…` / `duckdb:…` → DuckDB
+/// * `:memory:` → DuckDB (in-memory)
+/// * `*.duckdb`, `*.ddb` file path → DuckDB
+pub fn detect_driver(connection: &str) -> Result<SqlDriver> {
+ let trimmed = connection.trim();
+ if trimmed.is_empty() {
+ return Err(anyhow!("empty connection string"));
+ }
+ let lower = trimmed.to_ascii_lowercase();
+ if lower.starts_with("postgres://") || lower.starts_with("postgresql://") {
+ return Ok(SqlDriver::Postgres);
+ }
+ if lower.starts_with("duckdb://") || lower.starts_with("duckdb:") || trimmed == ":memory:" {
+ return Ok(SqlDriver::DuckDb);
+ }
+ if lower.ends_with(".duckdb") || lower.ends_with(".ddb") {
+ return Ok(SqlDriver::DuckDb);
+ }
+ Err(anyhow!(
+ "unrecognised SQL connection string '{}': expected one of postgres://, postgresql://, duckdb://, :memory:, or a *.duckdb file path",
+ trimmed
+ ))
+}
+
+/// Strip the `duckdb:` / `duckdb://` prefix. Returns `:memory:` unchanged and
+/// preserves bare file paths. The remaining string is what the duckdb crate
+/// expects (a filesystem path or `:memory:`).
+pub fn duckdb_target(connection: &str) -> String {
+ let trimmed = connection.trim();
+ if let Some(rest) = trimmed.strip_prefix("duckdb://") {
+ if rest.is_empty() {
+ return ":memory:".to_string();
+ }
+ return rest.to_string();
+ }
+ if let Some(rest) = trimmed.strip_prefix("duckdb:") {
+ if rest.is_empty() {
+ return ":memory:".to_string();
+ }
+ return rest.to_string();
+ }
+ trimmed.to_string()
+}
+
+/// Run a SELECT query against the SQL backbone and return rows as
+/// `Vec<HashMap<String,String>>` (the same shape as
+/// [`crate::ingest::DataIngester::parse_file`]).
+///
+/// Compatible with [`crate::mapping::MappingConfig::rows_to_ntriples`].
+pub async fn query_rows(connection: &str, sql: &str) -> Result<Vec<HashMap<String, String>>> {
+ match detect_driver(connection)? {
+ SqlDriver::Postgres => query_postgres(connection, sql).await,
+ SqlDriver::DuckDb => query_duckdb(connection, sql).await,
+ }
+}
+
+/// Introspect tables/columns/foreign keys from the SQL backbone.
+///
+/// Used by `onto_import_schema` / `import-schema` to build OWL from a
+/// relational schema. Both Postgres and DuckDB expose the SQL-standard
+/// `information_schema.*` views that the introspectors rely on.
+pub async fn introspect_tables(connection: &str) -> Result<Vec<TableInfo>> {
+ match detect_driver(connection)? {
+ SqlDriver::Postgres => {
+ #[cfg(feature = "postgres")]
+ {
+ crate::schema::SchemaIntrospector::introspect_postgres(connection).await
+ }
+ #[cfg(not(feature = "postgres"))]
+ {
+ let _ = connection;
+ Err(anyhow!(
+ "Postgres connection requested but the 'postgres' feature was not compiled in"
+ ))
+ }
+ }
+ SqlDriver::DuckDb => {
+ #[cfg(feature = "duckdb")]
+ {
+ crate::schema::SchemaIntrospector::introspect_duckdb(&duckdb_target(connection))
+ }
+ #[cfg(not(feature = "duckdb"))]
+ {
+ let _ = connection;
+ Err(anyhow!(
+ "DuckDB connection requested but the 'duckdb' feature was not compiled in"
+ ))
+ }
+ }
+ }
+}
+
+// ─── Postgres ────────────────────────────────────────────────────────────────
+
+#[cfg(feature = "postgres")]
+async fn query_postgres(connection: &str, sql: &str) -> Result<Vec<HashMap<String, String>>> {
+ use sqlx::postgres::PgPoolOptions;
+ use sqlx::Column;
+ use sqlx::Row;
+ use sqlx::TypeInfo;
+
+ let pool = PgPoolOptions::new()
+ .max_connections(1)
+ .connect(connection)
+ .await?;
+
+ let pg_rows = sqlx::query(sql).fetch_all(&pool).await?;
+ let mut rows = Vec::with_capacity(pg_rows.len());
+ for row in &pg_rows {
+ let mut map = HashMap::new();
+ for (i, col) in row.columns().iter().enumerate() {
+ let name = col.name().to_string();
+ let value = pg_value_to_string(row, i, col.type_info().name());
+ map.insert(name, value);
+ }
+ rows.push(map);
+ }
+ pool.close().await;
+ Ok(rows)
+}
+
+#[cfg(not(feature = "postgres"))]
+async fn query_postgres(_connection: &str, _sql: &str) -> Result<Vec<HashMap<String, String>>> {
+ Err(anyhow!(
+ "Postgres connection requested but the 'postgres' feature was not compiled in"
+ ))
+}
+
+#[cfg(feature = "postgres")]
+fn pg_value_to_string(row: &sqlx::postgres::PgRow, idx: usize, type_name: &str) -> String {
+ use sqlx::Row;
+ // Try common types in order; fall back to NULL → "" or a debug stringification.
+ let upper = type_name.to_ascii_uppercase();
+ macro_rules! try_get {
+ ($t:ty) => {
+ if let Ok(v) = row.try_get::<Option<$t>, _>(idx) {
+ return v.map(|x| x.to_string()).unwrap_or_default();
+ }
+ };
+ }
+ match upper.as_str() {
+ "BOOL" => try_get!(bool),
+ "INT2" => try_get!(i16),
+ "INT4" => try_get!(i32),
+ "INT8" => try_get!(i64),
+ "FLOAT4" => try_get!(f32),
+ "FLOAT8" => try_get!(f64),
+ "NUMERIC" => {
+ // sqlx::types::BigDecimal isn't enabled — fall through to string.
+ }
+ "TEXT" | "VARCHAR" | "BPCHAR" | "NAME" | "CITEXT" | "UUID" => try_get!(String),
+ "DATE" | "TIMESTAMP" | "TIMESTAMPTZ" | "TIME" | "TIMETZ" => try_get!(String),
+ "JSON" | "JSONB" => {
+ if let Ok(v) = row.try_get::<Option<serde_json::Value>, _>(idx) {
+ return v.map(|x| x.to_string()).unwrap_or_default();
+ }
+ }
+ _ => {}
+ }
+ // Generic last-resort: ask for a String.
+ if let Ok(v) = row.try_get::<Option<String>, _>(idx) {
+ return v.unwrap_or_default();
+ }
+ String::new()
+}
+
+// ─── DuckDB ──────────────────────────────────────────────────────────────────
+
+#[cfg(feature = "duckdb")]
+async fn query_duckdb(connection: &str, sql: &str) -> Result<Vec<HashMap<String, String>>> {
+ let target = duckdb_target(connection);
+ let sql = sql.to_string();
+ tokio::task::spawn_blocking(move || query_duckdb_blocking(&target, &sql))
+ .await
+ .map_err(|e| anyhow!("duckdb worker panicked: {e}"))?
+}
+
+#[cfg(feature = "duckdb")]
+fn query_duckdb_blocking(target: &str, sql: &str) -> Result<Vec<HashMap<String, String>>> {
+ use duckdb::types::ValueRef;
+ use duckdb::Connection;
+
+ let conn = if target == ":memory:" {
+ Connection::open_in_memory()?
+ } else {
+ Connection::open(target)?
+ };
+
+ let mut stmt = conn.prepare(sql)?;
+ let mut rows = stmt.query([])?;
+
+ // Column names are only available after query() has been called.
+ let column_names: Vec<String> = match rows.as_ref() {
+ Some(r) => r.column_names().iter().map(|s| s.to_string()).collect(),
+ None => Vec::new(),
+ };
+
+ let mut out = Vec::new();
+ while let Some(row) = rows.next()? {
+ let mut map = HashMap::new();
+ for (i, name) in column_names.iter().enumerate() {
+ let value = match row.get_ref(i)? {
+ ValueRef::Null => String::new(),
+ ValueRef::Boolean(b) => b.to_string(),
+ ValueRef::TinyInt(v) => v.to_string(),
+ ValueRef::SmallInt(v) => v.to_string(),
+ ValueRef::Int(v) => v.to_string(),
+ ValueRef::BigInt(v) => v.to_string(),
+ ValueRef::HugeInt(v) => v.to_string(),
+ ValueRef::UTinyInt(v) => v.to_string(),
+ ValueRef::USmallInt(v) => v.to_string(),
+ ValueRef::UInt(v) => v.to_string(),
+ ValueRef::UBigInt(v) => v.to_string(),
+ ValueRef::Float(v) => v.to_string(),
+ ValueRef::Double(v) => v.to_string(),
+ ValueRef::Decimal(v) => v.to_string(),
+ ValueRef::Text(bytes) => String::from_utf8_lossy(bytes).to_string(),
+ ValueRef::Blob(bytes) => format!("0x{}", hex_encode(bytes)),
+ other => format!("{other:?}"),
+ };
+ map.insert(name.clone(), value);
+ }
+ out.push(map);
+ }
+ Ok(out)
+}
+
+#[cfg(feature = "duckdb")]
+fn hex_encode(bytes: &[u8]) -> String {
+ let mut out = String::with_capacity(bytes.len() * 2);
+ for b in bytes {
+ out.push_str(&format!("{b:02x}"));
+ }
+ out
+}
+
+#[cfg(not(feature = "duckdb"))]
+async fn query_duckdb(_connection: &str, _sql: &str) -> Result<Vec<HashMap<String, String>>> {
+ Err(anyhow!(
+ "DuckDB connection requested but the 'duckdb' feature was not compiled in"
+ ))
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn detect_driver_postgres() {
+ assert_eq!(detect_driver("postgres://u:p@h/d").unwrap(), SqlDriver::Postgres);
+ assert_eq!(detect_driver("postgresql://u@h/d").unwrap(), SqlDriver::Postgres);
+ assert_eq!(detect_driver("POSTGRES://U@H/D").unwrap(), SqlDriver::Postgres);
+ }
+
+ #[test]
+ fn detect_driver_duckdb() {
+ assert_eq!(detect_driver("duckdb:///tmp/x.db").unwrap(), SqlDriver::DuckDb);
+ assert_eq!(detect_driver("duckdb:/tmp/x.db").unwrap(), SqlDriver::DuckDb);
+ assert_eq!(detect_driver(":memory:").unwrap(), SqlDriver::DuckDb);
+ assert_eq!(detect_driver("/data/warehouse.duckdb").unwrap(), SqlDriver::DuckDb);
+ assert_eq!(detect_driver("./shop.ddb").unwrap(), SqlDriver::DuckDb);
+ }
+
+ #[test]
+ fn detect_driver_rejects_unknown() {
+ assert!(detect_driver("").is_err());
+ assert!(detect_driver("mysql://x").is_err());
+ assert!(detect_driver("/data/file.csv").is_err());
+ }
+
+ #[test]
+ fn duckdb_target_strips_prefix() {
+ assert_eq!(duckdb_target("duckdb:///tmp/x.db"), "/tmp/x.db");
+ assert_eq!(duckdb_target("duckdb:/tmp/x.db"), "/tmp/x.db");
+ assert_eq!(duckdb_target("duckdb://"), ":memory:");
+ assert_eq!(duckdb_target("duckdb:"), ":memory:");
+ assert_eq!(duckdb_target(":memory:"), ":memory:");
+ assert_eq!(duckdb_target("/data/warehouse.duckdb"), "/data/warehouse.duckdb");
+ }
+}
diff --git a/src/toolfilter.rs b/src/toolfilter.rs
index 86533e65..ffd62261 100644
--- a/src/toolfilter.rs
+++ b/src/toolfilter.rs
@@ -159,6 +159,7 @@ pub fn expand_group(name: &str) -> &'static [&'static str] {
"onto_version",
"onto_rollback",
"onto_ingest",
+ "onto_sql_ingest",
"onto_map",
"onto_shacl",
"onto_reason",
@@ -195,6 +196,11 @@ pub fn expand_group(name: &str) -> &'static [&'static str] {
"onto_search",
"onto_similarity",
],
+ // SQL data backbone tools (PostgreSQL / DuckDB).
+ "sql" => &[
+ "onto_import_schema",
+ "onto_sql_ingest",
+ ],
_ => &[],
}
}
diff --git a/tests/duckdb_test.rs b/tests/duckdb_test.rs
new file mode 100644
index 00000000..8704a17b
--- /dev/null
+++ b/tests/duckdb_test.rs
@@ -0,0 +1,132 @@
+#![cfg(feature = "duckdb")]
+//! Integration tests for the DuckDB SQL backbone.
+//!
+//! These tests cover the two integration points the data pipeline exposes for
+//! DuckDB: schema introspection (`onto_import_schema` / `import-schema`) and
+//! row extraction via SQL query (`onto_sql_ingest` / `sql-ingest`).
+
+use open_ontologies::schema::SchemaIntrospector;
+use open_ontologies::sqlsource::{self, SqlDriver};
+use std::collections::HashMap;
+
+fn rt() -> tokio::runtime::Runtime {
+ tokio::runtime::Runtime::new().unwrap()
+}
+
+fn seed_inmemory_db() -> duckdb::Connection {
+ // Note: each Connection::open_in_memory() call creates a *separate*
+ // in-memory database, so the helper used by tests creates a file-backed
+ // DuckDB in a temp dir so the introspector connecting separately can see
+ // the same data.
+ duckdb::Connection::open_in_memory().unwrap()
+}
+
+#[test]
+fn detect_driver_classifies_duckdb_strings() {
+ assert_eq!(sqlsource::detect_driver("duckdb:///tmp/x.db").unwrap(), SqlDriver::DuckDb);
+ assert_eq!(sqlsource::detect_driver(":memory:").unwrap(), SqlDriver::DuckDb);
+ assert_eq!(sqlsource::detect_driver("/data/foo.duckdb").unwrap(), SqlDriver::DuckDb);
+}
+
+#[test]
+fn introspect_duckdb_extracts_tables_and_constraints() {
+ let tmp = tempfile::tempdir().unwrap();
+ let path = tmp.path().join("schema_test.duckdb");
+ let path_str = path.to_string_lossy().to_string();
+
+ {
+ let conn = duckdb::Connection::open(&path).unwrap();
+ conn.execute_batch(
+ r#"
+ CREATE TABLE customer (
+ id INTEGER PRIMARY KEY,
+ name VARCHAR NOT NULL,
+ email VARCHAR
+ );
+ CREATE TABLE orders (
+ id INTEGER PRIMARY KEY,
+ customer_id INTEGER NOT NULL REFERENCES customer(id),
+ total DECIMAL(10,2) NOT NULL
+ );
+ "#,
+ )
+ .unwrap();
+ }
+
+ let tables = SchemaIntrospector::introspect_duckdb(&path_str).unwrap();
+ assert_eq!(tables.len(), 2);
+
+ let customer = tables.iter().find(|t| t.name == "customer").unwrap();
+ let id_col = customer.columns.iter().find(|c| c.name == "id").unwrap();
+ assert!(id_col.is_primary_key, "id should be PK");
+ assert!(!id_col.is_nullable, "PK column should be NOT NULL");
+
+ let orders = tables.iter().find(|t| t.name == "orders").unwrap();
+ let fk = orders
+ .foreign_keys
+ .iter()
+ .find(|fk| fk.column == "customer_id")
+ .expect("orders.customer_id FK should be detected");
+ assert_eq!(fk.parent_table, "customer");
+ assert_eq!(fk.parent_column, "id");
+
+ // Generated Turtle should reflect the FK as an ObjectProperty pointing to
+ // the parent class.
+ let turtle = SchemaIntrospector::generate_turtle(&tables, "http://example.org/db/");
+ assert!(turtle.contains("db:Customer a owl:Class"));
+ assert!(turtle.contains("db:Orders a owl:Class"));
+ assert!(turtle.contains("db:orders_customer_id a owl:ObjectProperty"));
+ assert!(turtle.contains("rdfs:range db:Customer"));
+}
+
+#[test]
+fn query_rows_returns_tabular_data_from_duckdb() {
+ let tmp = tempfile::tempdir().unwrap();
+ let path = tmp.path().join("query_test.duckdb");
+ let path_str = path.to_string_lossy().to_string();
+
+ {
+ let conn = duckdb::Connection::open(&path).unwrap();
+ conn.execute_batch(
+ r#"
+ CREATE TABLE pizza (name VARCHAR, base VARCHAR, price DECIMAL(5,2));
+ INSERT INTO pizza VALUES
+ ('Margherita', 'Thin', 9.50),
+ ('Pepperoni', 'Thin', 11.00);
+ "#,
+ )
+ .unwrap();
+ }
+
+ let rows = rt()
+ .block_on(sqlsource::query_rows(
+ &format!("duckdb://{}", path_str),
+ "SELECT name, base, price FROM pizza ORDER BY name",
+ ))
+ .expect("query_rows succeeds");
+
+ assert_eq!(rows.len(), 2);
+ assert_eq!(rows[0].get("name").map(String::as_str), Some("Margherita"));
+ assert_eq!(rows[0].get("base").map(String::as_str), Some("Thin"));
+ assert!(rows[0].get("price").map(String::as_str).unwrap().starts_with("9.5"));
+ assert_eq!(rows[1].get("name").map(String::as_str), Some("Pepperoni"));
+}
+
+#[test]
+fn query_rows_handles_in_memory_with_seed_query() {
+ // Validate that an in-memory DuckDB session works end-to-end: SELECT a
+ // hand-crafted constant table. This is the lightweight smoke test that
+ // does not require any temp file.
+ let _ = seed_inmemory_db();
+ let rows = rt()
+ .block_on(sqlsource::query_rows(
+ ":memory:",
+ "SELECT * FROM (VALUES (1, 'a'), (2, 'b')) t(id, label)",
+ ))
+ .expect("in-memory query succeeds");
+ assert_eq!(rows.len(), 2);
+ let mut sorted: Vec<&HashMap<String, String>> = rows.iter().collect();
+ sorted.sort_by_key(|r| r.get("id").cloned().unwrap_or_default());
+ assert_eq!(sorted[0].get("id").map(String::as_str), Some("1"));
+ assert_eq!(sorted[0].get("label").map(String::as_str), Some("a"));
+}
diff --git a/tests/sqlsource_test.rs b/tests/sqlsource_test.rs
new file mode 100644
index 00000000..50f51fdb
--- /dev/null
+++ b/tests/sqlsource_test.rs
@@ -0,0 +1,37 @@
+//! Tests for `sqlsource::detect_driver` and `duckdb_target` that work even
+//! without any SQL feature flag enabled. These exercise the connection-string
+//! parsing logic that the data-pipeline docs rely on.
+
+use open_ontologies::sqlsource::{detect_driver, duckdb_target, SqlDriver};
+
+#[test]
+fn detects_postgres() {
+ assert_eq!(detect_driver("postgres://u:p@h/db").unwrap(), SqlDriver::Postgres);
+ assert_eq!(detect_driver("postgresql://u@h:5432/db").unwrap(), SqlDriver::Postgres);
+}
+
+#[test]
+fn detects_duckdb_variants() {
+ assert_eq!(detect_driver("duckdb:///tmp/x.duckdb").unwrap(), SqlDriver::DuckDb);
+ assert_eq!(detect_driver("duckdb:/tmp/x.duckdb").unwrap(), SqlDriver::DuckDb);
+ assert_eq!(detect_driver(":memory:").unwrap(), SqlDriver::DuckDb);
+ assert_eq!(detect_driver("/var/data/warehouse.duckdb").unwrap(), SqlDriver::DuckDb);
+ assert_eq!(detect_driver("./local.ddb").unwrap(), SqlDriver::DuckDb);
+}
+
+#[test]
+fn rejects_unsupported_drivers() {
+ assert!(detect_driver("").is_err());
+ assert!(detect_driver("mysql://x").is_err());
+ assert!(detect_driver("sqlite:foo.db").is_err());
+ assert!(detect_driver("/data/file.csv").is_err());
+}
+
+#[test]
+fn duckdb_target_normalises_prefixes() {
+ assert_eq!(duckdb_target("duckdb:///tmp/x.db"), "/tmp/x.db");
+ assert_eq!(duckdb_target("duckdb:/tmp/x.db"), "/tmp/x.db");
+ assert_eq!(duckdb_target("duckdb://"), ":memory:");
+ assert_eq!(duckdb_target(":memory:"), ":memory:");
+ assert_eq!(duckdb_target("/data/file.duckdb"), "/data/file.duckdb");
+}