Elffuss BraidHub

kikocis/utopia public

95c87338cdc8 · 29.8 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 上,而 domain 要等
327/// 类先建好并解析 IRI → id(就是下面那个 `id_of`)。
328pub async fn apply(
329 state: &AppState,
330 kb_id: Uuid,
331 actor: Uuid,
332 filename: &str,
333 bytes: &[u8],
334) -> AppResult<(Uuid, ImportPlan)> {
335 let (plan, proj, format) = plan(state, kb_id, filename, bytes).await?;
336
337 // 第一层:原文按内容寻址进 blob。**先存原文再改本体**——投影失败可以重来,
338 // 原文丢了就永远回不去
339 let sha = sha256_hex(bytes);
340 state
341 .blob
342 .put(&sha, bytes)
343 .await
344 .map_err(utopia_core::AppError::Other)?;
345
346 let by_iri: HashMap<&str, &_> = proj.classes.iter().map(|c| (c.iri.as_str(), c)).collect();
347 // 已在库里的类:IRI → id。Aligned 要靠它把"同义的那个"接上父类引用
348 let existing_by_iri: HashMap<String, Uuid> =
349 utopia_store::graph::entity_types(&state.pool, kb_id)
350 .await?
351 .into_iter()
352 .filter_map(|t| t.iri.clone().map(|i| (i, t.id)))
353 .collect();
354 let mut created_classes = 0usize;
355 let mut updated_classes = 0usize;
356 // IRI → 本体里的 id,父类解析要用
357 let mut id_of: HashMap<String, Uuid> = HashMap::new();
358
359 // **新建的类一次插完,不逐条来。**
360 //
361 // 逐条 `execute(pool)` 每条各自提交,schema.org 那种量级(968 个类加约
362 // 1500 个属性)是五千次 fsync——实测导入 45 秒。同样的行数放进一条
363 // UNNEST 语句是 536 毫秒。Update 与 Aligned 留在下面逐条走:它们在
364 // 空库上是个位数,而且各自要读一次现状,批不起来。
365 let new_classes: Vec<(String, String, String, String)> = plan
366 .classes
367 .iter()
368 .filter(|i| i.disposition == Disposition::Create)
369 .filter_map(|i| by_iri.get(i.iri.as_str()).map(|c| (i, *c)))
370 // key 用 item 的:对齐表判为同名不同义时它是改过的那个
371 .map(|(i, c)| {
372 (
373 i.key.clone(),
374 c.label.clone(),
375 c.description.clone(),
376 c.iri.clone(),
377 )
378 })
379 .collect();
380 let created_ids =
381 utopia_store::ontology::create_entity_types_bulk(&state.pool, kb_id, &new_classes).await?;
382 for (key, label, _, iri) in &new_classes {
383 let _ = label;
384 if let Some(id) = created_ids.get(key) {
385 id_of.insert(iri.clone(), *id);
386 created_classes += 1;
387 }
388 }
389
390 for item in &plan.classes {
391 let Some(c) = by_iri.get(item.iri.as_str()) else {
392 continue;
393 };
394 match item.disposition {
395 // 上面已经批量建好了
396 Disposition::Create => {}
397 Disposition::Update => {
398 // 两种 Update:这个 IRI 上次导过(按 IRI 找得到),
399 // 或者它要认领一个同名的本地类(按 key 找,且那一行还没有 IRI)
400 let updated = utopia_store::ontology::update_type_from_import(
401 &state.pool,
402 kb_id,
403 &c.iri,
404 &c.label,
405 &c.description,
406 )
407 .await?;
408 let id = match updated {
409 Some(id) => Some(id),
410 None => {
411 utopia_store::ontology::adopt_iri_onto_key(
412 &state.pool,
413 kb_id,
414 &c.key,
415 &c.iri,
416 )
417 .await?
418 }
419 };
420 if let Some(id) = id {
421 id_of.insert(c.iri.clone(), id);
422 updated_classes += 1;
423 }
424 }
425 // key 被占:报告过了,不动
426 // 同义:不建。但要把 IRI 指向已有那个类的 id,否则以它为父类的
427 // 子类会解析不到,整棵树在这里断掉
428 Disposition::Aligned => {
429 if let Some(target) = item.conflict_with.as_deref() {
430 if let Some(id) = existing_by_iri.get(target) {
431 id_of.insert(c.iri.clone(), *id);
432 }
433 }
434 }
435 Disposition::KeyTaken => {}
436 }
437 }
438
439 // 父类第二遍解析:第一遍时父类可能还没建出来
440 // (子, 父) 边先攒着,一次插完
441 let mut parent_edges: Vec<(Uuid, Uuid)> = Vec::new();
442 for c in &proj.classes {
443 let Some(&child) = id_of.get(&c.iri) else {
444 continue;
445 };
446 // **全部父类**,不再只取第一个。FOAF 的 Person 同时是 Agent 与
447 // SpatialThing,丢掉后一支就让 domain 在那支上的属性判定不过。
448 // 指向没被建出来的类的那些父自然落选——少一支比整条不挂强
449 let parents: Vec<Uuid> = c
450 .parents
451 .iter()
452 .filter_map(|iri| id_of.get(iri).copied())
453 .collect();
454 parent_edges.extend(parents.into_iter().map(|p| (child, p)));
455 }
456 // 一次插完。单条版每次都跑一个递归 CTE 查环,schema.org 有 975 条父类边,
457 // 就是 975 次递归查询加 975 次提交。
458 //
459 // **批量版不查环。** 单条版对成环的处置本来也只是跳过那一条(`let _ =`),
460 // 不中断导入;而导入完之后本体页仍然能发现并让人处理。用九百多次递归查询
461 // 换一个"发现得早一点",不划算
462 utopia_store::ontology::set_parents_bulk(&state.pool, &parent_edges).await?;
463
464 // 类互斥同理攒一批(见 `relation_types` 的公理列)。指向没被建出来的类的那些自然落选——
465 // 一条互斥声明的两端都得在这个库里,才谈得上拿它判矛盾
466 let mut disjoint_edges: Vec<(Uuid, Uuid)> = Vec::new();
467 for c in &proj.classes {
468 let Some(&a) = id_of.get(&c.iri) else {
469 continue;
470 };
471 for other in &c.disjoint_with {
472 if let Some(&b) = id_of.get(other) {
473 disjoint_edges.push((a, b));
474 }
475 }
476 }
477 utopia_store::ontology::set_disjoint_bulk(&state.pool, kb_id, &disjoint_edges).await?;
478
479 let by_prop_iri: HashMap<&str, &_> = proj
480 .properties
481 .iter()
482 .map(|p| (p.iri.as_str(), p))
483 .collect();
484 // 关系。此前 apply 完全跳过它们——预览却在关系那行写着"N new",
485 // 承诺了不会发生的事。这与今天修掉的 key 撞车缺陷是同一种。
486 //
487 // **functional / inverse_functional 照词汇表的声明写下去**:它们是时态引擎
488 // 自动闭合事实的依据,猜错会成批造假冲突(part_of 那次 59 条)。所以不猜——
489 // 词汇表说是就是,预览已经把它们单独列出来让人过目。
490 let mut created_rels = 0usize;
491 let mut updated_rels = 0usize;
492 let mut new_rels: Vec<utopia_store::ontology::BulkRelation> = Vec::new();
493 // (key, domains, ranges):关系 id 要等批量插完才有,先按 key 记着
494 let mut pending_links: Vec<(String, Vec<Uuid>, Vec<Uuid>)> = Vec::new();
495 for item in &plan.relations {
496 if item.disposition == Disposition::KeyTaken {
497 continue;
498 }
499 let Some(p) = by_prop_iri.get(item.iri.as_str()) else {
500 continue;
501 };
502 // domain/range 指向没被建出来的类时只丢那一个,不丢整条关系:
503 // 关系不像属性那样必须挂在类上,没有 domain 就是"不限主语类型"
504 let resolve = |iris: &[String]| -> Vec<Uuid> {
505 iris.iter().filter_map(|i| id_of.get(i).copied()).collect()
506 };
507 let domains = resolve(&p.domains);
508 let ranges = resolve(&p.ranges);
509
510 if item.disposition == Disposition::Update {
511 if utopia_store::ontology::update_relation_from_import(
512 &state.pool,
513 kb_id,
514 &p.iri,
515 &p.label,
516 &p.description,
517 &domains,
518 &ranges,
519 )
520 .await?
521 {
522 updated_rels += 1;
523 }
524 continue;
525 }
526 // 新建的攒起来一次插——理由同上面的类
527 new_rels.push(utopia_store::ontology::BulkRelation {
528 key: p.key.clone(),
529 label: p.label.clone(),
530 description: p.description.clone(),
531 iri: p.iri.clone(),
532 kind: "relation",
533 datatype: None,
534 functional: p.functional,
535 inverse_functional: p.inverse_functional,
536 transitive: p.transitive,
537 symmetric: p.symmetric,
538 asymmetric: p.asymmetric,
539 irreflexive: p.irreflexive,
540 });
541 pending_links.push((p.key.clone(), domains, ranges));
542 }
543 let rel_ids =
544 utopia_store::ontology::create_relation_types_bulk(&state.pool, kb_id, &new_rels).await?;
545 created_rels += rel_ids.len();
546
547 // 逆与父属性指的是**另一个关系类型**,id 要等全部插完才有——所以是第二遍。
548 // 一遍过只能处理「父属性恰好排在前面」的文件,而 RDF 三元组没有顺序。
549 //
550 // 新建的与已存在的都收:一份本体重导时,这两条声明可能是这次才加上的
551 let mut inv_pairs: Vec<(String, String)> = Vec::new();
552 let mut sub_pairs: Vec<(String, String)> = Vec::new();
553 for item in &plan.relations {
554 let Some(p) = by_prop_iri.get(item.iri.as_str()) else {
555 continue;
556 };
557 if let Some(o) = &p.inverse_of {
558 inv_pairs.push((p.iri.clone(), o.clone()));
559 }
560 if let Some(o) = &p.sub_property_of {
561 sub_pairs.push((p.iri.clone(), o.clone()));
562 }
563 }
564 let (linked_inv, linked_sub) = utopia_store::ontology::link_property_axioms_bulk(
565 &state.pool,
566 kb_id,
567 &inv_pairs,
568 &sub_pairs,
569 )
570 .await?;
571 // 关联行也摊平:单条版对每条关系跑 4 句(两张表各一次 DELETE 一次 INSERT),
572 // 一千五百条关系就是六千次提交
573 let mut link_d: Vec<(Uuid, Uuid)> = Vec::new();
574 let mut link_r: Vec<(Uuid, Uuid)> = Vec::new();
575 for (key, domains, ranges) in &pending_links {
576 let Some(rid) = rel_ids.get(key) else {
577 continue;
578 };
579 link_d.extend(domains.iter().map(|d| (*rid, *d)));
580 link_r.extend(ranges.iter().map(|r| (*rid, *r)));
581 }
582 utopia_store::ontology::link_domains_ranges_bulk(&state.pool, &link_d, &link_r).await?;
583
584 // 属性:类建完、id_of 填好之后才轮到它们。计划里已经算出了每个属性的去向,
585 // **这里只执行,不重新判断**——两处各判一次就会分叉,而分叉意味着
586 // 预览说的和实际做的不是一回事
587 let mut created_attrs = 0usize;
588 let mut new_attrs: Vec<utopia_store::ontology::BulkRelation> = Vec::new();
589 let mut pending_attr_domains: Vec<(String, Vec<Uuid>)> = Vec::new();
590 for item in &plan.attributes {
591 if item.disposition == Disposition::KeyTaken {
592 continue;
593 }
594 let (Some(note), Some(p)) = (item.attr.as_ref(), by_prop_iri.get(item.iri.as_str())) else {
595 continue;
596 };
597 let Some(dt) = attr_datatype(note) else {
598 continue;
599 };
600 // 计划阶段判为可解析、落库时却没有 id 的(类被跳过或更新失败)自然落选;
601 // 全落选就不建,而不是造一个挂空的属性
602 let domain_ids: Vec<Uuid> = p
603 .domains
604 .iter()
605 .filter_map(|iri| id_of.get(iri).copied())
606 .collect();
607 if domain_ids.is_empty() {
608 continue;
609 }
610 new_attrs.push(utopia_store::ontology::BulkRelation {
611 key: p.key.clone(),
612 label: p.label.clone(),
613 description: p.description.clone(),
614 iri: p.iri.clone(),
615 kind: "attribute",
616 datatype: Some(dt.to_string()),
617 // 属性不参与时态闭合,也不参与一致性检查:那几类判定都是关于
618 // **实体之间**的边,而属性的宾语是字面值
619 functional: false,
620 inverse_functional: false,
621 transitive: false,
622 symmetric: false,
623 asymmetric: false,
624 irreflexive: false,
625 });
626 pending_attr_domains.push((p.key.clone(), domain_ids));
627 }
628 let attr_ids =
629 utopia_store::ontology::create_relation_types_bulk(&state.pool, kb_id, &new_attrs).await?;
630 created_attrs += attr_ids.len();
631 let mut attr_links: Vec<(Uuid, Uuid)> = Vec::new();
632 for (key, domains) in &pending_attr_domains {
633 let Some(aid) = attr_ids.get(key) else {
634 continue;
635 };
636 attr_links.extend(domains.iter().map(|d| (*aid, *d)));
637 }
638 utopia_store::ontology::link_domains_ranges_bulk(&state.pool, &attr_links, &[]).await?;
639
640 let summary = serde_json::json!({
641 "classes_created": created_classes,
642 "classes_updated": updated_classes,
643 "classes_key_taken": plan.classes.iter().filter(|c| c.disposition == Disposition::KeyTaken).count(),
644 "relations_seen": plan.relations.len(),
645 // 连上了几条逆 / 父属性。**报出来**——目标 IRI 不在这个库里时会静默跳过
646 // (引用外部词汇表是常态),不给数就没人知道少连了多少
647 "inverse_linked": linked_inv,
648 "sub_property_linked": linked_sub,
649 "relations_created": created_rels,
650 "relations_updated": updated_rels,
651 "attributes_seen": plan.attributes.len(),
652 "attributes_created": created_attrs,
653 "attributes_skipped": plan.attr_skips(),
654 "classes_without_description": plan.classes_without_description,
655 "functional_relations": plan.functional_relations,
656 "unprojected": plan.unprojected.iter().take(30).collect::<Vec<_>>(),
657 "triples": plan.triples,
658 });
659 let import_id = utopia_store::ontology::record_import(
660 &state.pool,
661 kb_id,
662 &sha,
663 filename,
664 &format!("{format:?}").to_lowercase(),
665 bytes.len() as i64,
666 &summary,
667 actor,
668 )
669 .await?;
670
671 let _ = utopia_store::audit::record(
672 &state.pool,
673 Some(kb_id),
674 actor,
675 "ontology.imported",
676 "kb",
677 Some(kb_id),
678 summary,
679 )
680 .await;
681 // 本体刚变过,向量都是陈的。**排任务而不是就地跑**:这一趟要嵌几千行,
682 // 放在导入请求里,用户点完确认要多等六到八分钟。排不上也不要紧——
683 // 索引是自愈的,下一个用到检索的人会补上
684 let _ = utopia_store::jobs::enqueue(
685 &state.pool,
686 "embed_ontology",
687 serde_json::json!({ "kb_id": kb_id }),
688 )
689 .await;
690
691 Ok((import_id, plan))
692}
693
694fn sha256_hex(bytes: &[u8]) -> String {
695 use sha2::{Digest, Sha256};
696 let mut h = Sha256::new();
697 h.update(bytes);
698 h.finalize().iter().map(|b| format!("{b:02x}")).collect()
699}