Elffuss BraidHub

kikocis/utopia public

dev · 68.3 KiBRawPermalink
1//! 本体编辑器仓储:类型/关系 CRUD(带使用量与删除保护)+ 未匹配统计。
2
3use pgvector::Vector;
4use sqlx::PgPool;
5use utopia_core::models::{
6 EntityInstance, EntityTypeView, OntologyImportView, OntologyMiss, RelationAxioms,
7 RelationTypeView, TypeCandidate,
8};
9use utopia_core::{AppError, AppResult};
10use uuid::Uuid;
11
12pub async fn entity_type_views(pool: &PgPool, kb_id: Uuid) -> AppResult<Vec<EntityTypeView>> {
13 Ok(sqlx::query_as(
14 "SELECT t.id, t.key, t.label, t.color, t.shape, t.builtin, t.description,
15 ARRAY(SELECT p.parent_id FROM entity_type_parents p
16 WHERE p.child_id = t.id) AS parents,
17 (SELECT p.parent_id FROM entity_type_parents p
18 WHERE p.child_id = t.id AND p.is_primary) AS primary_parent,
19 ARRAY(SELECT d.b_id FROM entity_type_disjoint d
20 WHERE d.kb_id = t.kb_id AND d.a_id = t.id) AS disjoint,
21 (SELECT count(*) FROM entities e
22 WHERE e.type_id = t.id AND e.merged_into IS NULL) AS usage
23 FROM entity_types t WHERE t.kb_id = $1 ORDER BY lower(t.label)",
24 )
25 .bind(kb_id)
26 .fetch_all(pool)
27 .await?)
28}
29
30/// 某个类下的实体实例(按名称序,分页)。返回 (rows, total)。
31pub async fn entity_instances(
32 pool: &PgPool,
33 kb_id: Uuid,
34 type_id: Uuid,
35 limit: i64,
36 offset: i64,
37) -> AppResult<(Vec<EntityInstance>, i64)> {
38 let rows: Vec<EntityInstance> = sqlx::query_as(
39 "SELECT e.id, e.canonical_name AS name,
40 (SELECT count(*) FROM facts f
41 WHERE (f.subject_id = e.id OR f.object_id = e.id)
42 AND f.invalidated_at IS NULL) AS fact_count
43 FROM entities e
44 WHERE e.kb_id = $1 AND e.type_id = $2 AND e.merged_into IS NULL
45 ORDER BY lower(e.canonical_name)
46 LIMIT $3 OFFSET $4",
47 )
48 .bind(kb_id)
49 .bind(type_id)
50 .bind(limit)
51 .bind(offset)
52 .fetch_all(pool)
53 .await?;
54 let (total,): (i64,) = sqlx::query_as(
55 "SELECT count(*) FROM entities e
56 WHERE e.kb_id = $1 AND e.type_id = $2 AND e.merged_into IS NULL",
57 )
58 .bind(kb_id)
59 .bind(type_id)
60 .fetch_one(pool)
61 .await?;
62 Ok((rows, total))
63}
64
65fn validate_shape(shape: &str) -> AppResult<()> {
66 if !matches!(shape, "circle" | "square") {
67 return Err(AppError::Validation(
68 "shape must be circle or square".into(),
69 ));
70 }
71 Ok(())
72}
73
74pub async fn relation_type_views(pool: &PgPool, kb_id: Uuid) -> AppResult<Vec<RelationTypeView>> {
75 Ok(sqlx::query_as(
76 "SELECT r.id, r.key, r.label, r.temporal, r.functional, r.inverse_functional,
77 r.is_transitive, r.is_symmetric, r.is_asymmetric, r.is_irreflexive,
78 r.inverse_of, r.sub_property_of,
79 r.builtin, r.description,
80 r.kind, r.datatype, r.unit,
81 ARRAY(SELECT d.entity_type_id FROM relation_type_domains d
82 WHERE d.relation_type_id = r.id) AS domains,
83 ARRAY(SELECT g.entity_type_id FROM relation_type_ranges g
84 WHERE g.relation_type_id = r.id) AS ranges,
85 (SELECT count(*) FROM facts f
86 WHERE f.predicate_id = r.id AND f.invalidated_at IS NULL) AS usage
87 FROM relation_types r WHERE r.kb_id = $1 ORDER BY lower(r.label)",
88 )
89 .bind(kb_id)
90 .fetch_all(pool)
91 .await?)
92}
93
94fn validate_key(key: &str) -> AppResult<()> {
95 let ok = !key.is_empty()
96 && key.len() <= 40
97 && key
98 .chars()
99 .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '_');
100 if !ok {
101 return Err(AppError::invalid(
102 "bad_key",
103 "Key must be lowercase snake_case (a-z, 0-9, _), max 40 chars",
104 ));
105 }
106 Ok(())
107}
108
109#[allow(clippy::too_many_arguments)]
110pub async fn create_entity_type(
111 pool: &PgPool,
112 kb_id: Uuid,
113 key: &str,
114 label: &str,
115 color: &str,
116 shape: &str,
117 parents: &[Uuid],
118 description: &str,
119) -> AppResult<Uuid> {
120 validate_key(key)?;
121 validate_shape(shape)?;
122 let id = Uuid::now_v7();
123 sqlx::query(
124 "INSERT INTO entity_types (id, kb_id, key, label, color, shape, description)
125 VALUES ($1, $2, $3, $4, $5, $6, $7)",
126 )
127 .bind(id)
128 .bind(kb_id)
129 .bind(key)
130 .bind(label)
131 .bind(color)
132 .bind(shape)
133 .bind(description)
134 .execute(pool)
135 .await
136 .map_err(|e| match &e {
137 sqlx::Error::Database(db) if db.is_unique_violation() => {
138 AppError::Conflict(format!("Type key '{key}' already exists"))
139 }
140 _ => AppError::Db(e),
141 })?;
142 set_parents(pool, kb_id, id, parents).await?;
143 Ok(id)
144}
145
146#[allow(clippy::too_many_arguments)]
147/// 改一个实体类。
148///
149/// **`color: None` = 保持原色**,不是重置。从前这里是 `&str`,调用方不给就
150/// 写死一个默认灰蓝,于是任何一次不带颜色的改名都会抹掉用户挑过的颜色。
151pub async fn update_entity_type(
152 pool: &PgPool,
153 kb_id: Uuid,
154 id: Uuid,
155 label: &str,
156 color: Option<&str>,
157 shape: &str,
158 parents: &[Uuid],
159 description: &str,
160) -> AppResult<()> {
161 validate_shape(shape)?;
162 let res = sqlx::query(
163 "UPDATE entity_types SET label = $3, color = COALESCE($4, color), shape = $5,
164 description = $6
165 WHERE id = $2 AND kb_id = $1",
166 )
167 .bind(kb_id)
168 .bind(id)
169 .bind(label)
170 .bind(color)
171 .bind(shape)
172 .bind(description)
173 .execute(pool)
174 .await?;
175 if res.rows_affected() == 0 {
176 return Err(AppError::NotFound);
177 }
178 set_parents(pool, kb_id, id, parents).await?;
179 Ok(())
180}
181
182/// 把 `parents` 设成这个类的全部父类,第一个当主父(左栏画在那一支下)。
183///
184/// **先查环再写**。单父时代只需要挡自环,一条链天然不会成环;DAG 里 A→B→A
185/// 完全可能,而 `type_matches_domain` 沿父链上溯,成环就是死循环。
186/// SQL 拦不住这个——外键只挡自环,更长的要应用来查。
187pub async fn set_parents(
188 pool: &PgPool,
189 kb_id: Uuid,
190 child: Uuid,
191 parents: &[Uuid],
192) -> AppResult<()> {
193 if parents.contains(&child) {
194 return Err(AppError::invalid(
195 "self_parent",
196 "A class cannot be its own parent",
197 ));
198 }
199 if !parents.is_empty() {
200 // 候选父类的全部祖先里出现 child,就说明这条边会成环
201 let (cycles,): (i64,) = sqlx::query_as(
202 "WITH RECURSIVE up(id) AS (
203 SELECT unnest($2::uuid[])
204 UNION
205 SELECT p.parent_id FROM entity_type_parents p JOIN up ON p.child_id = up.id
206 )
207 SELECT count(*) FROM up WHERE id = $1",
208 )
209 .bind(child)
210 .bind(parents)
211 .fetch_one(pool)
212 .await?;
213 if cycles > 0 {
214 return Err(AppError::invalid(
215 "parent_cycle",
216 "That parent is already a subclass of this one",
217 ));
218 }
219 }
220 sqlx::query("DELETE FROM entity_type_parents WHERE child_id = $1")
221 .bind(child)
222 .execute(pool)
223 .await?;
224 for (i, p) in parents.iter().enumerate() {
225 sqlx::query(
226 "INSERT INTO entity_type_parents (child_id, parent_id, is_primary)
227 VALUES ($1, $2, $3) ON CONFLICT DO NOTHING",
228 )
229 .bind(child)
230 .bind(p)
231 // 第一个当主父:界面上说明了"画在第一个下面",不再多一个控件
232 .bind(i == 0)
233 .execute(pool)
234 .await?;
235 }
236 let _ = kb_id;
237 Ok(())
238}
239
240pub async fn delete_entity_type(pool: &PgPool, kb_id: Uuid, id: Uuid) -> AppResult<()> {
241 let (usage,): (i64,) = sqlx::query_as("SELECT count(*) FROM entities WHERE type_id = $1")
242 .bind(id)
243 .fetch_one(pool)
244 .await?;
245 if usage > 0 {
246 return Err(AppError::Conflict(format!(
247 "Cannot delete: {usage} entities use this type"
248 )));
249 }
250 // 只剩这一个 domain 的属性随类一起走:属性必须挂在类上,
251 // 留一个没有 domain 的属性等于留一个不会出现在任何地方的死行。
252 // 还挂在别的类上的则只掉一条关联(外键 CASCADE 负责)
253 sqlx::query(
254 "DELETE FROM relation_types r
255 WHERE r.kind = 'attribute' AND r.kb_id = $1
256 AND EXISTS (SELECT 1 FROM relation_type_domains d
257 WHERE d.relation_type_id = r.id AND d.entity_type_id = $2)
258 AND NOT EXISTS (SELECT 1 FROM relation_type_domains d
259 WHERE d.relation_type_id = r.id AND d.entity_type_id <> $2)",
260 )
261 .bind(kb_id)
262 .bind(id)
263 .execute(pool)
264 .await?;
265 let res = sqlx::query("DELETE FROM entity_types WHERE id = $2 AND kb_id = $1 AND NOT builtin")
266 .bind(kb_id)
267 .bind(id)
268 .execute(pool)
269 .await?;
270 if res.rows_affected() == 0 {
271 return Err(AppError::Conflict(
272 "Built-in types cannot be deleted".into(),
273 ));
274 }
275 Ok(())
276}
277
278/// 属性字段校验:attribute 必须有所属类和合法 datatype;relation 三者强制为空。
279fn validate_attribute_fields(
280 kind: &str,
281 domains: &[Uuid],
282 datatype: Option<&str>,
283) -> AppResult<()> {
284 match kind {
285 "relation" => Ok(()),
286 "attribute" => {
287 if domains.is_empty() {
288 return Err(AppError::invalid(
289 "attr_needs_class",
290 "An attribute needs a class (domain)",
291 ));
292 }
293 if !matches!(datatype, Some("text" | "number" | "date" | "bool")) {
294 return Err(AppError::Validation(
295 "datatype must be text / number / date / bool".into(),
296 ));
297 }
298 Ok(())
299 }
300 _ => Err(AppError::Validation(
301 "kind must be relation / attribute".into(),
302 )),
303 }
304}
305
306/// 两条指向别的关系的公理,落库前必须过这里。
307///
308/// **最要紧的一条是同库。** 列上的外键是 `REFERENCES relation_types(id)`,
309/// 它不认知识库——数据库层面,A 库的关系可以指向 B 库的关系。RDF 导入那条路
310/// 天然过不去(按 IRI 在本库里查),而接口收的是裸 UUID:不在这里挡,
311/// 拿到任意一个 UUID 就能让推理机跨库读公理。**不能靠前端只列本库选项**,
312/// 那是界面礼貌,不是边界。
313///
314/// 另外两条:属性没有逆(它的宾语是字面值,反过来无从谈起),
315/// 子属性不能是自己(DB 有 CHECK,但撞上去是 500,得在这里给出人话)。
316/// 而**逆是自己允许**——那等于对称,R0 会提示改用 `symmetric` 更直白,不算错。
317async fn validate_property_links(
318 pool: &PgPool,
319 kb_id: Uuid,
320 self_id: Option<Uuid>,
321 kind: &str,
322 ax: RelationAxioms,
323) -> AppResult<()> {
324 let links = [ax.inverse_of, ax.sub_property_of];
325 if links.iter().all(|l| l.is_none()) {
326 return Ok(());
327 }
328 if kind == "attribute" {
329 return Err(AppError::invalid(
330 "attr_has_no_link",
331 "An attribute cannot have an inverse or a super-property",
332 ));
333 }
334 if self_id.is_some() && ax.sub_property_of == self_id {
335 return Err(AppError::invalid(
336 "sub_property_self",
337 "A relation cannot be its own super-property",
338 ));
339 }
340 for target in links.into_iter().flatten() {
341 let ok: Option<(String,)> =
342 sqlx::query_as("SELECT kind FROM relation_types WHERE id = $1 AND kb_id = $2")
343 .bind(target)
344 .bind(kb_id)
345 .fetch_optional(pool)
346 .await?;
347 match ok {
348 // 不区分「不存在」与「在别的库」:能问出哪个 UUID 存在于别处,
349 // 本身就是一点不该给的信息
350 None => {
351 return Err(AppError::invalid(
352 "unknown_relation",
353 "That relation is not in this knowledge base",
354 ));
355 }
356 Some((k,)) if k != "relation" => {
357 return Err(AppError::invalid(
358 "link_target_is_attr",
359 "An attribute cannot be an inverse or a super-property",
360 ));
361 }
362 Some(_) => {}
363 }
364 }
365 Ok(())
366}
367
368#[allow(clippy::too_many_arguments)]
369pub async fn create_relation_type(
370 pool: &PgPool,
371 kb_id: Uuid,
372 key: &str,
373 label: &str,
374 temporal: &str,
375 ax: RelationAxioms,
376 description: &str,
377 kind: &str,
378 domains: &[Uuid],
379 ranges: &[Uuid],
380 datatype: Option<&str>,
381 unit: Option<&str>,
382) -> AppResult<Uuid> {
383 validate_key(key)?;
384 if !matches!(temporal, "state" | "event" | "eternal") {
385 return Err(AppError::Validation(
386 "temporal must be state / event / eternal".into(),
387 ));
388 }
389 validate_attribute_fields(kind, domains, datatype)?;
390 // 新建的行 id 还不存在,指向自己无从谈起——所以 self_id 传 None
391 validate_property_links(pool, kb_id, None, kind, ax).await?;
392 let is_attr = kind == "attribute";
393 let id = Uuid::now_v7();
394 sqlx::query(
395 "INSERT INTO relation_types (id, kb_id, key, label, temporal,
396 functional, inverse_functional, description,
397 kind, datatype, unit,
398 is_transitive, is_symmetric,
399 is_asymmetric, is_irreflexive,
400 inverse_of, sub_property_of)
401 VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15,
402 $16, $17)",
403 )
404 .bind(id)
405 .bind(kb_id)
406 .bind(key)
407 .bind(label)
408 .bind(temporal)
409 .bind(ax.functional)
410 .bind(ax.inverse_functional)
411 .bind(description)
412 .bind(kind)
413 .bind(is_attr.then_some(datatype).flatten())
414 .bind(is_attr.then_some(unit).flatten())
415 .bind(ax.transitive)
416 .bind(ax.symmetric)
417 .bind(ax.asymmetric)
418 .bind(ax.irreflexive)
419 // 属性不带这两条(上面已经拦了非空的情况,这里是兜底)
420 .bind(if is_attr { None } else { ax.inverse_of })
421 .bind(if is_attr { None } else { ax.sub_property_of })
422 .execute(pool)
423 .await
424 .map_err(|e| match &e {
425 sqlx::Error::Database(db) if db.is_unique_violation() => {
426 AppError::Conflict(format!("Relation key '{key}' already exists"))
427 }
428 _ => AppError::Db(e),
429 })?;
430 // attribute 不写 range:它的值域是字面量类型,落在 datatype 上
431 set_domains_ranges(pool, id, domains, if is_attr { &[] } else { ranges }).await?;
432 Ok(id)
433}
434
435/// 覆盖式写入 domain / range。**先删后插**,所以它既能用于新建也能用于重导入,
436/// 且不会留下上一轮的残余。
437async fn set_domains_ranges(
438 pool: &PgPool,
439 relation_type_id: Uuid,
440 domains: &[Uuid],
441 ranges: &[Uuid],
442) -> AppResult<()> {
443 for (table, ids) in [
444 ("relation_type_domains", domains),
445 ("relation_type_ranges", ranges),
446 ] {
447 sqlx::query(&format!("DELETE FROM {table} WHERE relation_type_id = $1"))
448 .bind(relation_type_id)
449 .execute(pool)
450 .await?;
451 if ids.is_empty() {
452 continue;
453 }
454 // unnest 一次插完,省去逐条往返
455 sqlx::query(&format!(
456 "INSERT INTO {table} (relation_type_id, entity_type_id)
457 SELECT $1, x FROM unnest($2::uuid[]) AS x
458 ON CONFLICT DO NOTHING"
459 ))
460 .bind(relation_type_id)
461 .bind(ids)
462 .execute(pool)
463 .await?;
464 }
465 Ok(())
466}
467
468#[allow(clippy::too_many_arguments)]
469pub async fn update_relation_type(
470 pool: &PgPool,
471 kb_id: Uuid,
472 id: Uuid,
473 label: &str,
474 temporal: &str,
475 ax: RelationAxioms,
476 description: &str,
477 datatype: Option<&str>,
478 unit: Option<&str>,
479 // None = 不动。不管 domain 的调用方(属性表单)传 None,
480 // 否则一次不相干的改名就会把属性的 domain 清空
481 domains: Option<&[Uuid]>,
482 ranges: Option<&[Uuid]>,
483) -> AppResult<()> {
484 if !matches!(temporal, "state" | "event" | "eternal") {
485 return Err(AppError::Validation(
486 "temporal must be state / event / eternal".into(),
487 ));
488 }
489 if datatype.is_some() && !matches!(datatype, Some("text" | "number" | "date" | "bool")) {
490 return Err(AppError::Validation(
491 "datatype must be text / number / date / bool".into(),
492 ));
493 }
494 // 指向别的关系的两条要先问过库:目标在不在本库、是不是关系。
495 // 只在真的填了的时候查——清空(两个都 None)没有目标可验
496 if ax.inverse_of.is_some() || ax.sub_property_of.is_some() {
497 let row: Option<(String,)> =
498 sqlx::query_as("SELECT kind FROM relation_types WHERE id = $1 AND kb_id = $2")
499 .bind(id)
500 .bind(kb_id)
501 .fetch_optional(pool)
502 .await?;
503 let (kind,) = row.ok_or(AppError::NotFound)?;
504 validate_property_links(pool, kb_id, Some(id), &kind, ax).await?;
505 }
506 // kind 不可变(改它会让存量事实语义错乱)。domain/range 可改——
507 // 它们是签名不是身份,"这个属性也适用于承包商" 是个正当的编辑。
508 // datatype/unit 只对 attribute 行生效,datatype 缺省保持原值
509 //
510 // 两条链**跟着六位公理一起覆盖式写**:缺省 = 清空,不是「不动」。
511 // 与 `is_transitive` 那几位同一条规矩——它们是同一个表单里同时提交的
512 // 一组声明,一半覆盖一半保留才是真正会出事的语义
513 let res = sqlx::query(
514 "UPDATE relation_types
515 SET label = $3, temporal = $4,
516 functional = $5, inverse_functional = $6, description = $7,
517 datatype = CASE WHEN kind = 'attribute' AND $8 IS NOT NULL THEN $8 ELSE datatype END,
518 unit = CASE WHEN kind = 'attribute' THEN $9 ELSE unit END,
519 is_transitive = $10, is_symmetric = $11,
520 is_asymmetric = $12, is_irreflexive = $13,
521 inverse_of = $14, sub_property_of = $15
522 WHERE id = $2 AND kb_id = $1",
523 )
524 .bind(kb_id)
525 .bind(id)
526 .bind(label)
527 .bind(temporal)
528 .bind(ax.functional)
529 .bind(ax.inverse_functional)
530 .bind(description)
531 .bind(datatype)
532 .bind(unit)
533 .bind(ax.transitive)
534 .bind(ax.symmetric)
535 .bind(ax.asymmetric)
536 .bind(ax.irreflexive)
537 .bind(ax.inverse_of)
538 .bind(ax.sub_property_of)
539 .execute(pool)
540 .await?;
541 if res.rows_affected() == 0 {
542 return Err(AppError::NotFound);
543 }
544 if domains.is_some() || ranges.is_some() {
545 let (kind,): (String,) = sqlx::query_as("SELECT kind FROM relation_types WHERE id = $1")
546 .bind(id)
547 .fetch_one(pool)
548 .await?;
549 let next_domains = domains.unwrap_or(&[]);
550 if kind == "attribute" && next_domains.is_empty() {
551 return Err(AppError::invalid(
552 "attr_needs_class",
553 "An attribute needs a class (domain)",
554 ));
555 }
556 // 属性没有 range:它的值域是字面量类型,落在 datatype 上
557 let next_ranges: &[Uuid] = if kind == "attribute" {
558 &[]
559 } else {
560 ranges.unwrap_or(&[])
561 };
562 set_domains_ranges(pool, id, next_domains, next_ranges).await?;
563 }
564 Ok(())
565}
566
567pub async fn delete_relation_type(pool: &PgPool, kb_id: Uuid, id: Uuid) -> AppResult<()> {
568 let (usage,): (i64,) = sqlx::query_as("SELECT count(*) FROM facts WHERE predicate_id = $1")
569 .bind(id)
570 .fetch_one(pool)
571 .await?;
572 if usage > 0 {
573 return Err(AppError::Conflict(format!(
574 "Cannot delete: {usage} facts use this relation"
575 )));
576 }
577 let res =
578 sqlx::query("DELETE FROM relation_types WHERE id = $2 AND kb_id = $1 AND NOT builtin")
579 .bind(kb_id)
580 .bind(id)
581 .execute(pool)
582 .await?;
583 if res.rows_affected() == 0 {
584 return Err(AppError::Conflict(
585 "Built-in relations cannot be deleted".into(),
586 ));
587 }
588 Ok(())
589}
590
591/* ---- 未匹配统计 ---- */
592
593pub async fn record_miss(
594 pool: &PgPool,
595 kb_id: Uuid,
596 kind: &str,
597 key: &str,
598 example: Option<&str>,
599) -> AppResult<()> {
600 sqlx::query(
601 // **被拒绝过的照样累加。**
602 //
603 // 从前这里带着 `WHERE dismissed_at IS NULL`,理由是"否则计数会把'不要'
604 // 重新顶成一个待处理信号"。那个理由针对的是**呈现**,用的手段却是
605 // **停止计数**——两件事被绑在一起了,代价是一次点击变成永久失明:
606 // 第一篇里出现一次的说法被忽略掉,后面二十篇都在用它,计数仍停在 1,
607 // 谁也不知道当初那个判断已经不成立,那批事实永远没有谓词。
608 //
609 // 用户是对**当时看得见的证据**做的判断,不是对所有时间。所以计数照记,
610 // 抑制交给读取侧:`list_misses` 仍然只返回未忽略的,提案与自动扩本体
611 // 一步没变;已忽略的连同更新后的计数走 `list_dismissed_misses`,
612 // 在面板上单列一处,人看见涨到 40 了可以自己撤回
613 "INSERT INTO ontology_misses (kb_id, kind, key, example)
614 VALUES ($1, $2, left($3, 80), left($4, 200))
615 ON CONFLICT (kb_id, kind, key)
616 DO UPDATE SET count = ontology_misses.count + 1,
617 example = COALESCE(EXCLUDED.example, ontology_misses.example),
618 updated_at = now()",
619 )
620 .bind(kb_id)
621 .bind(kind)
622 .bind(key)
623 .bind(example)
624 .execute(pool)
625 .await?;
626 Ok(())
627}
628
629pub async fn list_misses(pool: &PgPool, kb_id: Uuid) -> AppResult<Vec<OntologyMiss>> {
630 Ok(sqlx::query_as(
631 "SELECT kind, key, example, count FROM ontology_misses
632 WHERE kb_id = $1 AND dismissed_at IS NULL
633 ORDER BY count DESC, updated_at DESC LIMIT 50",
634 )
635 .bind(kb_id)
636 .fetch_all(pool)
637 .await?)
638}
639
640/// 已被忽略的说法,连同**它此后继续累积的计数**。
641///
642/// 存在的理由是忽略这个动作曾经是单向门:点下去之后既不再呈现、也不再计数,
643/// 于是"当时只出现过一次"这个判断依据一旦过期,没有任何人看得见。
644/// 这个列表是那扇门上的窗——抑制照旧,但看得见抑制掉的是什么、现在有多重。
645pub async fn list_dismissed_misses(pool: &PgPool, kb_id: Uuid) -> AppResult<Vec<OntologyMiss>> {
646 Ok(sqlx::query_as(
647 "SELECT kind, key, example, count FROM ontology_misses
648 WHERE kb_id = $1 AND dismissed_at IS NOT NULL
649 ORDER BY count DESC, updated_at DESC LIMIT 50",
650 )
651 .bind(kb_id)
652 .fetch_all(pool)
653 .await?)
654}
655
656/// 撤回一次忽略:这个说法重新进入提案与自动扩本体。
657pub async fn restore_miss(pool: &PgPool, kb_id: Uuid, kind: &str, key: &str) -> AppResult<()> {
658 sqlx::query(
659 "UPDATE ontology_misses SET dismissed_at = NULL, updated_at = now()
660 WHERE kb_id = $1 AND kind = $2 AND key = $3 AND dismissed_at IS NOT NULL",
661 )
662 .bind(kb_id)
663 .bind(kind)
664 .bind(key)
665 .execute(pool)
666 .await?;
667 Ok(())
668}
669
670/// 用户说"不要这个"。**标记而非删除**——删掉的话下一次抽取遇到同一个词
671/// 原样插回来,用户的拒绝活不过一轮抽取。自动扩展路径也据此绕开。
672///
673/// 可撤回(见 [`restore_miss`]),且撤回之后计数是连续的——忽略期间照样在记。
674pub async fn dismiss_miss(pool: &PgPool, kb_id: Uuid, kind: &str, key: &str) -> AppResult<()> {
675 sqlx::query(
676 "UPDATE ontology_misses SET dismissed_at = now()
677 WHERE kb_id = $1 AND kind = $2 AND key = $3 AND dismissed_at IS NULL",
678 )
679 .bind(kb_id)
680 .bind(kind)
681 .bind(key)
682 .execute(pool)
683 .await?;
684 Ok(())
685}
686
687/// 本体已经覆盖了这个说法(采纳时调用):与"用户拒绝"不同,这条真的可以清掉,
688/// 下次抽取它会命中本体,不再是未匹配。
689pub async fn clear_miss(pool: &PgPool, kb_id: Uuid, kind: &str, key: &str) -> AppResult<()> {
690 sqlx::query("DELETE FROM ontology_misses WHERE kb_id = $1 AND kind = $2 AND key = $3")
691 .bind(kb_id)
692 .bind(kind)
693 .bind(key)
694 .execute(pool)
695 .await?;
696 Ok(())
697}
698
699/* ---- OWL 导入 ---- */
700
701/// 建一个带 IRI 的类。IRI 是全局身份,重导入据它匹配(见 0001 P2)。
702pub async fn create_entity_type_with_iri(
703 pool: &PgPool,
704 kb_id: Uuid,
705 key: &str,
706 label: &str,
707 description: &str,
708 iri: &str,
709) -> AppResult<Uuid> {
710 validate_key(key)?;
711 let id = Uuid::now_v7();
712 sqlx::query(
713 "INSERT INTO entity_types (id, kb_id, key, label, color, shape, description, iri)
714 VALUES ($1, $2, $3, $4, $7, $8, $5, $6)",
715 )
716 .bind(id)
717 .bind(kb_id)
718 .bind(key)
719 .bind(label)
720 .bind(description)
721 .bind(iri)
722 // 按 key 取色而不是所有类一个灰蓝——导入一个大本体进来才有得看
723 .bind(crate::palette::color_for_key(key))
724 // 形状说明来历:这条路带 IRI,就是词表声明的
725 .bind(crate::palette::shape_for(iri))
726 .execute(pool)
727 .await
728 .map_err(|e| match &e {
729 sqlx::Error::Database(db) if db.is_unique_violation() => {
730 AppError::Conflict(format!("Type key '{key}' already exists"))
731 }
732 _ => AppError::Db(e),
733 })?;
734 Ok(id)
735}
736
737/// 重导入时按 IRI 更新标签与描述。**key 不动**——它可能已经被抽取出的实体
738/// 和提示词引用,改它等于把已有数据的引用打断;上游改 label 是常态,
739/// 而 IRI 才是身份。
740pub async fn update_type_from_import(
741 pool: &PgPool,
742 kb_id: Uuid,
743 iri: &str,
744 label: &str,
745 description: &str,
746) -> AppResult<Option<Uuid>> {
747 let row: Option<(Uuid,)> = sqlx::query_as(
748 "UPDATE entity_types
749 SET label = $3,
750 -- 空描述不覆盖已有的:上游可能没写 rdfs:comment,而本地可能
751 -- 已经被人按自己的语料调过,那份调整比空值有价值
752 description = CASE WHEN $4 = '' THEN description ELSE $4 END
753 WHERE kb_id = $1 AND iri = $2 RETURNING id",
754 )
755 .bind(kb_id)
756 .bind(iri)
757 .bind(label)
758 .bind(description)
759 .fetch_optional(pool)
760 .await?;
761 Ok(row.map(|(id,)| id))
762}
763
764/// 设父类。自环与已是该父类的情形静默跳过。
765/// 从导入建一个属性(`kind='attribute'`),带 IRI。
766///
767/// 与 [`create_relation_type`] 的区别只在多了 `iri` 与 key 冲突的处置:
768/// 导入按 IRI 认身份,key 撞了是"两个不同的东西争一个短标签",
769/// 由调用方在计划阶段报告并跳过,到这里不该再撞——所以冲突时返回 None
770/// 而不是覆盖,让调用方把它计进"跳过"。
771///
772/// `temporal` 固定 `state`:属性是随时间变化的取值(薪资、人数),
773/// 新值闭合旧值正是我们要的。OWL 里没有对应概念,猜 event 或 eternal 都更差。
774#[allow(clippy::too_many_arguments)]
775pub async fn create_attribute_with_iri(
776 pool: &PgPool,
777 kb_id: Uuid,
778 key: &str,
779 label: &str,
780 description: &str,
781 iri: &str,
782 domains: &[Uuid],
783 datatype: &str,
784) -> AppResult<Option<Uuid>> {
785 validate_key(key)?;
786 let id = Uuid::now_v7();
787 let row: Option<(Uuid,)> = sqlx::query_as(
788 "INSERT INTO relation_types
789 (id, kb_id, key, label, temporal, functional, inverse_functional,
790 description, kind, datatype, iri)
791 VALUES ($1, $2, $3, $4, 'state', FALSE, FALSE, $5, 'attribute', $6, $7)
792 ON CONFLICT (kb_id, key) DO NOTHING
793 RETURNING id",
794 )
795 .bind(id)
796 .bind(kb_id)
797 .bind(key)
798 .bind(label)
799 .bind(description)
800 .bind(datatype)
801 .bind(iri)
802 .fetch_optional(pool)
803 .await?;
804 let Some((new_id,)) = row else {
805 return Ok(None);
806 };
807 set_domains_ranges(pool, new_id, domains, &[]).await?;
808 Ok(Some(new_id))
809}
810
811/// 从导入建一个关系(`kind='relation'`),带 IRI。
812///
813/// `temporal` 固定 `state`:OWL 没有对应概念,而 state(有区间)是三者里唯一
814/// 不丢信息的——event 会把区间压成时点,eternal 会宣称它永不改变。
815///
816/// **`functional` / `inverse_functional` 照词汇表写**。它们驱动时态引擎自动闭合
817/// 旧事实,猜错就成批造假冲突(`part_of` 那次 59 条)。预览已经把声明为函数性的
818/// 关系单独列出来让人过目,所以这里不再自作主张改成 false。
819#[allow(clippy::too_many_arguments)]
820pub async fn create_relation_with_iri(
821 pool: &PgPool,
822 kb_id: Uuid,
823 key: &str,
824 label: &str,
825 description: &str,
826 iri: &str,
827 functional: bool,
828 inverse_functional: bool,
829 domains: &[Uuid],
830 ranges: &[Uuid],
831) -> AppResult<Option<Uuid>> {
832 validate_key(key)?;
833 let id = Uuid::now_v7();
834 let row: Option<(Uuid,)> = sqlx::query_as(
835 "INSERT INTO relation_types
836 (id, kb_id, key, label, temporal, functional, inverse_functional,
837 description, kind, iri)
838 VALUES ($1, $2, $3, $4, 'state', $5, $6, $7, 'relation', $8)
839 ON CONFLICT (kb_id, key) DO NOTHING
840 RETURNING id",
841 )
842 .bind(id)
843 .bind(kb_id)
844 .bind(key)
845 .bind(label)
846 .bind(functional)
847 .bind(inverse_functional)
848 .bind(description)
849 .bind(iri)
850 .fetch_optional(pool)
851 .await?;
852 let Some((new_id,)) = row else {
853 return Ok(None);
854 };
855 set_domains_ranges(pool, new_id, domains, ranges).await?;
856 Ok(Some(new_id))
857}
858
859/// 重导入时更新一个已按 IRI 认下的关系。
860///
861/// **key 不动**(它可能已被事实引用),**空描述不覆盖**(人写过的比上游的准),
862/// **domain/range 整体重写**——它们是上游声明的结构,不是人调过的措辞。
863pub async fn update_relation_from_import(
864 pool: &PgPool,
865 kb_id: Uuid,
866 iri: &str,
867 label: &str,
868 description: &str,
869 domains: &[Uuid],
870 ranges: &[Uuid],
871) -> AppResult<bool> {
872 let row: Option<(Uuid,)> = sqlx::query_as(
873 "UPDATE relation_types
874 SET label = $3,
875 description = CASE WHEN $4 = '' THEN description ELSE $4 END
876 WHERE kb_id = $1 AND iri = $2
877 RETURNING id",
878 )
879 .bind(kb_id)
880 .bind(iri)
881 .bind(label)
882 .bind(description)
883 .fetch_optional(pool)
884 .await?;
885 let Some((id,)) = row else {
886 return Ok(false);
887 };
888 set_domains_ranges(pool, id, domains, ranges).await?;
889 Ok(true)
890}
891
892/// 记一次导入。原文已按内容寻址存进 blob,这里只记账。
893#[allow(clippy::too_many_arguments)]
894pub async fn record_import(
895 pool: &PgPool,
896 kb_id: Uuid,
897 sha256: &str,
898 filename: &str,
899 format: &str,
900 byte_size: i64,
901 summary: &serde_json::Value,
902 actor: Uuid,
903) -> AppResult<Uuid> {
904 let id = Uuid::now_v7();
905 sqlx::query(
906 "INSERT INTO ontology_imports
907 (id, kb_id, sha256, filename, format, byte_size, summary, imported_by)
908 VALUES ($1, $2, $3, $4, $5, $6, $7, $8)",
909 )
910 .bind(id)
911 .bind(kb_id)
912 .bind(sha256)
913 .bind(filename)
914 .bind(format)
915 .bind(byte_size)
916 .bind(summary)
917 .bind(actor)
918 .execute(pool)
919 .await?;
920 Ok(id)
921}
922
923/// 一个库的导入历史(带导入人显示名;删号后为 NULL)。
924pub async fn list_imports(pool: &PgPool, kb_id: Uuid) -> AppResult<Vec<OntologyImportView>> {
925 Ok(sqlx::query_as(
926 "SELECT i.id, i.filename, i.format, i.byte_size, i.summary, i.imported_at,
927 u.display_name AS imported_by_name
928 FROM ontology_imports i
929 LEFT JOIN users u ON u.id = i.imported_by
930 WHERE i.kb_id = $1 ORDER BY i.imported_at DESC LIMIT 50",
931 )
932 .bind(kb_id)
933 .fetch_all(pool)
934 .await?)
935}
936
937/// 一条待嵌入的本体行。`text` 是要送去嵌入的那段字,`kind` 决定回写哪张表。
938#[derive(Debug, Clone)]
939pub struct TypeToEmbed {
940 pub id: Uuid,
941 pub kind: TypeKind,
942 pub text: String,
943 /// 写进哪一组列。类有两份向量:整段(label + 描述)与只有 label 的那份,
944 /// 分别服务长画像与短说法两种查询(见 `entity_types.label_embedding`)
945 pub field: EmbedField,
946}
947
948/// 同一行的两份向量。**短查询比 Label,长画像比 Full**——查询分了两种形状,
949/// 文档也得分两种,否则短查询会被同义反复的类接管(`Map\nA map.` 那一类)。
950#[derive(Debug, Clone, Copy, PartialEq, Eq)]
951pub enum EmbedField {
952 Full,
953 Label,
954}
955
956/// 本体行属于哪张表。类进 `entity_types`,关系与属性同住 `relation_types`。
957#[derive(Debug, Clone, Copy, PartialEq, Eq)]
958pub enum TypeKind {
959 Entity,
960 Relation,
961}
962
963/// 嵌入用的那段字:标签在前、描述在后。
964///
965/// **key 不进去。** key 是模型读写的令牌(`founding_date`),描述才是这个类型
966/// 的意思所在。把 key 混进来,检索会被"两个 key 长得像"带偏——而
967/// `position`(列表位次)与 `position`(职位)正是长得一模一样的两回事。
968fn embed_text(label: &str, description: &str) -> String {
969 let d = description.trim();
970 if d.is_empty() {
971 label.trim().to_string()
972 } else {
973 format!("{}\n{}", label.trim(), d)
974 }
975}
976
977/// 哪些本体行的向量是陈的(没嵌过、描述改了、或换了嵌入模型)。
978///
979/// 判据是**比对当时嵌的原文与模型名**,不是看时间戳:描述改了、模型换了,
980/// 时间戳一样看不出来。这样也不必在每个改描述的写入点挂钩子——漏一个就悄悄烂掉。
981///
982/// `only` 限定只补一半。类型消解只用类,让它等 1633 个关系嵌完是白等六分钟;
983/// 而后台那个补齐任务不限,两边补的是同一批行,谁先跑到都算数。
984pub async fn types_needing_embedding(
985 pool: &PgPool,
986 kb_id: Uuid,
987 model: &str,
988 only: Option<TypeKind>,
989) -> AppResult<Vec<TypeToEmbed>> {
990 let mut out = Vec::new();
991 if only == Some(TypeKind::Relation) {
992 // 类型消解只用类,等 1633 个关系嵌完是白等六分钟
993 return relations_needing_embedding(pool, kb_id, model).await;
994 }
995 let ents: Vec<(Uuid, String, String)> = sqlx::query_as(
996 "SELECT id, label, coalesce(description, '') FROM entity_types
997 WHERE kb_id = $1
998 AND (embedding IS NULL
999 OR embedded_model IS DISTINCT FROM $2
1000 OR embedded_text IS DISTINCT FROM
1001 CASE WHEN coalesce(btrim(description), '') = '' THEN btrim(label)
1002 ELSE btrim(label) || E'\n' || btrim(description) END)",
1003 )
1004 .bind(kb_id)
1005 .bind(model)
1006 .fetch_all(pool)
1007 .await?;
1008 out.extend(ents.into_iter().map(|(id, label, desc)| TypeToEmbed {
1009 id,
1010 kind: TypeKind::Entity,
1011 text: embed_text(&label, &desc),
1012 field: EmbedField::Full,
1013 }));
1014 // 只嵌 label 的那一份(见 `entity_types.label_embedding`)。短查询走这个索引——查询分了两种形状,
1015 // 文档也得分两种,否则短查询被同义反复的类接管
1016 let labels: Vec<(Uuid, String)> = sqlx::query_as(
1017 "SELECT id, label FROM entity_types
1018 WHERE kb_id = $1
1019 AND (label_embedding IS NULL
1020 OR label_embedded_model IS DISTINCT FROM $2
1021 OR label_embedded_text IS DISTINCT FROM btrim(label))",
1022 )
1023 .bind(kb_id)
1024 .bind(model)
1025 .fetch_all(pool)
1026 .await?;
1027 out.extend(labels.into_iter().map(|(id, label)| TypeToEmbed {
1028 id,
1029 kind: TypeKind::Entity,
1030 text: label.trim().to_string(),
1031 field: EmbedField::Label,
1032 }));
1033 if only == Some(TypeKind::Entity) {
1034 return Ok(out);
1035 }
1036 out.extend(relations_needing_embedding(pool, kb_id, model).await?);
1037 Ok(out)
1038}
1039
1040async fn relations_needing_embedding(
1041 pool: &PgPool,
1042 kb_id: Uuid,
1043 model: &str,
1044) -> AppResult<Vec<TypeToEmbed>> {
1045 let mut out = Vec::new();
1046 let rels: Vec<(Uuid, String, String)> = sqlx::query_as(
1047 "SELECT id, label, coalesce(description, '') FROM relation_types
1048 WHERE kb_id = $1
1049 AND (embedding IS NULL
1050 OR embedded_model IS DISTINCT FROM $2
1051 OR embedded_text IS DISTINCT FROM
1052 CASE WHEN coalesce(btrim(description), '') = '' THEN btrim(label)
1053 ELSE btrim(label) || E'\n' || btrim(description) END)",
1054 )
1055 .bind(kb_id)
1056 .bind(model)
1057 .fetch_all(pool)
1058 .await?;
1059 out.extend(rels.into_iter().map(|(id, label, desc)| TypeToEmbed {
1060 id,
1061 kind: TypeKind::Relation,
1062 text: embed_text(&label, &desc),
1063 // 关系没有短查询那一路,只有整段这一份
1064 field: EmbedField::Full,
1065 }));
1066 Ok(out)
1067}
1068
1069/// 回写向量,连同"嵌的是哪段字、用的哪个模型"。三者必须同一次写入——
1070/// 只写向量而不写来源,下一轮就会认为它还是陈的,从此每轮重嵌。
1071pub async fn set_type_embeddings(
1072 pool: &PgPool,
1073 model: &str,
1074 items: &[(TypeToEmbed, Vec<f32>)],
1075) -> AppResult<()> {
1076 let mut tx = pool.begin().await?;
1077 for (item, emb) in items {
1078 let table = match item.kind {
1079 TypeKind::Entity => "entity_types",
1080 TypeKind::Relation => "relation_types",
1081 };
1082 // 两份向量各写各的列(见 `entity_types.label_embedding`)。列名前缀不同,其余一模一样
1083 let (vec_col, text_col, model_col) = match item.field {
1084 EmbedField::Full => ("embedding", "embedded_text", "embedded_model"),
1085 EmbedField::Label => (
1086 "label_embedding",
1087 "label_embedded_text",
1088 "label_embedded_model",
1089 ),
1090 };
1091 sqlx::query(&format!(
1092 "UPDATE {table} SET {vec_col} = $2, {text_col} = $3, {model_col} = $4
1093 WHERE id = $1"
1094 ))
1095 .bind(item.id)
1096 .bind(Vector::from(emb.clone()))
1097 .bind(&item.text)
1098 .bind(model)
1099 .execute(&mut *tx)
1100 .await?;
1101 }
1102 tx.commit().await?;
1103 Ok(())
1104}
1105
1106/// 与给定向量最近的 k 个实体类型。
1107///
1108/// **既没有描述、又不在分类树上的类不参加。** 导入一份词表时,凡被
1109/// domainIncludes / rangeIncludes / equivalentClass 引用到的外部 IRI 都会建成一行
1110/// (OMG、UNECE、GS1…),它们没有标签正文、没有父也没有子——不是词汇,是悬空引用。
1111///
1112/// 它们偏偏很能赢:`embed_text` 在描述为空时退化成只嵌标签,于是这一行嵌的
1113/// 就是 "Location" 一个词。短的那一侧距离系统性地更小(同一条规律在这个文件
1114/// 和类型消解里已经栽过三次),于是一个空壳压过了带 83 字定义的
1115/// `administrative_area`——实测 `杭州拱墅区` 正是这么丢的。
1116///
1117/// 而且就算端上去也判不了:裁决看到的是 `- location (location)`,没有定义可依。
1118/// 装 schema.org 的库里这样的行有 50 个,43 个连一条继承边都没有。
1119///
1120/// **只是不当候选,不删行**:domain / range 仍然指着它们,删了会断引用。
1121pub async fn nearest_entity_types(
1122 pool: &PgPool,
1123 kb_id: Uuid,
1124 embedding: &[f32],
1125 limit: i64,
1126 // true = 比只有 label 的那份向量(见 `entity_types.label_embedding`)。短说法走这一路:**短对短**,
1127 // 否则 `district. place` 会被 `Map\nA map.` 这类同义反复的一行话赢过去
1128 by_label: bool,
1129) -> AppResult<Vec<TypeCandidate>> {
1130 let col = if by_label {
1131 "label_embedding"
1132 } else {
1133 "embedding"
1134 };
1135 let rows: Vec<(Uuid, String, String, String, f64)> = sqlx::query_as(&format!(
1136 "SELECT id, key, label, coalesce(description, ''), ({col} <=> $2)::float8
1137 FROM entity_types t
1138 WHERE t.kb_id = $1 AND t.{col} IS NOT NULL
1139 AND (coalesce(btrim(t.description), '') <> ''
1140 OR EXISTS (SELECT 1 FROM entity_type_parents p
1141 WHERE p.child_id = t.id OR p.parent_id = t.id))
1142 ORDER BY {col} <=> $2
1143 LIMIT $3"
1144 ))
1145 .bind(kb_id)
1146 .bind(Vector::from(embedding.to_vec()))
1147 .bind(limit)
1148 .fetch_all(pool)
1149 .await?;
1150 Ok(rows
1151 .into_iter()
1152 .map(|(id, key, label, description, distance)| TypeCandidate {
1153 id,
1154 key,
1155 label,
1156 description,
1157 kind: None,
1158 distance: distance as f32,
1159 })
1160 .collect())
1161}
1162
1163/// 与给定向量最近的 k 个关系/属性。
1164///
1165/// `only_kind` 分道:字面值宾语的事实要找的是属性,实体宾语的要找的是关系。
1166/// 不分道就会把 `founding_date` 这种属性推给一条关系事实,反过来也一样。
1167pub async fn nearest_relation_types(
1168 pool: &PgPool,
1169 kb_id: Uuid,
1170 embedding: &[f32],
1171 limit: i64,
1172 only_kind: Option<&str>,
1173) -> AppResult<Vec<TypeCandidate>> {
1174 let rows: Vec<(Uuid, String, String, String, String, f64)> = sqlx::query_as(
1175 "SELECT id, key, label, coalesce(description, ''), kind, (embedding <=> $2)::float8
1176 FROM relation_types
1177 WHERE kb_id = $1 AND embedding IS NOT NULL
1178 AND ($4::text IS NULL OR kind = $4)
1179 ORDER BY embedding <=> $2
1180 LIMIT $3",
1181 )
1182 .bind(kb_id)
1183 .bind(Vector::from(embedding.to_vec()))
1184 .bind(limit)
1185 .bind(only_kind)
1186 .fetch_all(pool)
1187 .await?;
1188 Ok(rows
1189 .into_iter()
1190 .map(
1191 |(id, key, label, description, kind, distance)| TypeCandidate {
1192 id,
1193 key,
1194 label,
1195 description,
1196 kind: Some(kind),
1197 distance: distance as f32,
1198 },
1199 )
1200 .collect())
1201}
1202
1203/// 按 key 找关系/属性的 id。给"映射到已有类型"那条路用。
1204///
1205/// 不区分 kind:属性与关系同住一张表且共用 key 命名空间,调用方拿到 id 之后
1206/// 该怎么用它自己清楚(改写事实时谓词就是谓词)。
1207pub async fn relation_type_id_by_key(
1208 pool: &PgPool,
1209 kb_id: Uuid,
1210 key: &str,
1211) -> AppResult<Option<Uuid>> {
1212 let row: Option<(Uuid,)> =
1213 sqlx::query_as("SELECT id FROM relation_types WHERE kb_id = $1 AND key = $2")
1214 .bind(kb_id)
1215 .bind(key)
1216 .fetch_optional(pool)
1217 .await?;
1218 Ok(row.map(|(id,)| id))
1219}
1220
1221/// 一个属性声明的 datatype。改写字面值事实时要按它换算。
1222///
1223/// 以**库里这一条**为准而不是以请求为准:指向已有属性时请求里根本没有
1224/// datatype,而即便有,本体说了算。
1225pub async fn relation_type_datatype(pool: &PgPool, id: Uuid) -> AppResult<Option<String>> {
1226 let row: Option<(Option<String>,)> =
1227 sqlx::query_as("SELECT datatype FROM relation_types WHERE id = $1")
1228 .bind(id)
1229 .fetch_optional(pool)
1230 .await?;
1231 Ok(row.and_then(|(d,)| d))
1232}
1233
1234/// 把一个 IRI 认到已有的**本地**类上(原本没有 IRI 的那种)。
1235///
1236/// **只写 IRI 与形状,不动 label、description、颜色。** 认领要解决的是
1237/// "这棵树是断的",不是"用词汇表的说法覆盖用户的说法":种子类的描述是照着
1238/// 抽取调过的、且跟库的语言走,而 schema.org 的描述是英文样板。覆盖它等于
1239/// 悄悄换掉抽取提示词里最承重的那一句。
1240///
1241/// **形状要跟着改,因为形状说的就是来历**(方=词表声明的,圆=语料里长的)。
1242/// 一个类被认领成"词表声明的"却还画成圆,画面就在说谎。实测过这个缝:
1243/// 往一个已有 `person` / `organization` 的库里导 schema.org,
1244/// 那几个类拿到了 IRI 却仍是圆的——有 IRI 却是圆的,自相矛盾。
1245///
1246/// 颜色不动:颜色是**身份**(同一个 key 永远同一个色),认领不改变它是谁。
1247/// 形状是**来历**,认领恰恰改变了这一点。
1248///
1249/// 只在 `iri IS NULL` 时写,所以重复导入是幂等的,也绝不会抢走另一个
1250/// 词汇表已经认领的类。
1251pub async fn adopt_iri_onto_key(
1252 pool: &PgPool,
1253 kb_id: Uuid,
1254 key: &str,
1255 iri: &str,
1256) -> AppResult<Option<Uuid>> {
1257 let row: Option<(Uuid,)> = sqlx::query_as(
1258 "UPDATE entity_types SET iri = $3, shape = 'square'
1259 WHERE kb_id = $1 AND key = $2 AND iri IS NULL
1260 RETURNING id",
1261 )
1262 .bind(kb_id)
1263 .bind(key)
1264 .bind(iri)
1265 .fetch_optional(pool)
1266 .await?;
1267 Ok(row.map(|(id,)| id))
1268}
1269
1270/// 与给定向量最近的若干**类 id**(只回 id,调用方手里已有类的全量数据)。
1271///
1272/// 给抽取用:分块向量在抽取循环里本来就有(实体消解在用),拿它检索出这一块
1273/// 可能用得上的类,只把这些铺进提示词。
1274pub async fn nearest_entity_type_ids(
1275 pool: &PgPool,
1276 kb_id: Uuid,
1277 embedding: &[f32],
1278 limit: i64,
1279) -> AppResult<Vec<Uuid>> {
1280 let rows: Vec<(Uuid,)> = sqlx::query_as(
1281 "SELECT id FROM entity_types
1282 WHERE kb_id = $1 AND embedding IS NOT NULL
1283 ORDER BY embedding <=> $2
1284 LIMIT $3",
1285 )
1286 .bind(kb_id)
1287 .bind(Vector::from(embedding.to_vec()))
1288 .bind(limit)
1289 .fetch_all(pool)
1290 .await?;
1291 Ok(rows.into_iter().map(|(id,)| id).collect())
1292}
1293
1294/// 同上,关系与属性。`only_kind` 分道:关系清单与属性清单在提示词里是两段。
1295pub async fn nearest_relation_type_ids(
1296 pool: &PgPool,
1297 kb_id: Uuid,
1298 embedding: &[f32],
1299 limit: i64,
1300 only_kind: Option<&str>,
1301) -> AppResult<Vec<Uuid>> {
1302 let rows: Vec<(Uuid,)> = sqlx::query_as(
1303 "SELECT id FROM relation_types
1304 WHERE kb_id = $1 AND embedding IS NOT NULL
1305 AND ($4::text IS NULL OR kind = $4)
1306 ORDER BY embedding <=> $2
1307 LIMIT $3",
1308 )
1309 .bind(kb_id)
1310 .bind(Vector::from(embedding.to_vec()))
1311 .bind(limit)
1312 .bind(only_kind)
1313 .fetch_all(pool)
1314 .await?;
1315 Ok(rows.into_iter().map(|(id,)| id).collect())
1316}
1317
1318/// 一次插完一批类,返回 key → id。
1319///
1320/// **存在的理由是 fsync。** 逐条 `execute(pool)` 每条各自提交,导入 schema.org
1321/// 那种量级(968 个类加约 1500 个属性)是五千次 fsync,实测 45 秒;同样的行数
1322/// 放进一条语句是 536 毫秒。差的不是往返,是提交。
1323///
1324/// `ON CONFLICT DO NOTHING` 而不是报错:撞 key 的处置在计划阶段已经判过了
1325/// ([`crate::ontology::create_entity_type_with_iri`] 的注释讲了为什么不覆盖),
1326/// 这里只是把计划落地,撞上说明计划与库不同步,跳过并让调用方从返回的 map 里
1327/// 发现少了谁。
1328pub async fn create_entity_types_bulk(
1329 pool: &PgPool,
1330 kb_id: Uuid,
1331 rows: &[(String, String, String, String)],
1332) -> AppResult<std::collections::HashMap<String, Uuid>> {
1333 if rows.is_empty() {
1334 return Ok(std::collections::HashMap::new());
1335 }
1336 for (key, ..) in rows {
1337 validate_key(key)?;
1338 }
1339 let keys: Vec<&str> = rows.iter().map(|r| r.0.as_str()).collect();
1340 let labels: Vec<&str> = rows.iter().map(|r| r.1.as_str()).collect();
1341 let descs: Vec<&str> = rows.iter().map(|r| r.2.as_str()).collect();
1342 let iris: Vec<&str> = rows.iter().map(|r| r.3.as_str()).collect();
1343 // 颜色在 Rust 侧按 key 算好,跟着 UNNEST 一起进去——
1344 // SQL 里调不到 Rust 函数,而这一批正是导入大本体走的路
1345 let colours: Vec<&str> = keys
1346 .iter()
1347 .map(|k| crate::palette::color_for_key(k))
1348 .collect();
1349 let shapes: Vec<&str> = iris.iter().map(|i| crate::palette::shape_for(i)).collect();
1350 let out: Vec<(Uuid, String)> = sqlx::query_as(
1351 "INSERT INTO entity_types (id, kb_id, key, label, color, shape, description, iri)
1352 SELECT gen_random_uuid(), $1, k, l, c, s, d, i
1353 FROM UNNEST($2::text[], $3::text[], $4::text[], $5::text[], $6::text[], $7::text[])
1354 AS t(k, l, d, i, c, s)
1355 ON CONFLICT (kb_id, key) DO NOTHING
1356 RETURNING id, key",
1357 )
1358 .bind(kb_id)
1359 .bind(&keys)
1360 .bind(&labels)
1361 .bind(&descs)
1362 .bind(&iris)
1363 .bind(&colours)
1364 .bind(&shapes)
1365 .fetch_all(pool)
1366 .await?;
1367 Ok(out.into_iter().map(|(id, k)| (k, id)).collect())
1368}
1369
1370/// 批量建关系/属性时的一行。
1371///
1372/// **`functional` / `inverse_functional` 必须照词汇表写下去,不能默认 false。**
1373/// 它们是时态引擎自动闭合事实的依据,猜错会成批造假冲突——`part_of` 被误标成
1374/// functional 那次积了 59 条。
1375pub struct BulkRelation {
1376 pub key: String,
1377 pub label: String,
1378 pub description: String,
1379 pub iri: String,
1380 /// `relation` 或 `attribute`
1381 pub kind: &'static str,
1382 /// 只对属性有意义,关系传 `None`
1383 pub datatype: Option<String>,
1384 pub functional: bool,
1385 pub inverse_functional: bool,
1386 /// OWL 属性公理,一致性检查的判定依据(0002 R0)。
1387 /// 同样必须照词汇表写下去——`alias_of` 双向是对的、`produces` 双向是错的,
1388 /// 分开这两者的只能是本体
1389 pub transitive: bool,
1390 pub symmetric: bool,
1391 pub asymmetric: bool,
1392 pub irreflexive: bool,
1393}
1394
1395/// 一次插完一批关系或属性,返回 key → id。语义同 [`create_entity_types_bulk`]。
1396///
1397/// `kind` 决定走关系通道还是属性通道;`datatype` 只对属性有意义,关系传 `None`。
1398/// `temporal` 固定 `state`——OWL 里没有对应概念,猜 event 或 eternal 都更差
1399/// (与单条版的判断一致)。
1400pub async fn create_relation_types_bulk(
1401 pool: &PgPool,
1402 kb_id: Uuid,
1403 rows: &[BulkRelation],
1404) -> AppResult<std::collections::HashMap<String, Uuid>> {
1405 if rows.is_empty() {
1406 return Ok(std::collections::HashMap::new());
1407 }
1408 for r in rows {
1409 validate_key(&r.key)?;
1410 }
1411 let keys: Vec<&str> = rows.iter().map(|r| r.key.as_str()).collect();
1412 let labels: Vec<&str> = rows.iter().map(|r| r.label.as_str()).collect();
1413 let descs: Vec<&str> = rows.iter().map(|r| r.description.as_str()).collect();
1414 let iris: Vec<&str> = rows.iter().map(|r| r.iri.as_str()).collect();
1415 let kinds: Vec<&str> = rows.iter().map(|r| r.kind).collect();
1416 let dts: Vec<Option<&str>> = rows.iter().map(|r| r.datatype.as_deref()).collect();
1417 let funcs: Vec<bool> = rows.iter().map(|r| r.functional).collect();
1418 let invs: Vec<bool> = rows.iter().map(|r| r.inverse_functional).collect();
1419 let trans: Vec<bool> = rows.iter().map(|r| r.transitive).collect();
1420 let syms: Vec<bool> = rows.iter().map(|r| r.symmetric).collect();
1421 let asyms: Vec<bool> = rows.iter().map(|r| r.asymmetric).collect();
1422 let irrefs: Vec<bool> = rows.iter().map(|r| r.irreflexive).collect();
1423 let out: Vec<(Uuid, String)> = sqlx::query_as(
1424 "INSERT INTO relation_types
1425 (id, kb_id, key, label, temporal, functional, inverse_functional,
1426 description, kind, datatype, iri,
1427 is_transitive, is_symmetric, is_asymmetric, is_irreflexive)
1428 SELECT gen_random_uuid(), $1, k, l, 'state', fu, iv, d, kind, dt, i,
1429 tr, sy, asym, irr
1430 FROM UNNEST($2::text[], $3::text[], $4::text[], $5::text[], $6::text[], $7::text[],
1431 $8::bool[], $9::bool[], $10::bool[], $11::bool[], $12::bool[], $13::bool[])
1432 AS t(k, l, d, i, kind, dt, fu, iv, tr, sy, asym, irr)
1433 ON CONFLICT (kb_id, key) DO NOTHING
1434 RETURNING id, key",
1435 )
1436 .bind(kb_id)
1437 .bind(&keys)
1438 .bind(&labels)
1439 .bind(&descs)
1440 .bind(&iris)
1441 .bind(&kinds)
1442 .bind(&dts)
1443 .bind(&funcs)
1444 .bind(&invs)
1445 .bind(&trans)
1446 .bind(&syms)
1447 .bind(&asyms)
1448 .bind(&irrefs)
1449 .fetch_all(pool)
1450 .await?;
1451 Ok(out.into_iter().map(|(id, k)| (k, id)).collect())
1452}
1453
1454/// 一次写完一批关系的 domain / range。
1455///
1456/// 单条版 [`set_domains_ranges`] 内部已经用 unnest 省了往返,但它对**每条关系**
1457/// 都要跑 4 条语句(两张表各一次 DELETE 一次 INSERT)。1500 条关系就是 6000 次
1458/// 独立提交,而提交才是代价。这里把所有关系的关联行摊平成两条语句。
1459///
1460/// **不 DELETE**:调用方是刚建出来的新关系,关联表上不可能有旧行。
1461/// 更新既有关系仍然走单条版。
1462pub async fn link_domains_ranges_bulk(
1463 pool: &PgPool,
1464 domains: &[(Uuid, Uuid)],
1465 ranges: &[(Uuid, Uuid)],
1466) -> AppResult<()> {
1467 for (table, pairs) in [
1468 ("relation_type_domains", domains),
1469 ("relation_type_ranges", ranges),
1470 ] {
1471 if pairs.is_empty() {
1472 continue;
1473 }
1474 let rels: Vec<Uuid> = pairs.iter().map(|p| p.0).collect();
1475 let types: Vec<Uuid> = pairs.iter().map(|p| p.1).collect();
1476 sqlx::query(&format!(
1477 "INSERT INTO {table} (relation_type_id, entity_type_id)
1478 SELECT r, t FROM UNNEST($1::uuid[], $2::uuid[]) AS x(r, t)
1479 ON CONFLICT DO NOTHING"
1480 ))
1481 .bind(&rels)
1482 .bind(&types)
1483 .execute(pool)
1484 .await?;
1485 }
1486 Ok(())
1487}
1488
1489/// 一次设完一批类的父类。语义同 [`set_parents`],但**不查环**。
1490///
1491/// 单条版每次都要跑一个递归 CTE 查环,一千个类就是一千次递归查询。
1492/// 这里只用于导入新建的类:环是上游词汇表的问题,而 `set_parents` 对环的处置
1493/// 本来也只是跳过那一条(`let _ =`),不是中断导入。导入完之后本体页
1494/// 仍然能发现并让人处理。
1495pub async fn set_parents_bulk(pool: &PgPool, pairs: &[(Uuid, Uuid)]) -> AppResult<()> {
1496 if pairs.is_empty() {
1497 return Ok(());
1498 }
1499 let children: Vec<Uuid> = pairs.iter().map(|p| p.0).collect();
1500 let parents: Vec<Uuid> = pairs.iter().map(|p| p.1).collect();
1501 sqlx::query(
1502 "INSERT INTO entity_type_parents (child_id, parent_id)
1503 SELECT c, p FROM UNNEST($1::uuid[], $2::uuid[]) AS x(c, p)
1504 WHERE c <> p
1505 ON CONFLICT DO NOTHING",
1506 )
1507 .bind(&children)
1508 .bind(&parents)
1509 .execute(pool)
1510 .await?;
1511 Ok(())
1512}
1513
1514/// 类互斥落库(见 `relation_types` 的公理列)。语义同 [`set_parents_bulk`]。
1515///
1516/// **两个方向都写。** 解析侧已经把 `owl:disjointWith` 的对称性展开成两条,
1517/// 这里照写即可——查"A 与 B 互斥吗"因此不必关心从哪一头问。
1518///
1519/// `a <> b` 挡自指:自己跟自己互斥是无意义的声明,而它会让一致性检查
1520/// 把每个实体都报成矛盾。表上也有同样的 CHECK,两道都留着——
1521/// 约束是最后一道,过滤在这里是为了不让一整批插入因为一条脏数据整个失败。
1522pub async fn set_disjoint_bulk(
1523 pool: &PgPool,
1524 kb_id: Uuid,
1525 pairs: &[(Uuid, Uuid)],
1526) -> AppResult<()> {
1527 if pairs.is_empty() {
1528 return Ok(());
1529 }
1530 let a: Vec<Uuid> = pairs.iter().map(|p| p.0).collect();
1531 let b: Vec<Uuid> = pairs.iter().map(|p| p.1).collect();
1532 sqlx::query(
1533 "INSERT INTO entity_type_disjoint (kb_id, a_id, b_id)
1534 SELECT $1, x, y FROM UNNEST($2::uuid[], $3::uuid[]) AS t(x, y)
1535 WHERE x <> y
1536 ON CONFLICT DO NOTHING",
1537 )
1538 .bind(kb_id)
1539 .bind(&a)
1540 .bind(&b)
1541 .execute(pool)
1542 .await?;
1543 Ok(())
1544}
1545
1546/// 把 `others` 设成这个类的**全部**互斥对象(不在其中的解除)。
1547///
1548/// 与 [`set_disjoint_bulk`] 的分工:那个是导入用的「只增不减」,这个是编辑用的
1549/// 「这就是全部」。编辑必须能取消——否则界面上取消勾选没有任何效果,
1550/// 而用户会以为自己改了。
1551///
1552/// 两个方向各写一行,与导入侧一致:查「A 与 B 互斥吗」因此不必关心从哪头问。
1553pub async fn set_disjoint_for(
1554 pool: &PgPool,
1555 kb_id: Uuid,
1556 class: Uuid,
1557 others: &[Uuid],
1558) -> AppResult<()> {
1559 let mut tx = pool.begin().await?;
1560 // 先清掉这个类参与的全部互斥边——两个方向都要清,因为它两边都可能出现
1561 sqlx::query(
1562 "DELETE FROM entity_type_disjoint
1563 WHERE kb_id = $1 AND (a_id = $2 OR b_id = $2)",
1564 )
1565 .bind(kb_id)
1566 .bind(class)
1567 .execute(&mut *tx)
1568 .await?;
1569 for other in others {
1570 if *other == class {
1571 continue;
1572 }
1573 sqlx::query(
1574 "INSERT INTO entity_type_disjoint (kb_id, a_id, b_id)
1575 VALUES ($1, $2, $3), ($1, $3, $2)
1576 ON CONFLICT DO NOTHING",
1577 )
1578 .bind(kb_id)
1579 .bind(class)
1580 .bind(other)
1581 .execute(&mut *tx)
1582 .await?;
1583 }
1584 tx.commit().await?;
1585 Ok(())
1586}
1587
1588// ---------------------------------------------------------------------------
1589// 本体提案(见 `ontology_proposals`)
1590// ---------------------------------------------------------------------------
1591
1592/// 一条落库的提案。`payload` 是接口原样返回的那一条。
1593#[derive(Debug, Clone, sqlx::FromRow)]
1594pub struct StoredProposal {
1595 pub section: String,
1596 pub key: String,
1597 pub payload: serde_json::Value,
1598}
1599
1600/// 把一轮 Suggest 的结果写下来。
1601///
1602/// **已经有人表过态的不动。** `WHERE status = 'open'` 那一句是这个函数的全部要点:
1603/// 重跑 Suggest 会再次算出被拒绝过的那条提案(原材料还在 `ontology_misses` 里),
1604/// 不加这句它就会被刷回 open——等于每跑一次都把人的否决抹掉一次。
1605pub async fn save_proposals(
1606 pool: &PgPool,
1607 kb_id: Uuid,
1608 items: &[(String, String, serde_json::Value)],
1609) -> AppResult<()> {
1610 for (section, key, payload) in items {
1611 sqlx::query(
1612 "INSERT INTO ontology_proposals (id, kb_id, section, key, payload)
1613 VALUES ($1, $2, $3, $4, $5)
1614 ON CONFLICT (kb_id, section, key) DO UPDATE
1615 SET payload = EXCLUDED.payload, created_at = now()
1616 WHERE ontology_proposals.status = 'open'",
1617 )
1618 .bind(Uuid::now_v7())
1619 .bind(kb_id)
1620 .bind(section)
1621 .bind(key)
1622 .bind(payload)
1623 .execute(pool)
1624 .await?;
1625 }
1626 Ok(())
1627}
1628
1629/// 还等着人看的提案。新的排前面——旧的那批已经被看过好几眼了。
1630pub async fn open_proposals(pool: &PgPool, kb_id: Uuid) -> AppResult<Vec<StoredProposal>> {
1631 Ok(sqlx::query_as(
1632 "SELECT section, key, payload FROM ontology_proposals
1633 WHERE kb_id = $1 AND status = 'open'
1634 ORDER BY created_at DESC, key",
1635 )
1636 .bind(kb_id)
1637 .fetch_all(pool)
1638 .await?)
1639}
1640
1641/// 一条提案被采纳或拒绝了。
1642///
1643/// **改状态而不是删行**:采纳发生过、拒绝也发生过。跟 `fact_adoptions`、
1644/// `entity_retypes` 同一条路。拒绝留痕还有个当下就用得着的作用——下一轮
1645/// Suggest 不会把它刷回待看。
1646pub async fn decide_proposal(
1647 pool: &PgPool,
1648 kb_id: Uuid,
1649 section: &str,
1650 key: &str,
1651 status: &str,
1652 actor: Uuid,
1653) -> AppResult<()> {
1654 sqlx::query(
1655 "UPDATE ontology_proposals
1656 SET status = $4, decided_by = $5, decided_at = now()
1657 WHERE kb_id = $1 AND section = $2 AND key = $3 AND status = 'open'",
1658 )
1659 .bind(kb_id)
1660 .bind(section)
1661 .bind(key)
1662 .bind(status)
1663 .bind(actor)
1664 .execute(pool)
1665 .await?;
1666 Ok(())
1667}
1668
1669/// 还有多少条等着看。0003 的缺口:关掉自动扩展开关之后没有「自上次以来有 N 条」
1670/// 的提醒,信号在面板里但没人主动看——有了这张表,提醒就是这一句。
1671pub async fn open_proposal_count(pool: &PgPool, kb_id: Uuid) -> AppResult<i64> {
1672 let (n,): (i64,) = sqlx::query_as(
1673 "SELECT count(*) FROM ontology_proposals WHERE kb_id = $1 AND status = 'open'",
1674 )
1675 .bind(kb_id)
1676 .fetch_one(pool)
1677 .await?;
1678 Ok(n)
1679}
1680
1681/// 主语的类型合不合这个关系声明的 domain。沿继承链往上找。
1682///
1683/// **只回答,不动数据。** 0001 已经判过:签名是提示不是闸门,
1684/// 「用可能错的声明驱动自动动作风险高」。而实体类型本身也是模型判出来的
1685/// (实测里 Elon Musk 被判成 `researcher`),拿它去翻转事实方向,
1686/// 是两层不确定叠在一起还静默改写。所以这里的结果只用来落一条信号。
1687///
1688/// 三种回答,别混成两种:
1689/// - `Some(true)` 合
1690/// - `Some(false)` 不合——**这才是信号**
1691/// - `None` 没得判(关系没声明 domain,或实体还没有类型)
1692pub async fn subject_fits_domain(
1693 pool: &PgPool,
1694 relation_type_id: Uuid,
1695 subject_type_id: Option<Uuid>,
1696) -> AppResult<Option<bool>> {
1697 let Some(subject_type_id) = subject_type_id else {
1698 return Ok(None);
1699 };
1700 let (declared, ok): (i64, i64) = sqlx::query_as(
1701 "WITH RECURSIVE up(id) AS (
1702 SELECT $2::uuid
1703 UNION
1704 SELECT p.parent_id FROM entity_type_parents p JOIN up ON p.child_id = up.id
1705 )
1706 SELECT (SELECT count(*) FROM relation_type_domains WHERE relation_type_id = $1),
1707 (SELECT count(*) FROM relation_type_domains d
1708 JOIN up ON up.id = d.entity_type_id
1709 WHERE d.relation_type_id = $1)",
1710 )
1711 .bind(relation_type_id)
1712 .bind(subject_type_id)
1713 .fetch_one(pool)
1714 .await?;
1715 Ok((declared > 0).then_some(ok > 0))
1716}
1717
1718/// 这些类的全部祖先(不含自己)。沿 `subClassOf` 上溯,多继承与菱形都走得通。
1719///
1720/// 给按块检索的候选补地板用:向量检索偏爱字面出现在正文里的叶子类,
1721/// 泛化基类排得很后(实测 `person` 在 976 个类里排第 359),于是提示词里
1722/// 没有它们——实体无处落脚,关系签名也退化成 `*`。祖先是本体自己声明的
1723/// 泛化关系,拿它补比维护一张「通用类」清单可靠。
1724pub async fn ancestors_of(pool: &PgPool, ids: &[Uuid]) -> AppResult<Vec<Uuid>> {
1725 if ids.is_empty() {
1726 return Ok(Vec::new());
1727 }
1728 // 递归项里 UNION 去重,菱形继承不会把同一个祖先展开两次
1729 let rows: Vec<(Uuid,)> = sqlx::query_as(
1730 "WITH RECURSIVE up(id) AS (
1731 SELECT unnest($1::uuid[])
1732 UNION
1733 SELECT p.parent_id FROM entity_type_parents p JOIN up ON p.child_id = up.id
1734 )
1735 SELECT id FROM up WHERE id <> ALL($1::uuid[])",
1736 )
1737 .bind(ids)
1738 .fetch_all(pool)
1739 .await?;
1740 Ok(rows.into_iter().map(|(id,)| id).collect())
1741}
1742
1743/// 同 [`subject_fits_domain`],但类型**从库里的实体读**,不靠调用方手上那份。
1744///
1745/// 抽取器手上的 `entity_type_of` 只覆盖模型在这一块里声明过的实体;宾语常常
1746/// 是别处已经存在的实体,这一块没重新声明它的类型,于是查不到、判不了。
1747/// 而消解已经把它连到了库里那一行——那里有类型,用它才判得全。
1748pub async fn entity_fits_domain(
1749 pool: &PgPool,
1750 relation_type_id: Uuid,
1751 entity_id: Uuid,
1752) -> AppResult<Option<bool>> {
1753 let (declared, ok): (i64, i64) = sqlx::query_as(
1754 "WITH RECURSIVE up(id) AS (
1755 SELECT type_id FROM entities WHERE id = $2
1756 UNION
1757 SELECT p.parent_id FROM entity_type_parents p JOIN up ON p.child_id = up.id
1758 )
1759 SELECT (SELECT count(*) FROM relation_type_domains WHERE relation_type_id = $1),
1760 (SELECT count(*) FROM relation_type_domains d
1761 JOIN up ON up.id = d.entity_type_id
1762 WHERE d.relation_type_id = $1)",
1763 )
1764 .bind(relation_type_id)
1765 .bind(entity_id)
1766 .fetch_one(pool)
1767 .await?;
1768 Ok((declared > 0).then_some(ok > 0))
1769}
1770
1771/// 一条 (主语, 谓词, 宾语) 对着谓词的 domain 签名该怎么落。
1772#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1773pub enum Fit {
1774 /// 谓词没声明 domain——没有判据,照原样落
1775 Unchecked,
1776 /// 主语符合
1777 Keep,
1778 /// 主语不符合、宾语符合:按签名对调主宾
1779 Swap,
1780 /// 两边都不符合:这个关系不适用于这对实体,谓词该留空
1781 Neither,
1782}
1783
1784/// **三条写谓词的路共用的那一道判断**(#190 / #196):抽取落新事实、采纳把谓词
1785/// 挂回旧事实、合并换掉主语——从前只有抽取查,另外两条各自绕了过去。
1786///
1787/// 判据刻意窄(0012):只看签名,只在**正向违反而反向成立**时对调,两个方向都
1788/// 对不上就留空谓词。参数顺序不是关于世界的断言,是这个 key 的编码约定,所以本体
1789/// 在这一处是执法的;哪些类型能参与仍是引导,不在这里裁。
1790///
1791/// **range 也算进来**(#222)。从前只看 domain:`headOf` 的 domain 是 Agent,
1792/// schema.org 里 Project 也是 Organization 也是 Agent,于是 `Project Aurora head_of
1793/// Li Ting` 主语过关就 Keep,宾语是个人、range 要 Organization 这件事没人看。
1794/// 现在两端各看各的:正向两端都不违反才 Keep;否则反过来两端都不违反才 Swap。
1795/// 没判出类型的实体在 range 这一端不算违反("不知道"不是"不符合",与
1796/// `signature_breaks` 同一条纪律);domain 那一端沿用旧规矩,那是 0012 定下的
1797pub async fn judge_direction(
1798 pool: &PgPool,
1799 relation_type_id: Uuid,
1800 subject_id: Uuid,
1801 object_id: Uuid,
1802) -> AppResult<Fit> {
1803 let subject_in_domain = entity_fits_domain(pool, relation_type_id, subject_id).await?;
1804 let object_in_range = entity_fits_range(pool, relation_type_id, object_id).await?;
1805 if subject_in_domain.is_none() && object_in_range.is_none() {
1806 return Ok(Fit::Unchecked);
1807 }
1808 if subject_in_domain != Some(false) && object_in_range != Some(false) {
1809 return Ok(Fit::Keep);
1810 }
1811 let object_in_domain = entity_fits_domain(pool, relation_type_id, object_id).await?;
1812 let subject_in_range = entity_fits_range(pool, relation_type_id, subject_id).await?;
1813 if object_in_domain != Some(false) && subject_in_range != Some(false) {
1814 return Ok(Fit::Swap);
1815 }
1816 Ok(Fit::Neither)
1817}
1818
1819/// [`entity_fits_domain`] 的 range 版。多一条规矩:实体还没判出类型 → None,
1820/// 不当违反——range 这一端是新加的判据(#222),不该让未分类实体的事实因此
1821/// 丢掉谓词
1822pub async fn entity_fits_range(
1823 pool: &PgPool,
1824 relation_type_id: Uuid,
1825 entity_id: Uuid,
1826) -> AppResult<Option<bool>> {
1827 let (declared, typed, ok): (i64, bool, i64) = sqlx::query_as(
1828 "WITH RECURSIVE up(id) AS (
1829 SELECT type_id FROM entities WHERE id = $2
1830 UNION
1831 SELECT p.parent_id FROM entity_type_parents p JOIN up ON p.child_id = up.id
1832 )
1833 SELECT (SELECT count(*) FROM relation_type_ranges WHERE relation_type_id = $1),
1834 (SELECT type_id IS NOT NULL FROM entities WHERE id = $2),
1835 (SELECT count(*) FROM relation_type_ranges g
1836 JOIN up ON up.id = g.entity_type_id
1837 WHERE g.relation_type_id = $1)",
1838 )
1839 .bind(relation_type_id)
1840 .bind(entity_id)
1841 .fetch_one(pool)
1842 .await?;
1843 Ok((declared > 0 && typed).then_some(ok > 0))
1844}
1845
1846/// 把 `owl:inverseOf` / `rdfs:subPropertyOf` 从 IRI 解析成 id。
1847///
1848/// **必须是第二遍。** 这两条指的是另一个关系类型,而 id 要等全部插完才有——
1849/// 一遍过的写法只能处理「父属性恰好排在前面」的文件,而 RDF 三元组没有顺序。
1850///
1851/// 按 IRI 配对而不是按 key:key 会因为撞名加后缀(`part_of_2`),
1852/// 而 IRI 是这份本体里的身份。
1853pub async fn link_property_axioms_bulk(
1854 pool: &PgPool,
1855 kb_id: Uuid,
1856 inverse: &[(String, String)],
1857 sub_property: &[(String, String)],
1858) -> AppResult<(u64, u64)> {
1859 let run = |column: &'static str, pairs: &[(String, String)]| {
1860 let src: Vec<String> = pairs.iter().map(|(s, _)| s.clone()).collect();
1861 let dst: Vec<String> = pairs.iter().map(|(_, d)| d.clone()).collect();
1862 async move {
1863 if src.is_empty() {
1864 return AppResult::Ok(0);
1865 }
1866 // 目标 IRI 在这个库里找不到就跳过这一条——**部分导入是常态**
1867 // (引用了外部词汇表里的属性),一条连不上不该让整次导入失败
1868 let sql = format!(
1869 "UPDATE relation_types r SET {column} = t.id
1870 FROM UNNEST($2::text[], $3::text[]) AS p(src, dst)
1871 JOIN relation_types t ON t.kb_id = $1 AND t.iri = p.dst
1872 WHERE r.kb_id = $1 AND r.iri = p.src AND r.id <> t.id"
1873 );
1874 let n = sqlx::query(&sql)
1875 .bind(kb_id)
1876 .bind(&src)
1877 .bind(&dst)
1878 .execute(pool)
1879 .await?
1880 .rows_affected();
1881 AppResult::Ok(n)
1882 }
1883 };
1884 let inv = run("inverse_of", inverse).await?;
1885 let sub = run("sub_property_of", sub_property).await?;
1886 Ok((inv, sub))
1887}