Elffuss BraidHub

kikocis/utopia public

dev · 32.5 KiBRawPermalink
1//! OWL 导入:原文保真 → 投影 → 预览 → 落库。
2//!
3//! **预览与落库走同一个计划**。两条独立的代码路径迟早分叉,而分叉的后果是
4//! 用户点确认之后发生的事与他刚看过的不一样——那比没有预览更糟。
5//!
6//! 匹配按 **IRI** 不按 key:上游改一次 `rdfs:label`,派生出的 key 就变了,
7//! 按 key 匹配会把同一个类当新类建出来,实体全留在孤儿上(见 0001 P2)。
8
9use std::collections::{BTreeMap, HashMap, HashSet};
10
11use utopia_core::AppResult;
12use utopia_ingest::ontology_rdf::{self, OwlProjection, RdfFormat};
13use uuid::Uuid;
14
15use crate::state::AppState;
16
17/// 一个类/属性在这次导入里的去向。
18#[derive(Debug, Clone, Copy, PartialEq, serde::Serialize)]
19#[serde(rename_all = "snake_case")]
20pub enum Disposition {
21 /// 本体里没有这个 IRI → 新建
22 Create,
23 /// IRI 已在 → 更新标签与描述(key 不动:它可能已被引用)
24 Update,
25 /// key 被另一个 IRI 占着 → 跳过并报告,不悄悄改名也不覆盖
26 KeyTaken,
27 /// key 被另一个 IRI 占着,但对齐表说那两个是**同一个东西** → 跳过且不算冲突。
28 /// 与 KeyTaken 分开,是因为它不需要人裁:少建一个重复的类正是想要的结果
29 Aligned,
30}
31
32/// 一个属性在这次导入里会不会被建出来,以及为什么。
33///
34/// **预览必须说得出为什么**。上一版只报了"解析到 54 个属性",读者无从判断
35/// 那是"都会建"还是"一个都不建"——而实际上是后者。
36#[derive(Debug, Clone, PartialEq, serde::Serialize)]
37#[serde(rename_all = "snake_case", tag = "outcome", content = "detail")]
38pub enum AttrNote {
39 /// 会建,用这个 datatype
40 Datatype(&'static str),
41 /// 会建成 text:没写 range,词汇表没做声明,text 是诚实的超集
42 NoRange,
43 /// 会建成 text:range 是可读字面量但我们表达不了它的类型(`xsd:time` 等)。
44 /// 报出原 IRI,人可以改成更合适的类型;但值先落下来,不能因为类型糙就丢知识
45 DegradedToText(String),
46 /// 不建:抽取器不可能从散文里读出这种值(二进制、XML 片段、XML 内部标识)。
47 /// 建了也永远填不上,只会给每个文本块的提示词多一行死噪音
48 UnusableRange(String),
49 /// 不建:没写 domain。属性必须挂在一个类上,这是 store 层的硬约束
50 NoDomain,
51
52 /// 不建:domain 指向的类**在这个文件里,但被跳过了**(多半是 key 撞车)。
53 /// 与 UnknownDomain 分开报,因为处置不同:这个能通过给现有的类改名解开
54 DomainSkipped(String),
55 /// 不建:domain 指向一个这个文件里压根没有的类(外部词汇表)
56 UnknownDomain(String),
57}
58
59#[derive(Debug, Clone, serde::Serialize)]
60pub struct PlannedItem {
61 pub iri: String,
62 pub key: String,
63 pub label: String,
64 pub has_description: bool,
65 pub disposition: Disposition,
66 /// 关系专用:导入声明它是函数性的 —— 预览必须把这些单独列出来
67 #[serde(skip_serializing_if = "std::ops::Not::not")]
68 pub functional: bool,
69 #[serde(skip_serializing_if = "Option::is_none")]
70 pub conflict_with: Option<String>,
71 /// 属性专用:会以什么 datatype 建,或为什么建不了
72 #[serde(skip_serializing_if = "Option::is_none")]
73 pub attr: Option<AttrNote>,
74}
75
76/// 一次导入的完整计划。预览返回它,落库也执行它。
77#[derive(Debug, Clone, serde::Serialize)]
78pub struct ImportPlan {
79 pub format: String,
80 pub triples: usize,
81 pub classes: Vec<PlannedItem>,
82 pub relations: Vec<PlannedItem>,
83 pub attributes: Vec<PlannedItem>,
84 /// 出现过但今天不消费的公理 → 次数。**不是"已跳过",是"暂未投影"**
85 pub unprojected: Vec<(String, usize)>,
86 /// 没有 `rdfs:comment` 的类数。它们在抽取里质量会明显偏低——
87 /// description 逐字进提示词,是模型判断"什么算这个类"的唯一依据
88 pub classes_without_description: usize,
89 /// 声明为函数性的关系数。**这是 part_of 那个坑的企业版**:本体声明唯一,
90 /// 数据不遵守,导完就是一队假冲突
91 pub functional_relations: usize,
92}
93
94/// 属性的去向。**domain 先判**:没有 domain 的属性根本建不出来,
95/// 这时它的 range 是什么已经不重要了。
96fn attr_note(
97 p: &ontology_rdf::OwlProperty,
98 vocab: &ontology_rdf::VocabDatatypes,
99 resolvable: &HashSet<&str>,
100 in_file: &HashSet<&str>,
101) -> AttrNote {
102 if p.domains.is_empty() {
103 return AttrNote::NoDomain;
104 }
105 // **一个都解析不出来才算失败**:多个 domain 里有一部分被跳过时,
106 // 属性仍然建,只是少挂几个类——比整条丢掉强,而被跳过的那些类
107 // 在计划里各自报告过 key 撞车
108 if !p.domains.iter().any(|d| resolvable.contains(d.as_str())) {
109 let first = &p.domains[0];
110 return if in_file.contains(first.as_str()) {
111 AttrNote::DomainSkipped(first.clone())
112 } else {
113 AttrNote::UnknownDomain(first.clone())
114 };
115 }
116 match ontology_rdf::map_range_of(p, vocab) {
117 ontology_rdf::RangeMapping::Datatype(dt) => AttrNote::Datatype(dt),
118 ontology_rdf::RangeMapping::Absent => AttrNote::NoRange,
119 ontology_rdf::RangeMapping::Degraded(iri) => AttrNote::DegradedToText(iri),
120 ontology_rdf::RangeMapping::Unusable(iri) => AttrNote::UnusableRange(iri),
121 }
122}
123
124/// 属性会不会被建出来,以及用什么 datatype。落库与统计共用它,
125/// 免得"预览说会建"和"实际建了"两处各判一次而分叉。
126fn attr_datatype(note: &AttrNote) -> Option<&'static str> {
127 match note {
128 AttrNote::Datatype(dt) => Some(dt),
129 // 没写 range,或写了但类型表达不了:值仍是字面量,
130 // text 是拦不住任何东西的诚实超集
131 AttrNote::NoRange | AttrNote::DegradedToText(_) => Some("text"),
132 _ => None,
133 }
134}
135
136impl ImportPlan {
137 /// 建不出来的属性,按原因分组计数。**预览里报总数是不够的**——
138 /// "54 个属性"读不出那是都会建还是一个都不建,而实际上取决于原因。
139 pub fn attr_skips(&self) -> BTreeMap<&str, usize> {
140 let mut out: BTreeMap<&str, usize> = BTreeMap::new();
141 for a in &self.attributes {
142 if a.disposition == Disposition::KeyTaken {
143 *out.entry("key_taken").or_default() += 1;
144 continue;
145 }
146 let reason = match a.attr.as_ref() {
147 Some(AttrNote::Datatype(_))
148 | Some(AttrNote::NoRange)
149 | Some(AttrNote::DegradedToText(_)) => continue,
150 Some(AttrNote::UnusableRange(_)) => "unusable_range",
151 Some(AttrNote::NoDomain) => "no_domain",
152 Some(AttrNote::DomainSkipped(_)) => "domain_skipped",
153 Some(AttrNote::UnknownDomain(_)) => "unknown_domain",
154 None => continue,
155 };
156 *out.entry(reason).or_default() += 1;
157 }
158 out
159 }
160}
161
162/// 解析文件并对着现有本体算出计划。不写任何东西。
163pub async fn plan(
164 state: &AppState,
165 kb_id: Uuid,
166 filename: &str,
167 bytes: &[u8],
168) -> AppResult<(ImportPlan, OwlProjection, RdfFormat)> {
169 let format = RdfFormat::detect(filename, bytes);
170 let proj = ontology_rdf::project(bytes, format).map_err(|e| {
171 utopia_core::AppError::invalid_detail(
172 "bad_ontology_file",
173 "Could not parse this ontology file",
174 e.to_string(),
175 )
176 })?;
177
178 // 现有本体:按 IRI 与按 key 各建一份索引,两种冲突分别判
179 let etypes = utopia_store::graph::entity_types(&state.pool, kb_id).await?;
180 let rtypes = utopia_store::graph::relation_types(&state.pool, kb_id).await?;
181 let e_by_iri: HashMap<&str, &_> = etypes
182 .iter()
183 .filter_map(|t| t.iri.as_deref().map(|i| (i, t)))
184 .collect();
185 let e_by_key: HashMap<&str, &_> = etypes.iter().map(|t| (t.key.as_str(), t)).collect();
186 let r_by_iri: HashMap<&str, &_> = rtypes
187 .iter()
188 .filter_map(|t| t.iri.as_deref().map(|i| (i, t)))
189 .collect();
190 let r_by_key: HashMap<&str, &_> = rtypes.iter().map(|t| (t.key.as_str(), t)).collect();
191
192 // 这次结束后能解析出 id 的类 IRI:文件里新建或更新的,加上库里已有同 IRI 的。
193 // key 撞车被跳过的**不在其列**——它不会被建出来,挂在它上面的属性也就无处可挂
194 // 本次导入内部也会撞 key:不同 IRI 派生出同一个短标签
195 //(FOAF 的 familyName 与 family_name 都成了 family_name)。
196 // 只对着库里查是不够的——那样第二个在预览里显示"会新建",
197 // 落库时被 ON CONFLICT 悄悄丢掉,预览就说了假话
198 //
199 // **两个命名空间,不是一个**:类进 entity_types、关系与属性进 relation_types,
200 // 各有各的 (kb_id, key) 唯一约束。合成一张表就是凭空多出一条约束——
201 // 而且代价具体:schema.org 的 location / address 是属性,却先被
202 // OMG Commons 的 Location / Address 两个**类**占了名字(类先处理),
203 // 于是抽取时模型点名要 location,库里偏偏没有
204 let mut claimed_class: HashMap<&str, &str> = HashMap::new();
205 let mut claimed_prop: HashMap<&str, &str> = HashMap::new();
206
207 let mut classes = Vec::new();
208 for c in &proj.classes {
209 // 对齐表判为"同名不同义"时,用它声明的 key 顶替派生出来的那个
210 let mut renamed_key: Option<&'static str> = None;
211 let (disposition, conflict_with) = if let Some(prev) = claimed_class.get(c.key.as_str()) {
212 (Disposition::KeyTaken, Some((*prev).to_string()))
213 } else if e_by_iri.contains_key(c.iri.as_str()) {
214 (Disposition::Update, None)
215 } else if let Some(existing) = e_by_key.get(c.key.as_str()) {
216 match existing.iri.as_deref() {
217 // **占位者没有 IRI:认领它。**
218 //
219 // 没有 IRI 意味着这个类是本地起的名字(种子本体、或者手工建的),
220 // 不是另一个词汇表的同名词。导入说的是"这个 IRI 就是那个类",
221 // 而这一步不做,整棵树就是断的:schema.org 的 Organization
222 // 撞上内置的 organization 被跳过,于是 Corporation 的父类指向
223 // 一个没建出来的东西——内置那几个基类一个子类都挂不上,
224 // 类型精化无从谈起。
225 None => (Disposition::Update, None),
226 // 已经有一个**不同的** IRI:两个词汇表争同一个短标签。
227 // 先查预制包的对齐表——那是**声明**的处置,重导入结果一样,
228 // 所以下面那条"不自动加后缀"的理由对它不适用
229 Some(other) => match crate::pack_alignment::lookup(&c.iri, other) {
230 // 同义:已有的那个就是它,少建一个重复的类正是想要的
231 Some(crate::pack_alignment::Alignment::SameAs) => {
232 (Disposition::Aligned, existing.iri.clone())
233 }
234 // 同名不同义:换一个声明好的 key 建出来
235 Some(crate::pack_alignment::Alignment::Rename(k)) => {
236 renamed_key = Some(k);
237 (Disposition::Create, None)
238 }
239 // 表里没有:这是真冲突。不自动加后缀——那会让重导入
240 // 认不出自己上次建的是哪个
241 None => (Disposition::KeyTaken, existing.iri.clone()),
242 },
243 }
244 } else {
245 (Disposition::Create, None)
246 };
247 // 改名与原名都是借用(前者 'static,后者借自 proj),统一成一个引用用完再落地
248 let key: &str = renamed_key.unwrap_or(c.key.as_str());
249 if !matches!(disposition, Disposition::KeyTaken | Disposition::Aligned) {
250 claimed_class.insert(key, c.iri.as_str());
251 }
252 classes.push(PlannedItem {
253 iri: c.iri.clone(),
254 key: key.to_string(),
255 label: c.label.clone(),
256 has_description: !c.description.trim().is_empty(),
257 disposition,
258 functional: false,
259 conflict_with,
260 attr: None,
261 });
262 }
263
264 // 文件里出现过的类(含被跳过的)——用来区分它被跳过了与它压根不在这个文件里
265 let in_file: HashSet<&str> = proj.classes.iter().map(|c| c.iri.as_str()).collect();
266 let resolvable: HashSet<&str> = classes
267 .iter()
268 .filter(|c| c.disposition != Disposition::KeyTaken)
269 .map(|c| c.iri.as_str())
270 .chain(e_by_iri.keys().copied())
271 .collect();
272
273 let mut relations = Vec::new();
274 let mut attributes = Vec::new();
275 for p in &proj.properties {
276 let (disposition, conflict_with) = if let Some(prev) = claimed_prop.get(p.key.as_str()) {
277 (Disposition::KeyTaken, Some((*prev).to_string()))
278 } else if r_by_iri.contains_key(p.iri.as_str()) {
279 (Disposition::Update, None)
280 } else if let Some(existing) = r_by_key.get(p.key.as_str()) {
281 (Disposition::KeyTaken, existing.iri.clone())
282 } else {
283 (Disposition::Create, None)
284 };
285 if disposition != Disposition::KeyTaken {
286 claimed_prop.insert(p.key.as_str(), p.iri.as_str());
287 }
288 let mut item = PlannedItem {
289 iri: p.iri.clone(),
290 key: p.key.clone(),
291 label: p.label.clone(),
292 has_description: !p.description.trim().is_empty(),
293 disposition,
294 functional: p.functional,
295 conflict_with,
296 attr: None,
297 };
298 if p.is_datatype {
299 item.attr = Some(attr_note(p, &proj.vocab_datatypes, &resolvable, &in_file));
300 attributes.push(item);
301 } else {
302 relations.push(item);
303 }
304 }
305
306 let mut unprojected: Vec<(String, usize)> = proj
307 .unprojected
308 .iter()
309 .map(|(k, v)| (k.clone(), *v))
310 .collect();
311 unprojected.sort_by_key(|(_, n)| std::cmp::Reverse(*n));
312
313 let plan = ImportPlan {
314 format: format!("{format:?}").to_lowercase(),
315 triples: proj.triples,
316 classes_without_description: classes.iter().filter(|c| !c.has_description).count(),
317 functional_relations: relations.iter().filter(|r| r.functional).count(),
318 classes,
319 relations,
320 attributes,
321 unprojected,
322 };
323 Ok((plan, proj, format))
324}
325
326/// 装完一组包之后再过一遍:把 domain / range 指向**别的包里的类**的那些关系接上。
327///
328/// 单次导入认本文件里的类和库里已有的类(见 [`apply`] 里的 resolve),但包是挨个
329/// 装的:装 W3C Org 时 FOAF 还没来,`headOf` 的 `rdfs:domain foaf:Agent` 就落了空;
330/// 等 FOAF 装好,没人回头补。没有 domain 的谓词 `judge_direction` 不判方向,
331/// 反向的 `Project Aurora head_of Li Ting` 就原样进图(#222)。
332///
333/// 只补不删,关联表 ON CONFLICT DO NOTHING,重复跑无害。属性不在这里:属性的
334/// 去向在计划阶段就定了(没有 domain 的根本建不出来),事后补 domain 改不了它
335/// 已经是不是一列的事实
336pub async fn relink_domains_ranges(
337 state: &AppState,
338 kb_id: Uuid,
339 filename: &str,
340 bytes: &[u8],
341) -> AppResult<(usize, usize)> {
342 let format = RdfFormat::detect(filename, bytes);
343 let proj = ontology_rdf::project(bytes, format).map_err(|e| {
344 utopia_core::AppError::invalid_detail(
345 "bad_ontology_file",
346 "Could not parse this ontology file",
347 e.to_string(),
348 )
349 })?;
350 let classes: HashMap<String, Uuid> = utopia_store::graph::entity_types(&state.pool, kb_id)
351 .await?
352 .into_iter()
353 .filter_map(|t| t.iri.clone().map(|i| (i, t.id)))
354 .collect();
355 let relations: HashMap<String, Uuid> = utopia_store::graph::relation_types(&state.pool, kb_id)
356 .await?
357 .into_iter()
358 .filter_map(|r| r.iri.clone().map(|i| (i, r.id)))
359 .collect();
360 let mut link_d: Vec<(Uuid, Uuid)> = Vec::new();
361 let mut link_r: Vec<(Uuid, Uuid)> = Vec::new();
362 for p in &proj.properties {
363 if p.is_datatype {
364 continue;
365 }
366 let Some(&rid) = relations.get(&p.iri) else {
367 continue;
368 };
369 link_d.extend(
370 p.domains
371 .iter()
372 .filter_map(|d| classes.get(d).map(|&t| (rid, t))),
373 );
374 link_r.extend(
375 p.ranges
376 .iter()
377 .filter_map(|r| classes.get(r).map(|&t| (rid, t))),
378 );
379 }
380 utopia_store::ontology::link_domains_ranges_bulk(&state.pool, &link_d, &link_r).await?;
381 Ok((link_d.len(), link_r.len()))
382}
383
384/// 执行计划。属性在类之后落库——它们要挂在 domain 上,而 domain 要等
385/// 类先建好并解析 IRI → id(就是下面那个 `id_of`)。
386pub async fn apply(
387 state: &AppState,
388 kb_id: Uuid,
389 actor: Uuid,
390 filename: &str,
391 bytes: &[u8],
392) -> AppResult<(Uuid, ImportPlan)> {
393 let (plan, proj, format) = plan(state, kb_id, filename, bytes).await?;
394
395 // 第一层:原文按内容寻址进 blob。**先存原文再改本体**——投影失败可以重来,
396 // 原文丢了就永远回不去
397 let sha = sha256_hex(bytes);
398 state
399 .blob
400 .put(&sha, bytes)
401 .await
402 .map_err(utopia_core::AppError::Other)?;
403
404 let by_iri: HashMap<&str, &_> = proj.classes.iter().map(|c| (c.iri.as_str(), c)).collect();
405 // 已在库里的类:IRI → id。Aligned 要靠它把"同义的那个"接上父类引用
406 let existing_by_iri: HashMap<String, Uuid> =
407 utopia_store::graph::entity_types(&state.pool, kb_id)
408 .await?
409 .into_iter()
410 .filter_map(|t| t.iri.clone().map(|i| (i, t.id)))
411 .collect();
412 let mut created_classes = 0usize;
413 let mut updated_classes = 0usize;
414 // IRI → 本体里的 id,父类解析要用
415 let mut id_of: HashMap<String, Uuid> = HashMap::new();
416
417 // **新建的类一次插完,不逐条来。**
418 //
419 // 逐条 `execute(pool)` 每条各自提交,schema.org 那种量级(968 个类加约
420 // 1500 个属性)是五千次 fsync——实测导入 45 秒。同样的行数放进一条
421 // UNNEST 语句是 536 毫秒。Update 与 Aligned 留在下面逐条走:它们在
422 // 空库上是个位数,而且各自要读一次现状,批不起来。
423 let new_classes: Vec<(String, String, String, String)> = plan
424 .classes
425 .iter()
426 .filter(|i| i.disposition == Disposition::Create)
427 .filter_map(|i| by_iri.get(i.iri.as_str()).map(|c| (i, *c)))
428 // key 用 item 的:对齐表判为同名不同义时它是改过的那个
429 .map(|(i, c)| {
430 (
431 i.key.clone(),
432 c.label.clone(),
433 c.description.clone(),
434 c.iri.clone(),
435 )
436 })
437 .collect();
438 let created_ids =
439 utopia_store::ontology::create_entity_types_bulk(&state.pool, kb_id, &new_classes).await?;
440 for (key, label, _, iri) in &new_classes {
441 let _ = label;
442 if let Some(id) = created_ids.get(key) {
443 id_of.insert(iri.clone(), *id);
444 created_classes += 1;
445 }
446 }
447
448 for item in &plan.classes {
449 let Some(c) = by_iri.get(item.iri.as_str()) else {
450 continue;
451 };
452 match item.disposition {
453 // 上面已经批量建好了
454 Disposition::Create => {}
455 Disposition::Update => {
456 // 两种 Update:这个 IRI 上次导过(按 IRI 找得到),
457 // 或者它要认领一个同名的本地类(按 key 找,且那一行还没有 IRI)
458 let updated = utopia_store::ontology::update_type_from_import(
459 &state.pool,
460 kb_id,
461 &c.iri,
462 &c.label,
463 &c.description,
464 )
465 .await?;
466 let id = match updated {
467 Some(id) => Some(id),
468 None => {
469 utopia_store::ontology::adopt_iri_onto_key(
470 &state.pool,
471 kb_id,
472 &c.key,
473 &c.iri,
474 )
475 .await?
476 }
477 };
478 if let Some(id) = id {
479 id_of.insert(c.iri.clone(), id);
480 updated_classes += 1;
481 }
482 }
483 // key 被占:报告过了,不动
484 // 同义:不建。但要把 IRI 指向已有那个类的 id,否则以它为父类的
485 // 子类会解析不到,整棵树在这里断掉
486 Disposition::Aligned => {
487 if let Some(target) = item.conflict_with.as_deref() {
488 if let Some(id) = existing_by_iri.get(target) {
489 id_of.insert(c.iri.clone(), *id);
490 }
491 }
492 }
493 Disposition::KeyTaken => {}
494 }
495 }
496
497 // 父类第二遍解析:第一遍时父类可能还没建出来
498 // (子, 父) 边先攒着,一次插完
499 let mut parent_edges: Vec<(Uuid, Uuid)> = Vec::new();
500 for c in &proj.classes {
501 let Some(&child) = id_of.get(&c.iri) else {
502 continue;
503 };
504 // **全部父类**,不再只取第一个。FOAF 的 Person 同时是 Agent 与
505 // SpatialThing,丢掉后一支就让 domain 在那支上的属性判定不过。
506 // 指向没被建出来的类的那些父自然落选——少一支比整条不挂强
507 let parents: Vec<Uuid> = c
508 .parents
509 .iter()
510 .filter_map(|iri| id_of.get(iri).copied())
511 .collect();
512 parent_edges.extend(parents.into_iter().map(|p| (child, p)));
513 }
514 // 一次插完。单条版每次都跑一个递归 CTE 查环,schema.org 有 975 条父类边,
515 // 就是 975 次递归查询加 975 次提交。
516 //
517 // **批量版不查环。** 单条版对成环的处置本来也只是跳过那一条(`let _ =`),
518 // 不中断导入;而导入完之后本体页仍然能发现并让人处理。用九百多次递归查询
519 // 换一个"发现得早一点",不划算
520 utopia_store::ontology::set_parents_bulk(&state.pool, &parent_edges).await?;
521
522 // 类互斥同理攒一批(见 `relation_types` 的公理列)。指向没被建出来的类的那些自然落选——
523 // 一条互斥声明的两端都得在这个库里,才谈得上拿它判矛盾
524 let mut disjoint_edges: Vec<(Uuid, Uuid)> = Vec::new();
525 for c in &proj.classes {
526 let Some(&a) = id_of.get(&c.iri) else {
527 continue;
528 };
529 for other in &c.disjoint_with {
530 if let Some(&b) = id_of.get(other) {
531 disjoint_edges.push((a, b));
532 }
533 }
534 }
535 utopia_store::ontology::set_disjoint_bulk(&state.pool, kb_id, &disjoint_edges).await?;
536
537 let by_prop_iri: HashMap<&str, &_> = proj
538 .properties
539 .iter()
540 .map(|p| (p.iri.as_str(), p))
541 .collect();
542 // 关系。此前 apply 完全跳过它们——预览却在关系那行写着"N new",
543 // 承诺了不会发生的事。这与今天修掉的 key 撞车缺陷是同一种。
544 //
545 // **functional / inverse_functional 照词汇表的声明写下去**:它们是时态引擎
546 // 自动闭合事实的依据,猜错会成批造假冲突(part_of 那次 59 条)。所以不猜——
547 // 词汇表说是就是,预览已经把它们单独列出来让人过目。
548 let mut created_rels = 0usize;
549 let mut updated_rels = 0usize;
550 let mut new_rels: Vec<utopia_store::ontology::BulkRelation> = Vec::new();
551 // (key, domains, ranges):关系 id 要等批量插完才有,先按 key 记着
552 let mut pending_links: Vec<(String, Vec<Uuid>, Vec<Uuid>)> = Vec::new();
553 for item in &plan.relations {
554 if item.disposition == Disposition::KeyTaken {
555 continue;
556 }
557 let Some(p) = by_prop_iri.get(item.iri.as_str()) else {
558 continue;
559 };
560 // domain/range 指向没被建出来的类时只丢那一个,不丢整条关系:
561 // 关系不像属性那样必须挂在类上,没有 domain 就是"不限主语类型"。
562 //
563 // **库里已有的类也算数。** 从前只认本文件里的类,于是 W3C Org 的
564 // `headOf rdfs:domain foaf:Agent` 在 FOAF 已经装好的库里照样丢 domain,
565 // 而没有 domain 的谓词 `judge_direction` 根本不判方向(#222)
566 let resolve = |iris: &[String]| -> Vec<Uuid> {
567 iris.iter()
568 .filter_map(|i| {
569 id_of
570 .get(i)
571 .copied()
572 .or_else(|| existing_by_iri.get(i).copied())
573 })
574 .collect()
575 };
576 let domains = resolve(&p.domains);
577 let ranges = resolve(&p.ranges);
578
579 if item.disposition == Disposition::Update {
580 if utopia_store::ontology::update_relation_from_import(
581 &state.pool,
582 kb_id,
583 &p.iri,
584 &p.label,
585 &p.description,
586 &domains,
587 &ranges,
588 )
589 .await?
590 {
591 updated_rels += 1;
592 }
593 continue;
594 }
595 // 新建的攒起来一次插——理由同上面的类
596 new_rels.push(utopia_store::ontology::BulkRelation {
597 key: p.key.clone(),
598 label: p.label.clone(),
599 description: p.description.clone(),
600 iri: p.iri.clone(),
601 kind: "relation",
602 datatype: None,
603 functional: p.functional,
604 inverse_functional: p.inverse_functional,
605 transitive: p.transitive,
606 symmetric: p.symmetric,
607 asymmetric: p.asymmetric,
608 irreflexive: p.irreflexive,
609 });
610 pending_links.push((p.key.clone(), domains, ranges));
611 }
612 let rel_ids =
613 utopia_store::ontology::create_relation_types_bulk(&state.pool, kb_id, &new_rels).await?;
614 created_rels += rel_ids.len();
615
616 // 逆与父属性指的是**另一个关系类型**,id 要等全部插完才有——所以是第二遍。
617 // 一遍过只能处理「父属性恰好排在前面」的文件,而 RDF 三元组没有顺序。
618 //
619 // 新建的与已存在的都收:一份本体重导时,这两条声明可能是这次才加上的
620 let mut inv_pairs: Vec<(String, String)> = Vec::new();
621 let mut sub_pairs: Vec<(String, String)> = Vec::new();
622 for item in &plan.relations {
623 let Some(p) = by_prop_iri.get(item.iri.as_str()) else {
624 continue;
625 };
626 if let Some(o) = &p.inverse_of {
627 inv_pairs.push((p.iri.clone(), o.clone()));
628 }
629 if let Some(o) = &p.sub_property_of {
630 sub_pairs.push((p.iri.clone(), o.clone()));
631 }
632 }
633 let (linked_inv, linked_sub) = utopia_store::ontology::link_property_axioms_bulk(
634 &state.pool,
635 kb_id,
636 &inv_pairs,
637 &sub_pairs,
638 )
639 .await?;
640 // 关联行也摊平:单条版对每条关系跑 4 句(两张表各一次 DELETE 一次 INSERT),
641 // 一千五百条关系就是六千次提交
642 let mut link_d: Vec<(Uuid, Uuid)> = Vec::new();
643 let mut link_r: Vec<(Uuid, Uuid)> = Vec::new();
644 for (key, domains, ranges) in &pending_links {
645 let Some(rid) = rel_ids.get(key) else {
646 continue;
647 };
648 link_d.extend(domains.iter().map(|d| (*rid, *d)));
649 link_r.extend(ranges.iter().map(|r| (*rid, *r)));
650 }
651 utopia_store::ontology::link_domains_ranges_bulk(&state.pool, &link_d, &link_r).await?;
652
653 // 属性:类建完、id_of 填好之后才轮到它们。计划里已经算出了每个属性的去向,
654 // **这里只执行,不重新判断**——两处各判一次就会分叉,而分叉意味着
655 // 预览说的和实际做的不是一回事
656 let mut created_attrs = 0usize;
657 let mut new_attrs: Vec<utopia_store::ontology::BulkRelation> = Vec::new();
658 let mut pending_attr_domains: Vec<(String, Vec<Uuid>)> = Vec::new();
659 for item in &plan.attributes {
660 if item.disposition == Disposition::KeyTaken {
661 continue;
662 }
663 let (Some(note), Some(p)) = (item.attr.as_ref(), by_prop_iri.get(item.iri.as_str())) else {
664 continue;
665 };
666 let Some(dt) = attr_datatype(note) else {
667 continue;
668 };
669 // 计划阶段判为可解析、落库时却没有 id 的(类被跳过或更新失败)自然落选;
670 // 全落选就不建,而不是造一个挂空的属性
671 let domain_ids: Vec<Uuid> = p
672 .domains
673 .iter()
674 .filter_map(|iri| id_of.get(iri).copied())
675 .collect();
676 if domain_ids.is_empty() {
677 continue;
678 }
679 new_attrs.push(utopia_store::ontology::BulkRelation {
680 key: p.key.clone(),
681 label: p.label.clone(),
682 description: p.description.clone(),
683 iri: p.iri.clone(),
684 kind: "attribute",
685 datatype: Some(dt.to_string()),
686 // 属性不参与时态闭合,也不参与一致性检查:那几类判定都是关于
687 // **实体之间**的边,而属性的宾语是字面值
688 functional: false,
689 inverse_functional: false,
690 transitive: false,
691 symmetric: false,
692 asymmetric: false,
693 irreflexive: false,
694 });
695 pending_attr_domains.push((p.key.clone(), domain_ids));
696 }
697 let attr_ids =
698 utopia_store::ontology::create_relation_types_bulk(&state.pool, kb_id, &new_attrs).await?;
699 created_attrs += attr_ids.len();
700 let mut attr_links: Vec<(Uuid, Uuid)> = Vec::new();
701 for (key, domains) in &pending_attr_domains {
702 let Some(aid) = attr_ids.get(key) else {
703 continue;
704 };
705 attr_links.extend(domains.iter().map(|d| (*aid, *d)));
706 }
707 utopia_store::ontology::link_domains_ranges_bulk(&state.pool, &attr_links, &[]).await?;
708
709 let summary = serde_json::json!({
710 "classes_created": created_classes,
711 "classes_updated": updated_classes,
712 "classes_key_taken": plan.classes.iter().filter(|c| c.disposition == Disposition::KeyTaken).count(),
713 "relations_seen": plan.relations.len(),
714 // 连上了几条逆 / 父属性。**报出来**——目标 IRI 不在这个库里时会静默跳过
715 // (引用外部词汇表是常态),不给数就没人知道少连了多少
716 "inverse_linked": linked_inv,
717 "sub_property_linked": linked_sub,
718 "relations_created": created_rels,
719 "relations_updated": updated_rels,
720 "attributes_seen": plan.attributes.len(),
721 "attributes_created": created_attrs,
722 "attributes_skipped": plan.attr_skips(),
723 "classes_without_description": plan.classes_without_description,
724 "functional_relations": plan.functional_relations,
725 "unprojected": plan.unprojected.iter().take(30).collect::<Vec<_>>(),
726 "triples": plan.triples,
727 });
728 let import_id = utopia_store::ontology::record_import(
729 &state.pool,
730 kb_id,
731 &sha,
732 filename,
733 &format!("{format:?}").to_lowercase(),
734 bytes.len() as i64,
735 &summary,
736 actor,
737 )
738 .await?;
739
740 let _ = utopia_store::audit::record(
741 &state.pool,
742 Some(kb_id),
743 actor,
744 "ontology.imported",
745 "kb",
746 Some(kb_id),
747 summary,
748 )
749 .await;
750 // 本体刚变过,向量都是陈的。**排任务而不是就地跑**:这一趟要嵌几千行,
751 // 放在导入请求里,用户点完确认要多等六到八分钟。排不上也不要紧——
752 // 索引是自愈的,下一个用到检索的人会补上
753 let _ = utopia_store::jobs::enqueue(
754 &state.pool,
755 "embed_ontology",
756 serde_json::json!({ "kb_id": kb_id }),
757 )
758 .await;
759
760 Ok((import_id, plan))
761}
762
763fn sha256_hex(bytes: &[u8]) -> String {
764 use sha2::{Digest, Sha256};
765 let mut h = Sha256::new();
766 h.update(bytes);
767 h.finalize().iter().map(|b| format!("{b:02x}")).collect()
768}