World's first open-source enterprise world model.
Rust agent-memorybitemporalgraphragknowledge-baseknowledge-graphllmontologypgvectorpostgresqlragrustself-hostedsemantic-searchtemporal-knowledge-graphworld-model
A predicate is named one way (#536)
WaylandYangdd7162498286
diff --git a/crates/utopia-store/src/ontology.rs b/crates/utopia-store/src/ontology.rsindex 8c425d7d..9c5e21f4 100644--- a/crates/utopia-store/src/ontology.rs+++ b/crates/utopia-store/src/ontology.rs@@ -91,6 +91,36 @@ pub async fn relation_type_views(pool: &PgPool, kb_id: Uuid) -> AppResult<Vec<Re.await?)}+/// 谓词的显示名统一成**小驼峰**(见迁移 0042)。+///+/// 类是大驼峰、谓词是小驼峰,这是 RDF/OWL 与 schema.org 的惯例,而且大小写+/// 本身就在说这个词是类还是属性。库里同时存在 `acceptedAnswer`、`access to`、+/// `ApplicableCertificate` 三种写法,在同一列里读起来就是没规矩。+///+/// **只动分隔符与首字母,不碰词内部的大小写**:`productID`、`hasLEI`、+/// `accessibilityAPI` 要原样留着。从 `key` 反推是做不到这一点的——`to_key`+/// 在连续大写之间不插下划线,`product_id` 拼回去只会得到 `productId`。+pub fn lower_camel(label: &str) -> String {+ let mut out = String::with_capacity(label.len());+ let mut start_of_word = false;+ for c in label.trim().chars() {+ if c == ' ' || c == '_' || c == '-' {+ // 连着几个分隔符只算一次,词首标记留着+ start_of_word = !out.is_empty();+ continue;+ }+ if out.is_empty() {+ out.extend(c.to_lowercase());+ } else if start_of_word {+ out.extend(c.to_uppercase());+ start_of_word = false;+ } else {+ out.push(c);+ }+ }+ out+}+fn validate_key(key: &str) -> AppResult<()> {let ok = !key.is_empty()&& key.len() <= 40@@ -387,6 +417,7 @@ pub async fn create_relation_type());}validate_attribute_fields(kind, domains, datatype)?;+ let label = &lower_camel(label);// 新建的行 id 还不存在,指向自己无从谈起——所以 self_id 传 Nonevalidate_property_links(pool, kb_id, None, kind, ax).await?;let is_attr = kind == "attribute";@@ -481,6 +512,8 @@ pub async fn update_relation_type(domains: Option<&[Uuid]>,ranges: Option<&[Uuid]>,) -> AppResult<()> {+ // 改名也归一:不然界面上改一次就能把小驼峰改回 "access to"+ let label = &lower_camel(label);if !matches!(temporal, "state" | "event" | "eternal") {return Err(AppError::Validation("temporal must be state / event / eternal".into(),@@ -1449,7 +1482,10 @@ pub async fn create_relation_types_bulk(validate_key(&r.key)?;}let keys: Vec<&str> = rows.iter().map(|r| r.key.as_str()).collect();- let labels: Vec<&str> = rows.iter().map(|r| r.label.as_str()).collect();+ // 导入来的词表自己就可能不一致(unece.org 里 `brandName` 与+ // `ApplicableCertificate` 并存)——落库前统一,真身留在 `iri` 里+ let camel: Vec<String> = rows.iter().map(|r| lower_camel(&r.label)).collect();+ let labels: Vec<&str> = camel.iter().map(String::as_str).collect();let descs: Vec<&str> = rows.iter().map(|r| r.description.as_str()).collect();let iris: Vec<&str> = rows.iter().map(|r| r.iri.as_str()).collect();let kinds: Vec<&str> = rows.iter().map(|r| r.kind).collect();@@ -1925,3 +1961,56 @@ pub async fn link_property_axioms_bulk(let sub = run("sub_property_of", sub_property).await?;Ok((inv, sub))}++#[cfg(test)]+mod name_shape_tests {+ use super::lower_camel;++ #[test]+ fn separators_become_camel_humps() {+ assert_eq!(lower_camel("access to"), "accessTo");+ assert_eq!(lower_camel("collaborated with"), "collaboratedWith");+ assert_eq!(lower_camel("works_for"), "worksFor");+ assert_eq!(lower_camel("date-applicability"), "dateApplicability");+ // 连着几个分隔符只算一次+ assert_eq!(lower_camel("called for"), "calledFor");+ assert_eq!(lower_camel(" start date "), "startDate");+ }++ #[test]+ fn only_the_first_letter_is_lowered() {+ assert_eq!(+ lower_camel("ApplicableCertificate"),+ "applicableCertificate"+ );+ assert_eq!(lower_camel("EffectiveEndDateTime"), "effectiveEndDateTime");+ }++ /// **这条是这个函数存在的理由之一**:从 `key` 反推做不到,+ /// `product_id` 拼回去只会得到 `productId`+ #[test]+ fn acronyms_are_left_alone() {+ assert_eq!(lower_camel("productID"), "productID");+ assert_eq!(lower_camel("hasLEI"), "hasLEI");+ assert_eq!(lower_camel("accessibilityAPI"), "accessibilityAPI");+ assert_eq!(+ lower_camel("checkoutPageURLTemplate"),+ "checkoutPageURLTemplate"+ );+ }++ #[test]+ fn already_right_is_untouched() {+ for s in ["owns", "acceptedAnswer", "worksFor", "3DModel"] {+ assert_eq!(lower_camel(s), s, "{s} 不该被动");+ }+ }++ #[test]+ fn idempotent() {+ for s in ["access to", "ApplicableCertificate", "productID", "owns"] {+ let once = lower_camel(s);+ assert_eq!(lower_camel(&once), once, "{s} 归一两次结果要一样");+ }+ }+}diff --git a/migrations/0042_a_predicate_is_named_one_way.sql b/migrations/0042_a_predicate_is_named_one_way.sqlnew file mode 100644index 00000000..3e5fe665--- /dev/null+++ b/migrations/0042_a_predicate_is_named_one_way.sql@@ -0,0 +1,47 @@+-- 0042:谓词的显示名只有一种写法——**小驼峰**。+--+-- 一个装了 schema.org 的库里,谓词名同时存在四种形态:`acceptedAnswer`(3819)、+-- `owns`(966)、`ApplicableCertificate`(60)、`access to`(88)。前两种是同一种+-- 写法的长短两例,后两种是另外两种写法。在左栏那一列里挨着排,读起来就是没规矩。+--+-- 定的规矩与 RDF/OWL、schema.org 一致,**而且它带信息量**:+--+-- 类 → 大驼峰 Person / CreativeWork+-- 谓词 → 小驼峰 worksFor / acceptedAnswer / accessTo+--+-- 大小写本身就在说这个词是类还是属性,一眼分得开。库里的类已经是大驼峰+-- (2774 条,另 3 条是 schema.org 自己的 `3DModel`,数字开头,不动),所以这一刀+-- 只动谓词。+--+-- **改 label 是安全的**:它从来不是身份。4875 条谓词带 `iri`,RDF 导出优先用+-- `iri`、没有才从 `key` 铸一个,任何导出路径都不读 label。`key` 也早就归一成+-- snake_case(4996/4999 与 label 只差大小写和分隔符)。+--+-- **只动写错的那些,不从 key 反推**。反推会把 `productID` 变成 `productId`——+-- to_key 在连续大写之间不插下划线,`product_id` 再拼回去就丢了缩写。所以:+-- 含分隔符的 → 拼成小驼峰,每一段除首字母外原样保留+-- 首字母大写的 → 只小写第一个字符+-- 两条都不碰词内部的大小写,`productID`、`hasLEI`、`accessibilityAPI` 原样留着。+-- (落这一刀时查过:含分隔符的 88 条里 0 条带连续大写,大写开头的 60 条里+-- 0 条以连续大写开头,所以这两条规则在现有数据上不会伤到任何缩写。)+--+-- 那 60 条大写开头的全部来自 unece.org,且 label 就是 IRI 末段——不是导入弄错了,+-- 是那份词表自己不一致(同一个命名空间里 `brandName` 又是小驼峰)。这里有意+-- 偏离它的局部名,因为 `iri` 把真身留住了。++UPDATE relation_types+SET label = (+ SELECT string_agg(+ CASE WHEN i = 1+ THEN lower(left(p, 1)) || substr(p, 2)+ ELSE upper(left(p, 1)) || substr(p, 2)+ END, '' ORDER BY i)+ FROM unnest(regexp_split_to_array(btrim(label), '[ _-]+'))+ WITH ORDINALITY AS t(p, i)+ WHERE p <> ''+)+WHERE label ~ '[ _-]';++UPDATE relation_types+SET label = lower(left(label, 1)) || substr(label, 2)+WHERE label ~ '^[A-Z]';diff --git a/web/src/pages/EntityHistory.tsx b/web/src/pages/EntityHistory.tsxindex 1685fc79..8660f593 100644--- a/web/src/pages/EntityHistory.tsx+++ b/web/src/pages/EntityHistory.tsx@@ -8,6 +8,7 @@ import { Link } from "@tanstack/react-router";import { FileText, Merge, PencilLine, Tag, Undo2 } from "lucide-react";import { api, type EntityHistoryEvent } from "../api";import { S } from "../i18n";+import { predicateSentence } from "../predicateText";import { useKbId } from "../kb";import { Pager } from "../ui";@@ -129,7 +130,10 @@ function EventRow({ e }: { e: EntityHistoryEvent }) {<span className="text-small text-ink-2">{e.direction === "in" ? "← " : ""}<span className={e.predicate_label === null ? "italic text-ink-2" : undefined}>- {e.predicate_label ?? S.graph.unknownPredicate}+ {/* 年表也是一行一句话,与事实行同一个拆法 */}+ {e.predicate_label+ ? predicateSentence(e.predicate_label)+ : S.graph.unknownPredicate}</span>{e.direction === "in" ? "" : " →"}</span>{" "}diff --git a/web/src/pages/Graph.tsx b/web/src/pages/Graph.tsxindex 95ef2748..46e4848b 100644--- a/web/src/pages/Graph.tsx+++ b/web/src/pages/Graph.tsx@@ -77,6 +77,7 @@ import {type ProofStep,} from "../api";import { S } from "../i18n";+import { predicateSentence } from "../predicateText";import {Button,CanvasLoading,@@ -2648,7 +2649,11 @@ function EntityPanel({(!f.holds_from || f.holds_from <= nowIso) &&(!f.holds_to || f.holds_to > nowIso);const order = (a: EntityFact, b: EntityFact) =>- (a.predicate_label ?? "\uffff").localeCompare(b.predicate_label ?? "\uffff") ||+ // 按**看到的那个写法**排序,不然 `worksFor` 与 `accessTo` 的先后+ // 跟屏幕上读到的 “works for” / “access to” 对不上+ predicateSentence(a.predicate_label ?? "").localeCompare(+ predicateSentence(b.predicate_label ?? ""),+ ) ||((a.valid_from ?? "9999") < (b.valid_from ?? "9999") ? -1 : 1);const split = (dir: "out" | "in") => {const mine = all.filter((f) => f.direction === dir);@@ -3084,12 +3089,18 @@ function FactRow({title={fact.predicate_label? fact.inferred- ? `${fact.predicate_label} · ${S.graph.inferredPredicate}`- : fact.predicate_label+ ? `${predicateSentence(fact.predicate_label)} · ${S.graph.inferredPredicate}`+ : predicateSentence(fact.predicate_label): undefined}>- {fact.predicate_label ?? S.graph.unknownPredicate}+ {/* **这一行是一句话,所以谓词拆开读**(见 predicateText.ts):+ 库里存的是词表该有的样子 `worksFor`,摆进+ 「Li Si — ? — Meridian Systems」中间时读作 “works for”。+ 管本体的那几个界面照旧显示驼峰,那儿认的是词本身 */}+ {fact.predicate_label+ ? predicateSentence(fact.predicate_label)+ : S.graph.unknownPredicate}</span><span className={ROW_VALUE}>{fact.other_name ?? fmtObjectValue(fact.object_value) ?? "?"}diff --git a/web/src/predicateText.ts b/web/src/predicateText.tsnew file mode 100644index 00000000..5c2431bb--- /dev/null+++ b/web/src/predicateText.ts@@ -0,0 +1,58 @@+/** 谓词在**句子里**怎么读。+ *+ * 库里存的是小驼峰(见迁移 0042):`worksFor`、`acceptedAnswer`、`accessTo`。+ * 那是词表该有的样子——管本体的那几个界面(左栏、表格、画布边标签、详情面板)+ * 就照这个显示,因为在那儿你认的是这个词本身,`acceptedAnswer` 才是能拿去查+ * schema.org 文档的那一个。+ *+ * 可事实行不是词表,**它是一句话**:+ *+ * Li Si — works for — Meridian Systems+ * Li Si — worksFor — Meridian Systems ← 像代码,不像话+ *+ * 所以只有读成句子的地方(事实行、时间线、Chat 的回答)走这里拆一次。+ *+ * **缩写整段留着大写**:`productID` 拆成 “product ID” 而不是 “product id”,+ * `checkoutPageURLTemplate` 拆成 “checkout page URL template”。判断方法是把+ * 连续的大写看作一个词,只有当它后面紧跟一个小写字母时,最后那个大写才是+ * 下一个词的开头。+ */+export function predicateSentence(label: string): string {+ const words: string[] = [];+ let cur = "";+ const chars = [...label.trim()];+ for (let i = 0; i < chars.length; i++) {+ const c = chars[i];+ if (c === " " || c === "_" || c === "-") {+ if (cur) words.push(cur);+ cur = "";+ continue;+ }+ const isUpper = c !== c.toLowerCase() && c === c.toUpperCase();+ if (!isUpper) {+ cur += c;+ continue;+ }+ const prev = chars[i - 1];+ const next = chars[i + 1];+ const prevUpper = prev !== undefined && prev === prev.toUpperCase() && prev !== prev.toLowerCase();+ const nextLower = next !== undefined && next === next.toLowerCase() && next !== next.toUpperCase();+ // 大写起新词的两种情形:前面是小写(worksFor 的 F),+ // 或前面也是大写但后面跟着小写(URLTemplate 的 T)+ if (cur && (!prevUpper || nextLower)) {+ words.push(cur);+ cur = "";+ }+ cur += c;+ }+ if (cur) words.push(cur);+ if (words.length === 0) return label;+ // 首词小写;**整段大写的词原样留着**,那是缩写+ return words+ .map((w, i) => {+ const allCaps = w.length > 1 && w === w.toUpperCase() && w !== w.toLowerCase();+ if (allCaps) return w;+ return i === 0 ? w.charAt(0).toLowerCase() + w.slice(1) : w.toLowerCase();+ })+ .join(" ");+}