Repository navigation
fluree ontology from tables (CSV, XLSX, SQL DDL) and fluree catalog from rows - #2210
Conversation
`fluree ontology from` now reads tables as well as RDF: a CSV header (.csv/.tsv), a workbook's sheets (.xlsx, through fluree-doc-xlsx) or SQL DDL (.sql, through sqlparser, trying generic, PostgreSQL, MySQL and Snowflake dialects). Every source fills one table model, and one emitter applies the rules that measurably help an extraction model: classes and properties labelled in words (singular class labels, `employer_id` -> "employer"), IRIs minted from the labels, descriptions copied with synonyms appended, foreign keys as relations, enumerated columns (CHECK ... IN, enum types, or few repeated values in a CSV) as a class with a catalog record per value, and primary keys left out. --base names the namespace, --enum-max tunes enumeration, --catalog-out writes the records apart. `fluree catalog from <CSV|XLSX> --class ... --label ...` writes SKOS records: prefLabel, altLabel from alias columns (emails to hiddenLabel), hiddenLabel from code columns, a definition from a column or written from others, IRIs from an id column. --ontology finds the class in an ontology. It reports the catalog's size against one extraction window, since the whole catalog is repeated in every window. docs/cli/catalog.md is new; docs/cli/ontology.md covers the table sources. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_016CjYmQVZNYkCgGd38GYUyX
bplatz
left a comment
There was a problem hiding this comment.
Approving. Feeding every source into one table model with one emitter is a good shape, and the DDL example in the docs reproduces exactly. Please go through the inline comments before merging. The CSV panic, the catalog from folding, the MySQL keys and the pg_dump constraints give a crash or wrong output on inputs people will actually have.
One theme across the converters, here and in the PRs stacked on this one: most of what I found is either two distinct source names merged into one IRI without a word (slug folding, a shared mint key, a foreign key taking its target's label) or content dropped with no count on stderr. One rule in the emitter would close most of these at once, rather than a fix in each converter: suffix the IRI on a clash, never merge silently, and count every drop in the notes.
None of the stacked PRs (#2210 through #2216) has had a CI run yet, because a PR based on another feature branch only gets the Release plan job. The CLI tests in this stack haven't run in CI.
| } | ||
|
|
||
| fn is_date_time(v: &str) -> bool { | ||
| v.len() > 10 && is_date(&v[..10]) && matches!(v.as_bytes()[10], b'T' | b' ') |
There was a problem hiding this comment.
&v[..10] slices by byte, so a value whose 10th byte falls inside a multi-byte character panics. A CSV with city = Kraków Główny (or any CJK text) crashes ontology from with "end byte index 10 is not a char boundary"; any text column can reach this. v.get(..10).is_some_and(is_date) avoids it.
There was a problem hiding this comment.
Good catch, thanks. Fixed in e98dfe8: is_date_time now takes v.get(..10) and reads byte 10 with get(10), so a multi-byte character there can't panic. multi_byte_text_and_upper_case_ids runs Kraków Główny and a CJK value through it.
| let key = id.map(cell).filter(|v| !v.is_empty()).unwrap_or(name); | ||
| let iri = format!("{}{}", options.base, slug(key)); | ||
| let fresh = !records.contains_key(&iri); | ||
| if !fresh { | ||
| out.merged += 1; | ||
| } | ||
| let record = records.entry(iri).or_default(); |
There was a problem hiding this comment.
Rows are folded by slug(key), which lowercases and drops punctuation, so distinct ids merge into one record:
- Salesforce-style ids
001A000001abcDE(Acme) and001A000001ABCde(Globex) become one record with prefLabel "Acme" and altLabel "Globex". A Globex mention would then link to Acme. - Without
--id,C,C++andC#fold into one record, and all-punctuation names all land on…/value.
The stderr summary then says these rows had "the same id". Folding on the exact key, and suffixing the IRI when two different keys slug alike, would keep them apart.
There was a problem hiding this comment.
Agreed, that was a real merge of two different records. Fixed in e98dfe8: rows fold only on the exact key now, and a second key that slugs like an earlier one gets its own IRI with a -2 suffix (the summary counts those separately from the true folds). keys_that_slug_alike_stay_apart covers both the Salesforce-style ids and C/C++/C#/???/!!! without --id.
| match constraint { | ||
| TableConstraint::PrimaryKey(pk) => { | ||
| for c in &pk.columns { | ||
| t.primary_key.push(unquote(&c.column.expr.to_string())); |
There was a problem hiding this comment.
c.column.expr.to_string() keeps MySQL's backticks (unquote strips only ' and "). So PRIMARY KEY (`id`) is stored as `id` and never matches the column: every mysqldump table keeps an id property, and keys_left_out is 0. Taking the identifier's .value, as the foreign-key branch below does, fixes it. mysql_enum_and_inline_comment uses exactly this input but doesn't assert the key.
There was a problem hiding this comment.
Yep, fixed in e98dfe8: key columns are read from the identifier itself (key_column), so backticked and double-quoted names match. I also added the missing assertion to mysql_enum_and_inline_comment, plus a dedicated mysql_backticked_primary_key test.
| for s in statements { | ||
| if let Statement::CreateTable(create) = s { | ||
| tables.push(table(create, &enums)); | ||
| } | ||
| } |
There was a problem hiding this comment.
Only constraints written inside CREATE TABLE are read. pg_dump writes keys and foreign keys as ALTER TABLE ONLY … ADD CONSTRAINT … PRIMARY KEY / FOREIGN KEY, and its enum checks as ((status)::text = ANY (ARRAY[…])). A pg_dump schema therefore comes out with:
idas a property on every class;employer_idas anxsd:integerinstead of the relation;statusnot enumerated.
pg_dump is probably the most common DDL people will have, so I'd handle Statement::AlterTable with AddConstraint, and the = ANY (ARRAY[…]) form. At the least, the docs should say that ALTER TABLE isn't read: "Foreign keys are read from REFERENCES and FOREIGN KEY" reads as if it were.
There was a problem hiding this comment.
Agreed that pg_dump is the common case. Fixed in e98dfe8: ALTER TABLE ... ADD CONSTRAINT is read for primary keys, foreign keys and checks (through the same apply_constraint as CREATE TABLE), and the ((col)::text = ANY ((ARRAY[...])::text[])) check form is read as an enumeration. pg_dump_constraints_after_the_tables is a trimmed pg_dump; the docs now say ALTER TABLE is read.
| let (statements, skipped) = statements.unwrap_or_else(|| { | ||
| let mut out = Vec::new(); | ||
| let mut skipped = 0; | ||
| for piece in sql.split(';').filter(|p| !p.trim().is_empty()) { |
There was a problem hiding this comment.
When any statement fails in every dialect (mysqldump's DELIMITER, some function bodies), this fallback splits on every ;, including those inside string literals. A table with COMMENT 'open; or closed' is dropped entirely, and COMMENT ON TABLE b IS 'Notes; misc' is lost; the only trace is a larger "statements skipped" count. Splitting on the tokenizer's SemiColon tokens would keep strings intact.
There was a problem hiding this comment.
Fixed in e98dfe8: the fallback now splits on the tokenizer's SemiColon tokens, so a semicolon inside a string or quoted name no longer cuts a statement. a_semicolon_in_a_string_doesnt_split_a_statement uses DELIMITER to force the fallback, with COMMENT 'open; or closed' and COMMENT ON TABLE b IS 'Notes; misc'.
| /// "employer". `None` when the name doesn't end in "id". | ||
| fn key_stem(name: &str) -> Option<String> { | ||
| let words = name_words(name)?; | ||
| let stem = words.strip_suffix(" id")?; |
There was a problem hiding this comment.
name_words("CustomerID") is "customer ID", so the case-sensitive strip_suffix(" id") misses it. In a CSV, OrderID/CustomerID become neither a key nor a foreign key (OrderID becomes an integer property). The same check in property_label (convert/mod.rs:102) labels a DDL foreign key CustomerID as "customer ID" (crm:customerID). Comparing the suffix case-insensitively fixes both.
There was a problem hiding this comment.
Good catch, fixed in e98dfe8: there's now a case-insensitive strip_word_suffix, used by the CSV key detection and by property_label, so OrderID/CustomerID are keys and foreign keys again and a DDL CustomerID labels as "customer".
| Some(stem) => { | ||
| let wanted = class_label(&stem); | ||
| column.references = Some( | ||
| labels | ||
| .iter() | ||
| .find(|(label, _)| *label == wanted) | ||
| .map_or(stem, |(_, name)| name.clone()), | ||
| ); |
There was a problem hiding this comment.
I know this is deliberate, but I think it does more harm than good. A _id column whose stem names no sheet still becomes a relation, labelled without the suffix and with no range, so tax_id, national_id and session_id come out as "tax", "national" and "session". I'd only make it a relation when the stem resolves to a sheet, and otherwise keep "tax id" as a value property.
There was a problem hiding this comment.
Agreed, I've switched to your rule in e98dfe8: a _id column is a relation only when its stem names another sheet, and otherwise stays a value labelled "tax id" etc.
| fn last(name: &ObjectName) -> String { | ||
| let text = name.to_string(); | ||
| let part = text.rsplit('.').next().unwrap_or(&text); | ||
| part.trim_matches(|c| c == '"' || c == '`' || c == '[' || c == ']') | ||
| .to_string() | ||
| } |
There was a problem hiding this comment.
last() drops the schema, and the emitter keys classes on the bare table name. So crm.users and billing.users become one User class, and their status enums become one class with the records pooled. Either keep the schema in the key (and in the label when two tables collide), or at least note the merge.
There was a problem hiding this comment.
Fixed in e98dfe8: tables are tracked by their qualified name, and when two schemas have a table of the same name, both keep the schema in their name (crm.users → "crm user", billing.users → "billing user"), with a note on stderr. Foreign keys resolve to the qualified table when they name one, else to the one table of that name. Covered by same_table_name_in_two_schemas.
| } else if !column.values.is_empty() { | ||
| let label = | ||
| property_label(&column.name, false).unwrap_or_else(|| column.name.clone()); | ||
| let class_label = if class_of.values().any(|(_, l)| *l == label) { |
There was a problem hiding this comment.
The class label is only qualified when it collides with a table's class. Take two enumerated status columns (orders.status, tickets.status): they give classes Status and Status2 and properties status and status2, all four labelled "status", so the model can't tell them apart. Qualifying with the table name ("order status", "ticket status") when another enumeration already has the label would fix it.
There was a problem hiding this comment.
This is now part of the emitter rule you suggested in the review (e98dfe8): a label another term already has is qualified, with the table's name in front for enumerations, so orders.status and tickets.status give "status" and "ticket status" (classes and properties both), and no two terms share a label. two_names_never_become_one_term covers it.
| e.class(&class_iri, &class_label, text.clone()); | ||
| e.out.enum_classes += 1; | ||
| for value in &column.values { | ||
| let record = format!("{class_iri}/{}", slug(value)); |
There was a problem hiding this comment.
Values that slug alike share one record. CHECK (terms IN ('Net 30','net-30','NET 30!')) gives one record with three skos:prefLabels (SKOS allows one per language), and '???' and '!!!' both become Terms/value, while records still counts 5. Same fix as in catalog from: suffix the IRI on a clash.
There was a problem hiding this comment.
Fixed in e98dfe8 along the same lines: values are de-duplicated exactly, and values that slug alike get suffixed IRIs (net-30, net-30-2), so each record has one prefLabel and records counts what was actually written.
…-tables Brings the HTTP reader wording, seed validation and OWL machinery handling up the stack; the catalog page and table docs take the same wording. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_016CjYmQVZNYkCgGd38GYUyX
…p; DDL, CSV and catalog fixes
Review follow-ups on the tables PR. The shared emitter now follows one
rule: two source names never become one term.
- A property is shared only by columns with the same name (and range) in
different tables. Any other clash gets a suffixed IRI, and a label
another term already has is qualified with the column's full name or the
table's name in front ("ticket status" beside "status"), so two terms
never read the same.
- Enumerated values are de-duplicated exactly; values that slug alike get
records of their own (suffixed IRIs) instead of one record with several
prefLabels.
- Columns left out for having no letters, foreign keys to tables the input
doesn't have, qualified labels and duplicate table names are counted in
notes the CLI prints; a file that yields no classes is an error rather
than an empty ontology with exit 0.
Readers:
- CSV/XLSX: no panic on a multi-byte character at byte 10 (date-time
sniffing sliced by byte); `CustomerID`-style keys are recognised (the
ID suffix compares case-insensitively, also in DDL key labels); a `_id`
column is a relation only when it names another sheet, so `tax_id` stays
"tax id".
- SQL: MySQL's backticked `PRIMARY KEY (`id`)` matches its column; pg_dump's
`ALTER TABLE ... ADD CONSTRAINT` keys, foreign keys and checks are read,
as is its `(col)::text = ANY (ARRAY[...])` enumeration; the per-statement
fallback splits on the tokenizer's semicolons, so `COMMENT 'a; b'` no
longer drops a table; tables of one name in two schemas stay apart,
named with the schema, and references resolve to the qualified table.
- catalog from: rows fold only on an identical id; two ids that slug alike
stay two records (suffixed IRI) and the summary counts them.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_016CjYmQVZNYkCgGd38GYUyX
|
Thanks @bplatz! All ten inline comments are fixed here in e98dfe8, and I replied on each one with its test. On the theme: I agree one rule in the emitter was the right fix, not a patch per converter, so it's now the emitter's rule. IRIs that clash and values that slug alike get suffixes, a label another term already has is qualified, and every drop is counted in the notes on stderr ( On CI, good point, and it's the main reason I'd merge #2208 first: once it lands, this PR retargets to |
Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_016CjYmQVZNYkCgGd38GYUyX
Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_018gr44LtZux3gFaK3fGq4R6
Brings #2247, #2232, #2246, #2248, #2245, #2230, #2205, #2231, #2255, #2219, #2209, #2207, #2190, #2216, #2186, #2215, #2213, #2184, #2210, #2206, #2198, #2187, #2183, #2200, #2193, #2199, #2196 and #2145 into next. Resolutions: - Novelty: main's fact-state trim (a cutoff plus a bounded sweep) and the dictionary's coverage watermark sit on next's graph slots and per-graph OrdMaps. A commit's reification links count toward coverage. Planner stats from segment sums decline under annotations, whose link deltas only the walk counts, and otherwise carry the indexed link counts. - Stats-view identity: the index root's id reaches the snapshot through next's root decoder (`decode` takes the id, as `take_snapshot_metadata` does). `LedgerState::load_record` has a decoding-root form beside `load_decoding_root`. - Transact: #2184's parallel-relationship check runs in next's link cascade, counting the `rdf:reifies` links on the retracted edge that the transaction does not retract itself. Main's bundle `edge_reifiers` is dropped, and `subjects_with_prior_rows` and `enforce_single_target_reifiers` stay deleted. The upsert pre-check takes main's dictionary probe and bounded seek. - Query: geo search resolves the graph's POST tree once at open (pooled graphs keep their filter), an empty manifest when there is none. `branch_or_none` reads the dedicated branch, and the batched joins keep next's pooled lanes. The stats-view key hashes the root id. - Indexer: `apply_dict_novelty` and `compact_forward_streams` take the cycle's compaction budget, so the term dictionary keeps its reserved share. `Prefetched` holds `ContentBytes`. `relocalize_sorted_commit` rewrites next's 20-byte types records. - Disk cache: main's in-flight write registration, with an empty entry still read as crash debris that a write replaces. The process-wide eviction walk stays removed. - Graph import (#2232): fenced CAS and publishes, the seed carries the record's namespace and fence, 32-bit graph ids and next's loaders. An import into a graph of an existing ledger refuses triple terms and edge annotations: the splice merges no triple-term dictionary yet. - Iceberg: `create_iceberg_graph_source` goes with main (a source needs a mapping); the R2RML path keeps next's `model_instance`. - CLI: main's shared import flags without the leaflet flags; `graph import` routes through next's process-wide server routing, and `upload_source_import` serves next's `Destination`. Doc sources read a ledger through the command's open instance. - Tests: sibling ledger ids become distinct names, `genesis_ledger` is awaited, Cypher state dumps include each relationship's `rdf:reifies` link, and the graph-import arena test checks the refusal instead.
Stacked on #2208 (base is
feat/ontology-check, so this diff is just the second commit). This is the "start from what you already have" half of the ontology tools:fluree ontology fromlearns to read tables, and a newfluree catalog fromturns rows into the SKOS records an extraction model links names to.fluree ontology from <FILE>now takes a CSV header (.csv/.tsv), a workbook (.xlsx, one table per sheet, read throughfluree-doc-xlsxwhich is already in the workspace) or SQL DDL (.sql, throughsqlparser, trying the generic dialect and then PostgreSQL, MySQL and Snowflake, and skipping/counting statements none of them can parse). Every source fills one small table model (fluree-db-ontology/src/convert/mod.rs) and one emitter applies the rules, so they're the same whatever the source. The rules are the ones that have measurably mattered for what an extraction model reads:DAMAGE_REPORTS→ "damage report", singular;opened_at→ "opened at"), and IRIs minted from those labels, since the model reads the local name too. A label likeemployer_idfinds a small fraction of the relations "employer" does, so the key suffix goes;employer_id INTEGER REFERENCES companies→crm:employer, rangecrm:Company, "A contact's employer: a company.");CHECK (status IN (...)), MySQLENUM(...), PostgreSQLCREATE TYPE ... AS ENUM, or, in a CSV/workbook, a short text column with at most--enum-maxdistinct values that each repeat);COMMENT ON TABLE|COLUMN, inlineCOMMENT '...', a table'sCOMMENT = '...') with synonyms appended where a source has them;In a CSV/workbook there are no declared keys, so a column named
idor<table singular>_idis the primary key and any other..._id/...Idcolumn is a foreign key, resolved to another sheet when one has that name (People.company_id → Companies). A key to a table the input doesn't have still becomes a relation labelled without the suffix, just with no range, rather than an integer-valued attribute. Datatypes come from DDL types or from the values (integers, decimals, ISO dates/date-times, booleans; a leading-zero number like a ZIP stays text).--basenames the namespace (defaulthttps://example.com/<file name>/, with a stderr nudge to set it),--catalog-outwrites the enumerated values' records to their own file, and the summary on stderr says what was made ("3 classes, 4 properties; 1 enumerated column made a class, with 2 catalog records; 2 primary key columns left out").fluree catalog from <CSV|XLSX> --class <C> --label <COL> [--alt <COL>]... [--code <COL>]... [--definition <COL> | --describe <COLS>] [--id <COL>]writes one record per row:skos:prefLabelfrom the label column,skos:altLabelfrom alias columns (several per cell split on;/|, and email addresses go toskos:hiddenLabelinstead),skos:hiddenLabelfrom code columns (account numbers, tickers), and askos:definitionfrom a column or written from others asindustry: Lab supplies; city: Taipei. IRIs come from--id(or the label), and rows with the same IRI fold into one record with their names pooled.--ontology ontology.ttlresolves--class organizationagainst the ontology by label/local name/prefixed name, so the records are typed with the class the model will actually read (I'd lean on this rather than minting the class under--base, and the stderr says so). Since the whole catalog is repeated in every extraction window, it reports the catalog's size in serialized tokens and warns when it leaves little room for text or doesn't fit a window at all.Things worth a look:
sqlparser = "0.63"is a new dependency (Apache-2.0, released 2026-09-13). I went with it over a hand-rolledCREATE TABLEsubset because the foreign keys, checks and enum types are exactly what the converter needs and they vary a lot by dialect.convert::singularis deliberately simple (common English suffixes pluspeople/children/men/women, and a keep-list likestatus,address,series). It only shapes labels, so a miss reads a little oddly but doesn't break anything.fluree-db-cli/tests/fixtures/ontology/crm.xlsxis a 2 KB generated two-sheet workbook (inline strings, no styles); the test that uses it says what's in it.docs/cli/catalog.mdis new (and indexed), anddocs/cli/ontology.mdgets a "From tables" section with a worked DDL example whose output I pasted from an actual run.Semantic-layer YAML (Snowflake semantic views, then dbt) and the Genie JSON export come next as their own PR, on the same table model.
cargo test -p fluree-db-ontology -p fluree-db-cliandcargo clippy -p fluree-db-ontology -p fluree-db-cli --all-targets --no-depsare clean locally.🤖 Generated with Claude Code
https://claude.ai/code/session_016CjYmQVZNYkCgGd38GYUyX