World's first open-source enterprise world model.
Rust agent-memorybitemporalgraphragknowledge-baseknowledge-graphllmontologypgvectorpostgresqlragrustself-hostedsemantic-searchtemporal-knowledge-graphworld-model
domain and range become join tables, so an attribute can belong to two classes (#66)
WaylandYang9faa2d1dc2fc
diff --git a/crates/utopia-core/src/models.rs b/crates/utopia-core/src/models.rsindex 75a1f744..1bd5467c 100644--- a/crates/utopia-core/src/models.rs+++ b/crates/utopia-core/src/models.rs@@ -315,8 +315,11 @@ pub struct RelationTypeView {pub description: String,/// relation(宾语是实体)| attribute(宾语是字面值)pub kind: String,- /// attribute 专用:挂在哪个类下- pub domain_type_id: Option<Uuid>,+ /// 可以当主语的类。attribute 至少一个;relation 可空(未声明 = 不限)+ pub domains: Vec<Uuid>,+ /// 可以当宾语的类。**只对 relation 有意义**——attribute 的值域是字面量类型,+ /// 落在 datatype 上+ pub ranges: Vec<Uuid>,/// attribute 专用:text | number | date | boolpub datatype: Option<String>,pub unit: Option<String>,@@ -413,8 +416,10 @@ pub struct RelationType {pub iri: Option<String>,/// relation(宾语是实体)| attribute(宾语是字面值,走 facts.object_value)pub kind: String,- /// attribute 专用:属性挂在哪个类下- pub domain_type_id: Option<Uuid>,+ /// 可以当主语的类(多值:OWL 里一个属性有多个 rdfs:domain 是常态)+ pub domains: Vec<Uuid>,+ /// 可以当宾语的类。只对 relation 有意义+ pub ranges: Vec<Uuid>,/// attribute 专用:text | number | date | boolpub datatype: Option<String>,pub unit: Option<String>,diff --git a/crates/utopia-server/src/api/ontology_routes.rs b/crates/utopia-server/src/api/ontology_routes.rsindex 5ca6b2cc..9485bcc5 100644--- a/crates/utopia-server/src/api/ontology_routes.rs+++ b/crates/utopia-server/src/api/ontology_routes.rs@@ -191,9 +191,12 @@ pub struct RelationTypeReq {/// relation | attribute(创建时定死,更新时忽略)#[serde(default)]pub kind: Option<String>,- /// attribute 专用:所属类+ /// 可以当主语的类。attribute 至少一个;relation 留空 = 不限#[serde(default)]- pub domain_type_id: Option<Uuid>,+ pub domains: Vec<Uuid>,+ /// 可以当宾语的类。只对 relation 有意义+ #[serde(default)]+ pub ranges: Vec<Uuid>,/// attribute 专用:text | number | date | bool#[serde(default)]pub datatype: Option<String>,@@ -229,7 +232,8 @@ pub async fn create_relation_type(req.inverse_functional,req.description.as_deref().unwrap_or("").trim(),kind,- req.domain_type_id,+ &req.domains,+ &req.ranges,req.datatype.as_deref(),req.unit.as_deref().map(str::trim).filter(|s| !s.is_empty()),)@@ -494,7 +498,9 @@ pub async fn adopt_predicate(req.inverse_functional,req.description.as_deref().unwrap_or("").trim(),"relation",- None,+ // 提案与冷启动只建关系,不声明 domain/range —— 留空 = 不限主宾类型+ &[],+ &[],None,None,)diff --git a/crates/utopia-server/src/bootstrap_ontology.rs b/crates/utopia-server/src/bootstrap_ontology.rsindex 684535f8..a9030a94 100644--- a/crates/utopia-server/src/bootstrap_ontology.rs+++ b/crates/utopia-server/src/bootstrap_ontology.rs@@ -161,7 +161,9 @@ pub async fn bootstrap_ontology(state: &AppState, kb_id: Uuid) -> anyhow::Result.or_else(|| str_of(p, "reason")).unwrap_or(""),"relation",- None,+ // 提案与冷启动只建关系,不声明 domain/range —— 留空 = 不限主宾类型+ &[],+ &[],None,None,)diff --git a/crates/utopia-server/src/extraction.rs b/crates/utopia-server/src/extraction.rsindex b693a438..f28f410f 100644--- a/crates/utopia-server/src/extraction.rs+++ b/crates/utopia-server/src/extraction.rs@@ -146,11 +146,14 @@ async fn run(state: &AppState, document_id: Uuid) -> anyhow::Result<()> {.filter(|r| r.kind == "attribute").map(|r| (r.key.as_str(), r)).collect();+ // 一个属性挂在多个类下时,**每个类各排一行**:模型读到的是+ // "store.opens_at" 而不是一个要它自己去分配的类清单let attr_lines: Vec<String> = rtypes.iter().filter(|r| r.kind == "attribute")- .filter_map(|r| {- let class_key = type_key_by_id.get(&r.domain_type_id?)?;+ .flat_map(|r| r.domains.iter().map(move |d| (r, d)))+ .filter_map(|(r, domain_id)| {+ let class_key = type_key_by_id.get(domain_id)?;let dt = r.datatype.as_deref().unwrap_or("text");let spec = match &r.unit {Some(u) if !u.is_empty() => format!("{dt}, {u}"),@@ -336,14 +339,24 @@ async fn run(state: &AppState, document_id: Uuid) -> anyhow::Result<()> {.await;continue;};- // 不可达:store 层强制 attribute 必有 domain,且 kind/domain 不可改,+ // 不可达:store 层强制 attribute 必有 domain,且 domain 不可改,// 无 domain 的属性连提示词都进不去。留着是防御,不需要信号- let Some(domain) = attr.domain_type_id else {+ if attr.domains.is_empty() {continue;- };- if !type_matches_domain(subject_type, domain) {+ }+ // **任一 domain 命中即可**:属性挂在多个类下时,主语属于其中之一就算数+ if !attr+ .domains+ .iter()+ .any(|d| type_matches_domain(subject_type, *d))+ {let subj_key = type_key_by_id.get(&subject_type).copied().unwrap_or("?");- let dom_key = type_key_by_id.get(&domain).copied().unwrap_or("?");+ let dom_key = attr+ .domains+ .iter()+ .filter_map(|d| type_key_by_id.get(d).copied())+ .collect::<Vec<_>>()+ .join("|");drop_signal(state,doc.kb_id,diff --git a/crates/utopia-server/src/owl_import.rs b/crates/utopia-server/src/owl_import.rsindex ffead1c4..9064fe02 100644--- a/crates/utopia-server/src/owl_import.rs+++ b/crates/utopia-server/src/owl_import.rs@@ -45,8 +45,7 @@ pub enum AttrNote {UnusableRange(String),/// 不建:没写 domain。属性必须挂在一个类上,这是 store 层的硬约束NoDomain,- /// 不建:多个 domain,等 domain 关联表(0001 P2c)- MultipleDomains(usize),+/// 不建:domain 指向的类**在这个文件里,但被跳过了**(多半是 key 撞车)。/// 与 UnknownDomain 分开报,因为处置不同:这个能通过给现有的类改名解开DomainSkipped(String),@@ -96,18 +95,19 @@ fn attr_note(resolvable: &HashSet<&str>,in_file: &HashSet<&str>,) -> AttrNote {- match p.domains.as_slice() {- [] => return AttrNote::NoDomain,- [one] => {- if !resolvable.contains(one.as_str()) {- return if in_file.contains(one.as_str()) {- AttrNote::DomainSkipped(one.clone())- } else {- AttrNote::UnknownDomain(one.clone())- };- }- }- many => return AttrNote::MultipleDomains(many.len()),+ if p.domains.is_empty() {+ return AttrNote::NoDomain;+ }+ // **一个都解析不出来才算失败**:多个 domain 里有一部分被跳过时,+ // 属性仍然建,只是少挂几个类——比整条丢掉强,而被跳过的那些类+ // 在计划里各自报告过 key 撞车+ if !p.domains.iter().any(|d| resolvable.contains(d.as_str())) {+ let first = &p.domains[0];+ return if in_file.contains(first.as_str()) {+ AttrNote::DomainSkipped(first.clone())+ } else {+ AttrNote::UnknownDomain(first.clone())+ };}match ontology_rdf::map_range(&p.ranges) {ontology_rdf::RangeMapping::Datatype(dt) => AttrNote::Datatype(dt),@@ -145,7 +145,6 @@ impl ImportPlan {| Some(AttrNote::DegradedToText(_)) => continue,Some(AttrNote::UnusableRange(_)) => "unusable_range",Some(AttrNote::NoDomain) => "no_domain",- Some(AttrNote::MultipleDomains(_)) => "multiple_domains",Some(AttrNote::DomainSkipped(_)) => "domain_skipped",Some(AttrNote::UnknownDomain(_)) => "unknown_domain",None => continue,@@ -378,14 +377,19 @@ pub async fn apply(let (Some(note), Some(p)) = (item.attr.as_ref(), by_prop_iri.get(item.iri.as_str())) else {continue;};- let (Some(dt), Some(domain_iri)) = (attr_datatype(note), p.domains.first()) else {+ let Some(dt) = attr_datatype(note) else {continue;};- let Some(&domain_id) = id_of.get(domain_iri) else {- // 计划阶段判为可解析,落库时却没有 id:类被跳过或更新失败。- // 计划已经报告过它,这里安静略过而不是造一个挂空的属性+ // 计划阶段判为可解析、落库时却没有 id 的(类被跳过或更新失败)自然落选;+ // 全落选就不建,而不是造一个挂空的属性+ let domain_ids: Vec<Uuid> = p+ .domains+ .iter()+ .filter_map(|iri| id_of.get(iri).copied())+ .collect();+ if domain_ids.is_empty() {continue;- };+ }if utopia_store::ontology::create_attribute_with_iri(&state.pool,kb_id,@@ -393,7 +397,7 @@ pub async fn apply(&p.label,&p.description,&p.iri,- domain_id,+ &domain_ids,dt,).await?diff --git a/crates/utopia-store/src/graph.rs b/crates/utopia-store/src/graph.rsindex 44c26842..27196655 100644--- a/crates/utopia-store/src/graph.rs+++ b/crates/utopia-store/src/graph.rs@@ -396,12 +396,19 @@ pub async fn entity_types(pool: &PgPool, kb_id: Uuid) -> AppResult<Vec<EntityTyp}pub async fn relation_types(pool: &PgPool, kb_id: Uuid) -> AppResult<Vec<RelationType>> {- Ok(- sqlx::query_as("SELECT * FROM relation_types WHERE kb_id = $1 ORDER BY created_at")- .bind(kb_id)- .fetch_all(pool)- .await?,+ // 不用 SELECT *:domain/range 在关联表里,`*` 取不到,+ // 而且 sqlx 要到运行时才会说 "no column found" —— 编译器看不见 SQL 字符串+ Ok(sqlx::query_as(+ "SELECT r.*,+ ARRAY(SELECT d.entity_type_id FROM relation_type_domains d+ WHERE d.relation_type_id = r.id) AS domains,+ ARRAY(SELECT g.entity_type_id FROM relation_type_ranges g+ WHERE g.relation_type_id = r.id) AS ranges+ FROM relation_types r WHERE r.kb_id = $1 ORDER BY r.created_at",)+ .bind(kb_id)+ .fetch_all(pool)+ .await?)}/// 写入事实。返回 (事实 id, 是否新建)。diff --git a/crates/utopia-store/src/ontology.rs b/crates/utopia-store/src/ontology.rsindex 1cdf2da1..f4cebd85 100644--- a/crates/utopia-store/src/ontology.rs+++ b/crates/utopia-store/src/ontology.rs@@ -66,7 +66,11 @@ fn validate_shape(shape: &str) -> AppResult<()> {pub async fn relation_type_views(pool: &PgPool, kb_id: Uuid) -> AppResult<Vec<RelationTypeView>> {Ok(sqlx::query_as("SELECT r.id, r.key, r.label, r.temporal, r.functional, r.inverse_functional, r.builtin, r.description,- r.kind, r.domain_type_id, r.datatype, r.unit,+ r.kind, r.datatype, r.unit,+ ARRAY(SELECT d.entity_type_id FROM relation_type_domains d+ WHERE d.relation_type_id = r.id) AS domains,+ ARRAY(SELECT g.entity_type_id FROM relation_type_ranges g+ WHERE g.relation_type_id = r.id) AS ranges,(SELECT count(*) FROM facts fWHERE f.predicate_id = r.id AND f.invalidated_at IS NULL) AS usageFROM relation_types r WHERE r.kb_id = $1 ORDER BY lower(r.label)",@@ -176,6 +180,21 @@ pub async fn delete_entity_type(pool: &PgPool, kb_id: Uuid, id: Uuid) -> AppResu"Cannot delete: {usage} entities use this type")));}+ // 只剩这一个 domain 的属性随类一起走:属性必须挂在类上,+ // 留一个没有 domain 的属性等于留一个不会出现在任何地方的死行。+ // 还挂在别的类上的则只掉一条关联(外键 CASCADE 负责)+ sqlx::query(+ "DELETE FROM relation_types r+ WHERE r.kind = 'attribute' AND r.kb_id = $1+ AND EXISTS (SELECT 1 FROM relation_type_domains d+ WHERE d.relation_type_id = r.id AND d.entity_type_id = $2)+ AND NOT EXISTS (SELECT 1 FROM relation_type_domains d+ WHERE d.relation_type_id = r.id AND d.entity_type_id <> $2)",+ )+ .bind(kb_id)+ .bind(id)+ .execute(pool)+ .await?;let res = sqlx::query("DELETE FROM entity_types WHERE id = $2 AND kb_id = $1 AND NOT builtin").bind(kb_id).bind(id)@@ -192,13 +211,13 @@ pub async fn delete_entity_type(pool: &PgPool, kb_id: Uuid, id: Uuid) -> AppResu/// 属性字段校验:attribute 必须有所属类和合法 datatype;relation 三者强制为空。fn validate_attribute_fields(kind: &str,- domain_type_id: Option<Uuid>,+ domains: &[Uuid],datatype: Option<&str>,) -> AppResult<()> {match kind {"relation" => Ok(()),"attribute" => {- if domain_type_id.is_none() {+ if domains.is_empty() {return Err(AppError::invalid("attr_needs_class","An attribute needs a class (domain)",@@ -228,7 +247,8 @@ pub async fn create_relation_type(inverse_functional: bool,description: &str,kind: &str,- domain_type_id: Option<Uuid>,+ domains: &[Uuid],+ ranges: &[Uuid],datatype: Option<&str>,unit: Option<&str>,) -> AppResult<Uuid> {@@ -238,13 +258,13 @@ pub async fn create_relation_type("temporal must be state / event / eternal".into(),));}- validate_attribute_fields(kind, domain_type_id, datatype)?;+ validate_attribute_fields(kind, domains, datatype)?;let is_attr = kind == "attribute";let id = Uuid::now_v7();sqlx::query("INSERT INTO relation_types (id, kb_id, key, label, temporal, functional, inverse_functional, description,- kind, domain_type_id, datatype, unit)- VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12)",+ kind, datatype, unit)+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11)",).bind(id).bind(kb_id)@@ -255,7 +275,6 @@ pub async fn create_relation_type(.bind(inverse_functional).bind(description).bind(kind)- .bind(is_attr.then_some(domain_type_id).flatten()).bind(is_attr.then_some(datatype).flatten()).bind(is_attr.then_some(unit).flatten()).execute(pool)@@ -266,9 +285,44 @@ pub async fn create_relation_type(}_ => AppError::Db(e),})?;+ // attribute 不写 range:它的值域是字面量类型,落在 datatype 上+ set_domains_ranges(pool, id, domains, if is_attr { &[] } else { ranges }).await?;Ok(id)}+/// 覆盖式写入 domain / range。**先删后插**,所以它既能用于新建也能用于重导入,+/// 且不会留下上一轮的残余。+async fn set_domains_ranges(+ pool: &PgPool,+ relation_type_id: Uuid,+ domains: &[Uuid],+ ranges: &[Uuid],+) -> AppResult<()> {+ for (table, ids) in [+ ("relation_type_domains", domains),+ ("relation_type_ranges", ranges),+ ] {+ sqlx::query(&format!("DELETE FROM {table} WHERE relation_type_id = $1"))+ .bind(relation_type_id)+ .execute(pool)+ .await?;+ if ids.is_empty() {+ continue;+ }+ // unnest 一次插完,省去逐条往返+ sqlx::query(&format!(+ "INSERT INTO {table} (relation_type_id, entity_type_id)+ SELECT $1, x FROM unnest($2::uuid[]) AS x+ ON CONFLICT DO NOTHING"+ ))+ .bind(relation_type_id)+ .bind(ids)+ .execute(pool)+ .await?;+ }+ Ok(())+}+#[allow(clippy::too_many_arguments)]pub async fn update_relation_type(pool: &PgPool,@@ -486,7 +540,7 @@ pub async fn create_attribute_with_iri(label: &str,description: &str,iri: &str,- domain_type_id: Uuid,+ domains: &[Uuid],datatype: &str,) -> AppResult<Option<Uuid>> {validate_key(key)?;@@ -494,8 +548,8 @@ pub async fn create_attribute_with_iri(let row: Option<(Uuid,)> = sqlx::query_as("INSERT INTO relation_types(id, kb_id, key, label, temporal, functional, inverse_functional,- description, kind, domain_type_id, datatype, iri)- VALUES ($1, $2, $3, $4, 'state', FALSE, FALSE, $5, 'attribute', $6, $7, $8)+ description, kind, datatype, iri)+ VALUES ($1, $2, $3, $4, 'state', FALSE, FALSE, $5, 'attribute', $6, $7)ON CONFLICT (kb_id, key) DO NOTHINGRETURNING id",)@@ -504,12 +558,15 @@ pub async fn create_attribute_with_iri(.bind(key).bind(label).bind(description)- .bind(domain_type_id).bind(datatype).bind(iri).fetch_optional(pool).await?;- Ok(row.map(|(id,)| id))+ let Some((new_id,)) = row else {+ return Ok(None);+ };+ set_domains_ranges(pool, new_id, domains, &[]).await?;+ Ok(Some(new_id))}pub async fn set_parent(pool: &PgPool, kb_id: Uuid, child: Uuid, parent: Uuid) -> AppResult<()> {diff --git a/migrations/0035_relation_type_domains_ranges.sql b/migrations/0035_relation_type_domains_ranges.sqlnew file mode 100644index 00000000..5d8c5550--- /dev/null+++ b/migrations/0035_relation_type_domains_ranges.sql@@ -0,0 +1,34 @@+-- domain / range 从单列改为关联表。+--+-- **为什么必须是多值**:OWL 里一个属性有多个 rdfs:domain 是常态+-- (works_at 的主语可能是 person 也可能是 organization),单列表达不了,+-- 导入时只能挑一个丢一个。FOAF 里就有这样的属性。+--+-- **为什么把列删掉而不是留着当"主 domain"**:留着就是同一件事有两处记录,+-- 而两处记录迟早分叉——今天已经在别处踩过一次(预览与落库各判一次 key 冲突,+-- 结果预览说了假话)。一处权威,读的人不必猜该信哪个。+--+-- range 只服务对象属性:数据属性的 range 是字面量类型,落在 relation_types.datatype 上。++CREATE TABLE relation_type_domains (+ relation_type_id UUID NOT NULL REFERENCES relation_types(id) ON DELETE CASCADE,+ entity_type_id UUID NOT NULL REFERENCES entity_types(id) ON DELETE CASCADE,+ PRIMARY KEY (relation_type_id, entity_type_id)+);++CREATE TABLE relation_type_ranges (+ relation_type_id UUID NOT NULL REFERENCES relation_types(id) ON DELETE CASCADE,+ entity_type_id UUID NOT NULL REFERENCES entity_types(id) ON DELETE CASCADE,+ PRIMARY KEY (relation_type_id, entity_type_id)+);++-- 反向查:本体页要按类列出它的属性,抽取要按类筛可用属性。+-- 主键覆盖了正向,反向得自己建+CREATE INDEX relation_type_domains_entity_idx ON relation_type_domains (entity_type_id);+CREATE INDEX relation_type_ranges_entity_idx ON relation_type_ranges (entity_type_id);++-- 回填现有属性的单个 domain。此前只有属性用得上这一列,关系一直是 NULL+INSERT INTO relation_type_domains (relation_type_id, entity_type_id)+SELECT id, domain_type_id FROM relation_types WHERE domain_type_id IS NOT NULL;++ALTER TABLE relation_types DROP COLUMN domain_type_id;diff --git a/web/src/api.ts b/web/src/api.tsindex 0c357de7..d8f5983c 100644--- a/web/src/api.ts+++ b/web/src/api.ts@@ -406,7 +406,10 @@ export interface RelationTypeView {description: string;/** relation(宾语是实体)| attribute(宾语是字面值) */kind: "relation" | "attribute";- domain_type_id: string | null;+ /** 可以当主语的类。attribute 至少一个;relation 留空 = 不限 */+ domains: string[];+ /** 可以当宾语的类。只对 relation 有意义——attribute 的值域是 datatype */+ ranges: string[];datatype: "text" | "number" | "date" | "bool" | null;unit: string | null;usage: number;diff --git a/web/src/pages/Ontology.tsx b/web/src/pages/Ontology.tsxindex 1ae5adb7..2f239260 100644--- a/web/src/pages/Ontology.tsx+++ b/web/src/pages/Ontology.tsx@@ -307,7 +307,7 @@ export function Ontology() {attributes={relation_types.filter((r) =>r.kind === "attribute" &&- r.domain_type_id === selectedClass.id,+ r.domains.includes(selectedClass.id),)}onChanged={refresh}onError={onError}@@ -537,7 +537,7 @@ function AttributeForm({key,label,kind: "attribute",- domain_type_id: typeId,+ domains: [typeId],temporal: "state",functional: single,inverse_functional: false,