Skip to content

World's first open-source enterprise world model.

A class can have more than one parent, which is what real vocabularies do (#71)

WaylandYang1127984af73a
diff --git a/crates/utopia-core/src/models.rs b/crates/utopia-core/src/models.rs
index 1bd5467c..35b35f28 100644
--- a/crates/utopia-core/src/models.rs
+++ b/crates/utopia-core/src/models.rs
@@ -273,7 +273,10 @@ pub struct EntityType {
pub shape: String,
pub builtin: bool,
/// subClassOf 层级(公理推理 P4 点亮,编辑器先维护数据)
- pub parent_id: Option<Uuid>,
+ /// 全部父类(subClassOf 可以有多个:FOAF 的 Person 同时是 Agent 与 SpatialThing)
+ pub parents: Vec<Uuid>,
+ /// 左栏画树时挂在哪一支下。不参与语义,只管展示
+ pub primary_parent: Option<Uuid>,
/// OWL 导入的全局身份。手工建的类为 NULL;重导入按它匹配,不按 key——
/// 上游改一次 rdfs:label 派生的 key 就变了,按 key 匹配会把同一个类当新类建
pub iri: Option<String>,
@@ -298,7 +301,10 @@ pub struct EntityTypeView {
pub color: String,
pub shape: String,
pub builtin: bool,
- pub parent_id: Option<Uuid>,
+ /// 全部父类(subClassOf 可以有多个:FOAF 的 Person 同时是 Agent 与 SpatialThing)
+ pub parents: Vec<Uuid>,
+ /// 左栏画树时挂在哪一支下。不参与语义,只管展示
+ pub primary_parent: Option<Uuid>,
pub description: String,
pub usage: i64,
}
diff --git a/crates/utopia-server/src/api/ontology_routes.rs b/crates/utopia-server/src/api/ontology_routes.rs
index f1cdc143..a7aeafe4 100644
--- a/crates/utopia-server/src/api/ontology_routes.rs
+++ b/crates/utopia-server/src/api/ontology_routes.rs
@@ -79,8 +79,10 @@ pub struct EntityTypeReq {
/// circle | square
#[serde(default)]
pub shape: Option<String>,
+ /// 全部父类,**第一个当主父**(左栏画在那一支下)。
+ /// 界面上写明了这条,所以不额外给一个"选主父"的控件
#[serde(default)]
- pub parent_id: Option<Uuid>,
+ pub parents: Vec<Uuid>,
/// 语义指引,注入抽取 prompt
#[serde(default)]
pub description: Option<String>,
@@ -106,7 +108,7 @@ pub async fn create_entity_type(
req.label.trim(),
req.color.as_deref().unwrap_or("#8ea5bd"),
req.shape.as_deref().unwrap_or("circle"),
- req.parent_id,
+ &req.parents,
req.description.as_deref().unwrap_or("").trim(),
)
.await?;
@@ -138,7 +140,7 @@ pub async fn update_entity_type(
req.label.trim(),
req.color.as_deref().unwrap_or("#8ea5bd"),
req.shape.as_deref().unwrap_or("circle"),
- req.parent_id,
+ &req.parents,
req.description.as_deref().unwrap_or("").trim(),
)
.await?;
diff --git a/crates/utopia-server/src/bootstrap_ontology.rs b/crates/utopia-server/src/bootstrap_ontology.rs
index a9030a94..30269cec 100644
--- a/crates/utopia-server/src/bootstrap_ontology.rs
+++ b/crates/utopia-server/src/bootstrap_ontology.rs
@@ -84,7 +84,8 @@ pub async fn bootstrap_ontology(state: &AppState, kb_id: Uuid) -> anyhow::Result
label,
"#8ea5bd",
"circle",
- None,
+ // 冷启动建的类不挂父:提案里没有层级信息,猜一个父类比不挂更糟
+ &[],
// 描述进抽取提示词,reason 只是给人看的理由——喂错了这个类就成新的倾倒场
str_of(p, "description")
.or_else(|| str_of(p, "reason"))
diff --git a/crates/utopia-server/src/extraction.rs b/crates/utopia-server/src/extraction.rs
index ed61636b..3dbd734f 100644
--- a/crates/utopia-server/src/extraction.rs
+++ b/crates/utopia-server/src/extraction.rs
@@ -4,7 +4,7 @@
use crate::llm_util;
use crate::state::AppState;
-use std::collections::HashMap;
+use std::collections::{HashMap, HashSet};
use utopia_store::graph::FALLBACK_RELATION_KEY;
use uuid::Uuid;
@@ -169,8 +169,10 @@ async fn run(state: &AppState, document_id: Uuid) -> anyhow::Result<()> {
.collect();
// 属性元数据(按 key 查)与提示词清单("person.salary (number, CNY): 月薪")。
// 没定义属性时清单为空,提示词一字不变
- let type_parent: HashMap<Uuid, Option<Uuid>> =
- etypes.iter().map(|t| (t.id, t.parent_id)).collect();
+ let type_parents: HashMap<Uuid, &[Uuid]> = etypes
+ .iter()
+ .map(|t| (t.id, t.parents.as_slice()))
+ .collect();
let attr_meta: HashMap<&str, &utopia_core::models::RelationType> = rtypes
.iter()
.filter(|r| r.kind == "attribute")
@@ -198,14 +200,24 @@ async fn run(state: &AppState, document_id: Uuid) -> anyhow::Result<()> {
})
.collect();
// 属性 domain 允许子类:主语类型沿 parent 链上溯命中 domain 即可
- let type_matches_domain = |mut ty: Uuid, domain: Uuid| -> bool {
- for _ in 0..10 {
- if ty == domain {
+ // 沿 subClassOf 上溯。**广度优先 + 访问集**,不是单链循环:
+ // 一个类可以有多个父(FOAF 的 Person 同时是 Agent 与 SpatialThing),
+ // 而菱形继承会从两条路到达同一个祖先,没有访问集就会重复展开。
+ //
+ // 深度上限换成了访问集:写入侧 set_parents 已经查环,这里再靠"最多走十层"
+ // 兜底既挡不住宽的图,也会悄悄放过深的层级。
+ let type_matches_domain = |ty: Uuid, domain: Uuid| -> bool {
+ let mut seen: HashSet<Uuid> = HashSet::new();
+ let mut queue = vec![ty];
+ while let Some(cur) = queue.pop() {
+ if cur == domain {
return true;
}
- match type_parent.get(&ty).copied().flatten() {
- Some(p) => ty = p,
- None => return false,
+ if !seen.insert(cur) {
+ continue;
+ }
+ if let Some(ps) = type_parents.get(&cur) {
+ queue.extend(ps.iter().copied());
}
}
false
diff --git a/crates/utopia-server/src/owl_import.rs b/crates/utopia-server/src/owl_import.rs
index 4dae442d..cf862501 100644
--- a/crates/utopia-server/src/owl_import.rs
+++ b/crates/utopia-server/src/owl_import.rs
@@ -351,13 +351,21 @@ pub async fn apply(
// 父类第二遍解析:第一遍时父类可能还没建出来
for c in &proj.classes {
- let (Some(&child), Some(parent_iri)) = (id_of.get(&c.iri), c.parents.first()) else {
+ let Some(&child) = id_of.get(&c.iri) else {
continue;
};
- // 多继承暂只投影主父(第一个)——`entity_type_parents` 关联表是下一层。
- // 少投影一个父分支不会静默出错,只是那分支的属性 domain 判定暂时够不到
- if let Some(&parent) = id_of.get(parent_iri) {
- let _ = utopia_store::ontology::set_parent(&state.pool, kb_id, child, parent).await;
+ // **全部父类**,不再只取第一个。FOAF 的 Person 同时是 Agent 与
+ // SpatialThing,丢掉后一支就让 domain 在那支上的属性判定不过。
+ // 指向没被建出来的类的那些父自然落选——少一支比整条不挂强
+ let parents: Vec<Uuid> = c
+ .parents
+ .iter()
+ .filter_map(|iri| id_of.get(iri).copied())
+ .collect();
+ if !parents.is_empty() {
+ // 成环时报错而不是中断整次导入:环是上游词汇表的问题,
+ // 而这一次导入的其余部分仍然值得落地
+ let _ = utopia_store::ontology::set_parents(&state.pool, kb_id, child, &parents).await;
}
}
diff --git a/crates/utopia-store/src/graph.rs b/crates/utopia-store/src/graph.rs
index 27196655..fa32463e 100644
--- a/crates/utopia-store/src/graph.rs
+++ b/crates/utopia-store/src/graph.rs
@@ -388,10 +388,20 @@ pub async fn ensure_default_ontology(pool: &PgPool, kb_id: Uuid, lang: &str) ->
pub async fn entity_types(pool: &PgPool, kb_id: Uuid) -> AppResult<Vec<EntityType>> {
Ok(
- sqlx::query_as("SELECT * FROM entity_types WHERE kb_id = $1 ORDER BY created_at")
- .bind(kb_id)
- .fetch_all(pool)
- .await?,
+ // 又一次 SELECT *:parents 在关联表里,`*` 取不到。
+ // 这是同一个陷阱的第三次——SQL 在字符串里,cargo check 全绿,
+ // 第一个请求才报 no column found
+ sqlx::query_as(
+ "SELECT t.*,
+ ARRAY(SELECT p.parent_id FROM entity_type_parents p
+ WHERE p.child_id = t.id) AS parents,
+ (SELECT p.parent_id FROM entity_type_parents p
+ WHERE p.child_id = t.id AND p.is_primary) AS primary_parent
+ FROM entity_types t WHERE t.kb_id = $1 ORDER BY t.created_at",
+ )
+ .bind(kb_id)
+ .fetch_all(pool)
+ .await?,
)
}
diff --git a/crates/utopia-store/src/ontology.rs b/crates/utopia-store/src/ontology.rs
index 27e40760..789d9ed1 100644
--- a/crates/utopia-store/src/ontology.rs
+++ b/crates/utopia-store/src/ontology.rs
@@ -9,7 +9,11 @@ use uuid::Uuid;
pub async fn entity_type_views(pool: &PgPool, kb_id: Uuid) -> AppResult<Vec<EntityTypeView>> {
Ok(sqlx::query_as(
- "SELECT t.id, t.key, t.label, t.color, t.shape, t.builtin, t.parent_id, t.description,
+ "SELECT t.id, t.key, t.label, t.color, t.shape, t.builtin, t.description,
+ ARRAY(SELECT p.parent_id FROM entity_type_parents p
+ WHERE p.child_id = t.id) AS parents,
+ (SELECT p.parent_id FROM entity_type_parents p
+ WHERE p.child_id = t.id AND p.is_primary) AS primary_parent,
(SELECT count(*) FROM entities e
WHERE e.type_id = t.id AND e.merged_into IS NULL) AS usage
FROM entity_types t WHERE t.kb_id = $1 ORDER BY lower(t.label)",
@@ -103,15 +107,15 @@ pub async fn create_entity_type(
label: &str,
color: &str,
shape: &str,
- parent_id: Option<Uuid>,
+ parents: &[Uuid],
description: &str,
) -> AppResult<Uuid> {
validate_key(key)?;
validate_shape(shape)?;
let id = Uuid::now_v7();
sqlx::query(
- "INSERT INTO entity_types (id, kb_id, key, label, color, shape, parent_id, description)
- VALUES ($1, $2, $3, $4, $5, $6, $7, $8)",
+ "INSERT INTO entity_types (id, kb_id, key, label, color, shape, description)
+ VALUES ($1, $2, $3, $4, $5, $6, $7)",
)
.bind(id)
.bind(kb_id)
@@ -119,7 +123,6 @@ pub async fn create_entity_type(
.bind(label)
.bind(color)
.bind(shape)
- .bind(parent_id)
.bind(description)
.execute(pool)
.await
@@ -129,6 +132,7 @@ pub async fn create_entity_type(
}
_ => AppError::Db(e),
})?;
+ set_parents(pool, kb_id, id, parents).await?;
Ok(id)
}
@@ -140,19 +144,13 @@ pub async fn update_entity_type(
label: &str,
color: &str,
shape: &str,
- parent_id: Option<Uuid>,
+ parents: &[Uuid],
description: &str,
) -> AppResult<()> {
- if parent_id == Some(id) {
- return Err(AppError::invalid(
- "self_parent",
- "A class cannot be its own parent",
- ));
- }
validate_shape(shape)?;
let res = sqlx::query(
- "UPDATE entity_types SET label = $3, color = $4, shape = $5, parent_id = $6,
- description = $7
+ "UPDATE entity_types SET label = $3, color = $4, shape = $5,
+ description = $6
WHERE id = $2 AND kb_id = $1",
)
.bind(kb_id)
@@ -160,13 +158,71 @@ pub async fn update_entity_type(
.bind(label)
.bind(color)
.bind(shape)
- .bind(parent_id)
.bind(description)
.execute(pool)
.await?;
if res.rows_affected() == 0 {
return Err(AppError::NotFound);
}
+ set_parents(pool, kb_id, id, parents).await?;
+ Ok(())
+}
+
+/// 把 `parents` 设成这个类的全部父类,第一个当主父(左栏画在那一支下)。
+///
+/// **先查环再写**。单父时代只需要挡自环,一条链天然不会成环;DAG 里 A→B→A
+/// 完全可能,而 `type_matches_domain` 沿父链上溯,成环就是死循环。
+/// SQL 拦不住这个——外键只挡自环,更长的要应用来查。
+pub async fn set_parents(
+ pool: &PgPool,
+ kb_id: Uuid,
+ child: Uuid,
+ parents: &[Uuid],
+) -> AppResult<()> {
+ if parents.contains(&child) {
+ return Err(AppError::invalid(
+ "self_parent",
+ "A class cannot be its own parent",
+ ));
+ }
+ if !parents.is_empty() {
+ // 候选父类的全部祖先里出现 child,就说明这条边会成环
+ let (cycles,): (i64,) = sqlx::query_as(
+ "WITH RECURSIVE up(id) AS (
+ SELECT unnest($2::uuid[])
+ UNION
+ SELECT p.parent_id FROM entity_type_parents p JOIN up ON p.child_id = up.id
+ )
+ SELECT count(*) FROM up WHERE id = $1",
+ )
+ .bind(child)
+ .bind(parents)
+ .fetch_one(pool)
+ .await?;
+ if cycles > 0 {
+ return Err(AppError::invalid(
+ "parent_cycle",
+ "That parent is already a subclass of this one",
+ ));
+ }
+ }
+ sqlx::query("DELETE FROM entity_type_parents WHERE child_id = $1")
+ .bind(child)
+ .execute(pool)
+ .await?;
+ for (i, p) in parents.iter().enumerate() {
+ sqlx::query(
+ "INSERT INTO entity_type_parents (child_id, parent_id, is_primary)
+ VALUES ($1, $2, $3) ON CONFLICT DO NOTHING",
+ )
+ .bind(child)
+ .bind(p)
+ // 第一个当主父:界面上说明了"画在第一个下面",不再多一个控件
+ .bind(i == 0)
+ .execute(pool)
+ .await?;
+ }
+ let _ = kb_id;
Ok(())
}
@@ -675,19 +731,6 @@ pub async fn update_relation_from_import(
Ok(true)
}
-pub async fn set_parent(pool: &PgPool, kb_id: Uuid, child: Uuid, parent: Uuid) -> AppResult<()> {
- if child == parent {
- return Ok(());
- }
- sqlx::query("UPDATE entity_types SET parent_id = $3 WHERE kb_id = $1 AND id = $2")
- .bind(kb_id)
- .bind(child)
- .bind(parent)
- .execute(pool)
- .await?;
- Ok(())
-}
-
/// 记一次导入。原文已按内容寻址存进 blob,这里只记账。
#[allow(clippy::too_many_arguments)]
pub async fn record_import(
diff --git a/migrations/0036_entity_type_parents.sql b/migrations/0036_entity_type_parents.sql
new file mode 100644
index 00000000..75be7b9f
--- /dev/null
+++ b/migrations/0036_entity_type_parents.sql
@@ -0,0 +1,32 @@
+-- subClassOf 从单列改为关联表:一个类可以有多个父类。
+--
+-- **为什么必须多父**:真实词汇表里这是常态。FOAF 的 Person 同时是 foaf:Agent
+-- 与 geo:SpatialThing——两个方向,不是同一根链上的祖孙。导入此前只投影第一个,
+-- 于是 domain 落在另一支上的属性判定不过:latitude 的 domain 是 SpatialThing,
+-- 而 person 只挂在 agent 下,那条事实抽出来了却被挡掉(报 attr_domain_mismatch)。
+--
+-- **is_primary 不是冗余**。左栏按树展示,一个类只能画在一处,而"画在哪一支下"
+-- 是 subClassOf 集合本身答不出的问题——它是多出来的一条信息,不是同一件事记两遍。
+-- 部分唯一索引保证每个类至多一个主父。
+
+CREATE TABLE entity_type_parents (
+ child_id UUID NOT NULL REFERENCES entity_types(id) ON DELETE CASCADE,
+ parent_id UUID NOT NULL REFERENCES entity_types(id) ON DELETE CASCADE,
+ -- 左栏画树时走这一支。不参与语义,只管展示
+ is_primary BOOLEAN NOT NULL DEFAULT FALSE,
+ PRIMARY KEY (child_id, parent_id),
+ -- 自环在这里就挡掉;更长的环由应用在写入前查(SQL 拦不住 A→B→A)
+ CONSTRAINT entity_type_parents_no_self CHECK (child_id <> parent_id)
+);
+
+CREATE UNIQUE INDEX entity_type_parents_primary_idx
+ ON entity_type_parents (child_id) WHERE is_primary;
+
+-- 反向查:左栏要按父类找子类,域判定要沿父链上溯
+CREATE INDEX entity_type_parents_parent_idx ON entity_type_parents (parent_id);
+
+-- 回填。原来的单父就是主父——它本来就是左栏画树用的那一支
+INSERT INTO entity_type_parents (child_id, parent_id, is_primary)
+SELECT id, parent_id, TRUE FROM entity_types WHERE parent_id IS NOT NULL;
+
+ALTER TABLE entity_types DROP COLUMN parent_id;
diff --git a/web/src/api.ts b/web/src/api.ts
index d8f5983c..a540ed98 100644
--- a/web/src/api.ts
+++ b/web/src/api.ts
@@ -390,7 +390,10 @@ export interface EntityTypeView {
color: string;
shape: "circle" | "square";
builtin: boolean;
- parent_id: string | null;
+ /** 全部父类(subClassOf 可以有多个) */
+ parents: string[];
+ /** 左栏画树时挂在哪一支下。不参与语义,只管展示 */
+ primary_parent: string | null;
description: string;
usage: number;
}
diff --git a/web/src/i18n/en.ts b/web/src/i18n/en.ts
index 94857f28..d0778429 100644
--- a/web/src/i18n/en.ts
+++ b/web/src/i18n/en.ts
@@ -43,6 +43,9 @@ export const en = {
bad_key:
"Keys are lowercase, letters digits and underscores only, up to 40 characters.",
self_parent: "A class cannot be its own parent.",
+ parent_cycle:
+ "That class is already below this one — the hierarchy would loop.",
+ bad_lang: "Pick a supported language.",
attr_needs_class: "An attribute has to belong to a class.",
entity_name_required: "Name cannot be empty.",
entity_name_too_long: "Name is too long — 100 characters at most.",
@@ -687,6 +690,8 @@ export const en = {
shapeColor: "Shape & color",
parent: "Parent class",
noParent: "(top level)",
+ /* 多父时左栏只能画一处,说明画在哪一支下 */
+ primaryParentHint: "Shown in the tree under the first one.",
/* 类型签名。措辞要说清它是引导不是闸门——本体写错时模型仍可覆盖 */
signature: "Type signature",
signatureHint:
diff --git a/web/src/i18n/zh.ts b/web/src/i18n/zh.ts
index 82763357..1e043280 100644
--- a/web/src/i18n/zh.ts
+++ b/web/src/i18n/zh.ts
@@ -41,6 +41,8 @@ export const zh: Strings = {
forms_required: "至少选一个这个关系涵盖的说法。",
bad_key: "key 只能用小写字母、数字和下划线,最长 40 个字符。",
self_parent: "一个类不能是自己的父类。",
+ parent_cycle: "那个类已经在这个类下面了——层级会成环。",
+ bad_lang: "选一个支持的语言。",
attr_needs_class: "属性必须挂在某个类上。",
entity_name_required: "名称不能为空。",
entity_name_too_long: "名称太长了——最多 100 个字符。",
@@ -640,6 +642,7 @@ export const zh: Strings = {
shapeColor: "形状与颜色",
parent: "父类",
noParent: "(顶层)",
+ primaryParentHint: "左栏的树里挂在第一个下面。",
signature: "类型签名",
signatureHint:
"这个关系连接哪些类。它作为提示进抽取提示词,不是闸门——" +
diff --git a/web/src/pages/Ontology.tsx b/web/src/pages/Ontology.tsx
index 7b7572e0..c63d657b 100644
--- a/web/src/pages/Ontology.tsx
+++ b/web/src/pages/Ontology.tsx
@@ -29,7 +29,6 @@ import {
Pager,
PageTitle,
RAIL_CLS,
- SearchSelect,
cn,
pageSlice,
} from "../ui";
@@ -276,7 +275,7 @@ export function Ontology() {
parentId={
sel?.kind === "new-class"
? sel.parentId
- : (selectedClass?.parent_id ?? null)
+ : (selectedClass?.primary_parent ?? null)
}
allTypes={entity_types}
onNewSub={
@@ -704,7 +703,7 @@ function ClassTree({
}
const children = new Map<string | null, EntityTypeView[]>();
for (const t of types) {
- const p = t.parent_id ?? null;
+ const p = t.primary_parent ?? null;
if (!children.has(p)) children.set(p, []);
children.get(p)!.push(t);
}
@@ -850,7 +849,7 @@ function parentOptions(
while (grew) {
grew = false;
for (const t of allTypes) {
- if (t.parent_id && excluded.has(t.parent_id) && !excluded.has(t.id)) {
+ if (t.parents.some((p) => excluded.has(p)) && !excluded.has(t.id)) {
excluded.add(t.id);
grew = true;
}
@@ -859,7 +858,7 @@ function parentOptions(
}
const children = new Map<string | null, EntityTypeView[]>();
for (const t of allTypes) {
- const p = t.parent_id ?? null;
+ const p = t.primary_parent ?? null;
if (!children.has(p)) children.set(p, []);
children.get(p)!.push(t);
}
@@ -900,10 +899,13 @@ function ClassForm({
const [shape, setShape] = useState<"circle" | "square">(
existing?.shape ?? "circle",
);
- const [parent, setParent] = useState<string>(parentId ?? "");
+ const [parents, setParents] = useState<string[]>(
+ existing?.parents ?? (parentId ? [parentId] : []),
+ );
const [description, setDescription] = useState(existing?.description ?? "");
- useEffect(() => setParent(parentId ?? ""), [parentId]);
+ // 从左栏点"+ 子类"进来时预填那个父。多父下它是第一个,也就是主父
+ useEffect(() => setParents(parentId ? [parentId] : []), [parentId]);
const save = useMutation({
mutationFn: async (): Promise<unknown> =>
@@ -912,7 +914,7 @@ function ClassForm({
label,
color,
shape,
- parent_id: parent || null,
+ parents,
description,
})
: api.createEntityType(kbId, {
@@ -920,7 +922,7 @@ function ClassForm({
label,
color,
shape,
- parent_id: parent || null,
+ parents,
description,
}),
onSuccess: (res) => {
@@ -1006,17 +1008,26 @@ function ClassForm({
</div>
</div>
</div>
+ {/* 多父:subClassOf 可以有多条。左栏按树画,一个类只能出现一次——
+ 所以第一个当主父。界面说明这条,不另加一个"选主父"的控件 */}
<div>
<label className={lbl}>{S.ontology.parent}</label>
- <SearchSelect
- value={parent}
- onChange={setParent}
- className="w-full"
- options={[
- { value: "", label: S.ontology.noParent },
- ...parentOptions(allTypes, existing?.id),
- ]}
+ <MultiSearchSelect
+ values={parents}
+ options={parentOptions(allTypes, existing?.id)}
+ onToggle={(id) =>
+ setParents((v) =>
+ v.includes(id) ? v.filter((x) => x !== id) : [...v, id],
+ )
+ }
+ placeholder={S.ontology.searchTypes}
+ emptyHint={S.ontology.noParent}
/>
+ {parents.length > 1 && (
+ <p className="mt-1 text-[11px] text-neutral-600">
+ {S.ontology.primaryParentHint}
+ </p>
+ )}
</div>
<div>
<label className={lbl}>{S.ontology.description}</label>