Skip to content

World's first open-source enterprise world model.

80.5 KB
Raw Blame
//! 本体编辑器仓储:类型/关系 CRUD(带使用量与删除保护)+ 未匹配统计。

use pgvector::Vector;
use sqlx::{PgConnection, PgPool};
use std::collections::HashSet;
use utopia_core::models::{
    EntityInstance, EntityTypeView, OntologyImportView, RelationAxioms, RelationTypeView,
    TypeCandidate,
};
use utopia_core::{AppError, AppResult};
use uuid::Uuid;

pub async fn entity_type_views(pool: &PgPool, kb_id: Uuid) -> AppResult<Vec<EntityTypeView>> {
    Ok(sqlx::query_as(
        "SELECT t.id, t.key, t.label, t.color, t.shape, t.builtin, t.description,
                ARRAY(SELECT p.parent_id FROM entity_type_parents p
                      WHERE p.child_id = t.id) AS parents,
                (SELECT p.parent_id FROM entity_type_parents p
                  WHERE p.child_id = t.id AND p.is_primary) AS primary_parent,
                ARRAY(SELECT d.b_id FROM entity_type_disjoint d
                      WHERE d.kb_id = t.kb_id AND d.a_id = t.id) AS disjoint,
                COALESCE(u.usage, 0) AS usage
         FROM entity_types t
         LEFT JOIN (
             SELECT type_id, count(*)::bigint AS usage
             FROM entities
             WHERE kb_id = $1 AND merged_into IS NULL AND type_id IS NOT NULL
             GROUP BY type_id
         ) u ON u.type_id = t.id
         WHERE t.kb_id = $1 ORDER BY lower(t.label)",
    )
    .bind(kb_id)
    .fetch_all(pool)
    .await?)
}

/// 「缺这条关系」看实体在哪一端:Out = 它是主语,In = 它是宾语,Either = 哪端都算。
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum LinkEnd {
    Out,
    In,
    Either,
}

/// 一个谓词在库里能以哪些样子出现,按「实体是关系的主语」这一端说。
///
/// 类型化行写的是属性;开放陈述写的是文档的短语,绑定(`phrase_bindings`)说哪些短语
/// 算这个属性、哪个方向。逆关系与对称关系把「主语」翻成「宾语」:`A parentOf B` 就是
/// `B childOf A`,所以缺 parentOf 的 A 也得没有一条「X childOf A」。
#[derive(Debug, Clone)]
pub struct LinkPredicate {
    /// 谓词是本体里某个属性的 key 时,那个属性
    pub relation_type_id: Option<Uuid>,
    along: Vec<Uuid>,
    against: Vec<Uuid>,
    phrases_along: Vec<String>,
    phrases_against: Vec<String>,
}

impl LinkPredicate {
    /// 认作这个谓词的全部短语(归一过的),两个方向合在一起
    pub fn phrases(&self) -> Vec<String> {
        let mut all = [self.phrases_along.clone(), self.phrases_against.clone()].concat();
        all.sort();
        all.dedup();
        all
    }
}

/// 把一个谓词(属性的 key,或者一个开放短语)解析成它在库里的各种写法。
pub async fn link_predicate(
    pool: &PgPool,
    kb_id: Uuid,
    predicate: &str,
) -> AppResult<LinkPredicate> {
    let (relation_type_id, against, mut phrases_along, phrases_against): (
        Option<Uuid>,
        Vec<Uuid>,
        Vec<String>,
        Vec<String>,
    ) = sqlx::query_as(
        "WITH r AS (SELECT id, inverse_of, is_symmetric FROM relation_types
                     WHERE kb_id = $1 AND key = $2),
              inv AS (SELECT x.id FROM relation_types x, r
                       WHERE x.kb_id = $1 AND (x.id = r.inverse_of OR x.inverse_of = r.id)
                      UNION SELECT id FROM r WHERE is_symmetric),
              b AS (SELECT phrase, direction = 'forward' AS fwd,
                           relation_type_id IN (SELECT id FROM r) AS on_r,
                           relation_type_id IN (SELECT id FROM inv) AS on_inv
                      FROM phrase_bindings
                     WHERE kb_id = $1 AND status = 'bound')
         SELECT (SELECT id FROM r),
                ARRAY(SELECT id FROM inv),
                ARRAY(SELECT DISTINCT phrase FROM b
                       WHERE (on_r AND fwd) OR (on_inv AND NOT fwd)),
                ARRAY(SELECT DISTINCT phrase FROM b
                       WHERE (on_r AND NOT fwd) OR (on_inv AND fwd))",
    )
    .bind(kb_id)
    .bind(predicate)
    .fetch_one(pool)
    .await?;
    phrases_along.push(crate::phrase_bindings::normalize(predicate));
    Ok(LinkPredicate {
        relation_type_id,
        along: relation_type_id.into_iter().collect(),
        against,
        phrases_along,
        phrases_against,
    })
}

/// 只列缺某条关系的成员(#1269):没有一条活着的事实(断言、陈述或派生)按这个谓词连着它。
#[derive(Debug, Clone, Copy)]
pub struct Lacking<'a> {
    pub predicate: &'a LinkPredicate,
    pub end: LinkEnd,
}

impl Lacking<'_> {
    /// 实体当主语时认哪些 (属性, 短语),当宾语时认哪些
    fn arms(&self) -> [(Vec<Uuid>, Vec<String>); 2] {
        let p = self.predicate;
        let along = (p.along.clone(), p.phrases_along.clone());
        let against = (p.against.clone(), p.phrases_against.clone());
        match self.end {
            LinkEnd::Out => [along, against],
            LinkEnd::In => [against, along],
            LinkEnd::Either => {
                let both = ([along.0, against.0].concat(), [along.1, against.1].concat());
                [both.clone(), both]
            }
        }
    }
}

/// 一端一个 NOT EXISTS,各自走 (kb_id, subject_id) / (kb_id, object_id) 的活行索引
fn lacking_sql() -> String {
    let phrase = crate::phrase_bindings::phrase_sql("f.phrase");
    ["subject", "object"]
        .iter()
        .zip([("$3", "$4"), ("$5", "$6")])
        .map(|(end, (ids, phrases))| {
            format!(
                " AND NOT EXISTS (SELECT 1 FROM facts f
                    WHERE f.kb_id = e.kb_id AND f.{end}_id = e.id AND f.invalidated_at IS NULL
                      AND (f.predicate_id = ANY({ids})
                           OR (f.layer = 'open' AND {phrase} = ANY({phrases}))))
                  AND NOT EXISTS (SELECT 1 FROM derived_facts d
                    WHERE d.kb_id = e.kb_id AND d.{end}_id = e.id AND d.invalidated_at IS NULL
                      AND d.predicate_id = ANY({ids}))"
            )
        })
        .collect()
}

/// 某个类下的实体实例(按名称序,分页)。返回 (rows, total)。
/// 给了 `lacking` 就只留缺那条关系的成员,页与总数按同一个条件数。
pub async fn entity_instances(
    pool: &PgPool,
    kb_id: Uuid,
    type_id: Uuid,
    lacking: Option<Lacking<'_>>,
    limit: i64,
    offset: i64,
) -> AppResult<(Vec<EntityInstance>, i64)> {
    // 没给 lacking 时 $3..$6 是空数组,条件里不引用它们
    let [(subject_ids, subject_phrases), (object_ids, object_phrases)] =
        lacking.map(|l| l.arms()).unwrap_or_default();
    let condition = format!(
        "e.kb_id = $1 AND e.type_id = $2 AND e.merged_into IS NULL{}",
        lacking.map(|_| lacking_sql()).unwrap_or_default()
    );
    let rows: Vec<EntityInstance> = sqlx::query_as(&format!(
        "SELECT e.id, e.canonical_name AS name,
                (SELECT count(*) FROM facts f
                  WHERE f.kb_id = e.kb_id
                    AND (f.subject_id = e.id OR f.object_id = e.id)
                    AND f.invalidated_at IS NULL) AS fact_count
         FROM entities e
         WHERE {condition}
         ORDER BY lower(e.canonical_name), e.id
         LIMIT $7 OFFSET $8"
    ))
    .bind(kb_id)
    .bind(type_id)
    .bind(&subject_ids)
    .bind(&subject_phrases)
    .bind(&object_ids)
    .bind(&object_phrases)
    .bind(limit)
    .bind(offset)
    .fetch_all(pool)
    .await?;
    let (total,): (i64,) = sqlx::query_as(&format!(
        "SELECT count(*) FROM entities e WHERE {condition}"
    ))
    .bind(kb_id)
    .bind(type_id)
    .bind(&subject_ids)
    .bind(&subject_phrases)
    .bind(&object_ids)
    .bind(&object_phrases)
    .fetch_one(pool)
    .await?;
    Ok((rows, total))
}

fn validate_shape(shape: &str) -> AppResult<()> {
    if !matches!(shape, "circle" | "square") {
        return Err(AppError::Validation(
            "shape must be circle or square".into(),
        ));
    }
    Ok(())
}

pub async fn relation_type_views(pool: &PgPool, kb_id: Uuid) -> AppResult<Vec<RelationTypeView>> {
    Ok(sqlx::query_as(
        "SELECT r.id, r.key, r.label, r.temporal, r.functional, r.inverse_functional,
                r.is_transitive, r.is_symmetric, r.is_asymmetric, r.is_irreflexive,
                r.inverse_of, r.sub_property_of,
                r.builtin, r.description,
                r.kind, r.datatype, r.unit,
                ARRAY(SELECT d.entity_type_id FROM relation_type_domains d
                      WHERE d.relation_type_id = r.id) AS domains,
                ARRAY(SELECT g.entity_type_id FROM relation_type_ranges g
                      WHERE g.relation_type_id = r.id) AS ranges,
                ARRAY(SELECT q.qualifier_type_id FROM relation_type_qualifiers q
                      WHERE q.relation_type_id = r.id) AS qualifiers,
                COALESCE(u.usage, 0) AS usage
         FROM relation_types r
         LEFT JOIN (
             SELECT predicate_id, count(*)::bigint AS usage
             FROM facts
             WHERE kb_id = $1 AND invalidated_at IS NULL AND predicate_id IS NOT NULL
             GROUP BY predicate_id
         ) u ON u.predicate_id = r.id
         WHERE r.kb_id = $1 ORDER BY lower(r.label)",
    )
    .bind(kb_id)
    .fetch_all(pool)
    .await?)
}

/// 谓词的显示名统一成**小驼峰**(见迁移 0042)。
///
/// 类是大驼峰、谓词是小驼峰,这是 RDF/OWL 与 schema.org 的惯例,而且大小写
/// 本身就在说这个词是类还是属性。库里同时存在 `acceptedAnswer`、`access to`、
/// `ApplicableCertificate` 三种写法,在同一列里读起来就是没规矩。
///
/// **只动分隔符与首字母,不碰词内部的大小写**:`productID`、`hasLEI`、
/// `accessibilityAPI` 要原样留着。从 `key` 反推是做不到这一点的——`to_key`
/// 在连续大写之间不插下划线,`product_id` 拼回去只会得到 `productId`。
pub fn lower_camel(label: &str) -> String {
    let mut out = String::with_capacity(label.len());
    let mut start_of_word = false;
    for c in label.trim().chars() {
        if c == ' ' || c == '_' || c == '-' {
            // 连着几个分隔符只算一次,词首标记留着
            start_of_word = !out.is_empty();
            continue;
        }
        if out.is_empty() {
            out.extend(c.to_lowercase());
        } else if start_of_word {
            out.extend(c.to_uppercase());
            start_of_word = false;
        } else {
            out.push(c);
        }
    }
    out
}

/// `temporal` 只有三个值(0031):单条建、单条改、批量建、重导入更新都走这一句
fn validate_temporal(temporal: &str) -> AppResult<()> {
    if !matches!(temporal, "state" | "event" | "eternal") {
        return Err(AppError::Validation(
            "temporal must be state / event / eternal".into(),
        ));
    }
    Ok(())
}

fn validate_key(key: &str) -> AppResult<()> {
    let ok = !key.is_empty()
        && key.len() <= 40
        && key
            .chars()
            .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '_');
    if !ok {
        return Err(AppError::invalid(
            "bad_key",
            "Key must be lowercase snake_case (a-z, 0-9, _), max 40 chars",
        ));
    }
    Ok(())
}

#[allow(clippy::too_many_arguments)]
pub async fn create_entity_type<'a>(
    pool: impl sqlx::Acquire<'a, Database = sqlx::Postgres>,
    kb_id: Uuid,
    key: &str,
    label: &str,
    color: &str,
    shape: &str,
    parents: &[Uuid],
    description: &str,
) -> AppResult<Uuid> {
    validate_key(key)?;
    validate_shape(shape)?;
    let mut tx = pool.begin().await?;
    let id = Uuid::now_v7();
    sqlx::query(
        "INSERT INTO entity_types (id, kb_id, key, label, color, shape, description)
         VALUES ($1, $2, $3, $4, $5, $6, $7)",
    )
    .bind(id)
    .bind(kb_id)
    .bind(key)
    .bind(label)
    .bind(color)
    .bind(shape)
    .bind(description)
    .execute(&mut *tx)
    .await
    .map_err(|e| match &e {
        sqlx::Error::Database(db) if db.is_unique_violation() => {
            AppError::Conflict(format!("Type key '{key}' already exists"))
        }
        _ => AppError::Db(e),
    })?;
    set_parents(&mut tx, kb_id, id, parents).await?;
    tx.commit().await?;
    Ok(id)
}

#[allow(clippy::too_many_arguments)]
/// 改一个实体类。
///
/// **`color: None` = 保持原色**,不是重置。从前这里是 `&str`,调用方不给就
/// 写死一个默认灰蓝,于是任何一次不带颜色的改名都会抹掉用户挑过的颜色。
pub async fn update_entity_type(
    pool: &PgPool,
    kb_id: Uuid,
    id: Uuid,
    label: &str,
    color: Option<&str>,
    shape: &str,
    parents: &[Uuid],
    description: &str,
) -> AppResult<()> {
    validate_shape(shape)?;
    let mut tx = pool.begin().await?;
    // 父链是签名判据(0062):违规按祖先链算。只比父集——label、颜色那些
    // 不改判据的字段照常写,不必跑检测
    let old_parents: Vec<Uuid> =
        sqlx::query_scalar("SELECT parent_id FROM entity_type_parents WHERE child_id = $1")
            .bind(id)
            .fetch_all(&mut *tx)
            .await?;
    let parents_changed =
        parents.len() != old_parents.len() || !parents.iter().all(|p| old_parents.contains(p));
    let was_detected = if parents_changed {
        Some(crate::reasoning::detection_keys(&mut tx, kb_id).await?)
    } else {
        None
    };
    let res = sqlx::query(
        "UPDATE entity_types SET label = $3, color = COALESCE($4, color), shape = $5,
                description = $6, updated_at = now()
         WHERE id = $2 AND kb_id = $1",
    )
    .bind(kb_id)
    .bind(id)
    .bind(label)
    .bind(color)
    .bind(shape)
    .bind(description)
    .execute(&mut *tx)
    .await?;
    if res.rows_affected() == 0 {
        return Err(AppError::NotFound);
    }
    set_parents(&mut tx, kb_id, id, parents).await?;
    if let Some(was) = was_detected {
        crate::reasoning::reconcile_ontology(&mut tx, kb_id, &was).await?;
    }
    tx.commit().await?;
    Ok(())
}

/// 把 `parents` 设成这个类的全部父类,第一个当主父(左栏画在那一支下)。
///
/// **先查环再写**。单父时代只需要挡自环,一条链天然不会成环;DAG 里 A→B→A
/// 完全可能,而 `type_matches_domain` 沿父链上溯,成环就是死循环。
/// SQL 拦不住这个——外键只挡自环,更长的要应用来查。
async fn set_parents(
    conn: &mut PgConnection,
    kb_id: Uuid,
    child: Uuid,
    parents: &[Uuid],
) -> AppResult<()> {
    if parents.contains(&child) {
        return Err(AppError::invalid(
            "self_parent",
            "A class cannot be its own parent",
        ));
    }
    if !parents.is_empty() {
        // 候选父类的全部祖先里出现 child,就说明这条边会成环
        let (cycles,): (i64,) = sqlx::query_as(
            "WITH RECURSIVE up(id) AS (
                 SELECT unnest($2::uuid[])
                 UNION
                 SELECT p.parent_id FROM entity_type_parents p JOIN up ON p.child_id = up.id
             )
             SELECT count(*) FROM up WHERE id = $1",
        )
        .bind(child)
        .bind(parents)
        .fetch_one(&mut *conn)
        .await?;
        if cycles > 0 {
            return Err(AppError::invalid(
                "parent_cycle",
                "That parent is already a subclass of this one",
            ));
        }
    }
    sqlx::query("DELETE FROM entity_type_parents WHERE child_id = $1")
        .bind(child)
        .execute(&mut *conn)
        .await?;
    for (i, p) in parents.iter().enumerate() {
        sqlx::query(
            "INSERT INTO entity_type_parents (child_id, parent_id, is_primary)
             VALUES ($1, $2, $3) ON CONFLICT DO NOTHING",
        )
        .bind(child)
        .bind(p)
        // 第一个当主父:界面上说明了"画在第一个下面",不再多一个控件
        .bind(i == 0)
        .execute(&mut *conn)
        .await?;
    }
    let _ = kb_id;
    Ok(())
}

pub async fn delete_entity_type(pool: &PgPool, kb_id: Uuid, id: Uuid) -> AppResult<()> {
    let mut tx = pool.begin().await?;
    let (usage,): (i64,) = sqlx::query_as("SELECT count(*) FROM entities WHERE type_id = $1")
        .bind(id)
        .fetch_one(&mut *tx)
        .await?;
    if usage > 0 {
        return Err(AppError::Conflict(format!(
            "Cannot delete: {usage} entities use this type"
        )));
    }
    // 这个类若牵着签名判据——是某个类的父类,或挂在某条关系的
    // domain / range 上——删掉它就改了「哪些违规成立」(0062)。
    // 动笔前把旧判据下的检出键集记下来,提交前对账
    let affects_criteria: bool = sqlx::query_scalar(
        "SELECT EXISTS(SELECT 1 FROM entity_type_parents WHERE parent_id = $1)
            OR EXISTS(SELECT 1 FROM relation_type_domains WHERE entity_type_id = $1)
            OR EXISTS(SELECT 1 FROM relation_type_ranges WHERE entity_type_id = $1)",
    )
    .bind(id)
    .fetch_one(&mut *tx)
    .await?;
    let was_detected = if affects_criteria {
        Some(crate::reasoning::detection_keys(&mut tx, kb_id).await?)
    } else {
        None
    };
    // 只剩这一个 domain 的属性随类一起走:属性必须挂在类上,
    // 留一个没有 domain 的属性等于留一个不会出现在任何地方的死行。
    // 还挂在别的类上的则只掉一条关联(外键 CASCADE 负责)。
    // 连带效果(0070 的 FK CASCADE):属性没了 → 用它做谓词的事实没了 →
    // 指向那些事实的违规行也被物理删掉。这些行不走 `criterion_changed`——
    // 它们的判据没换,是事实本身没了,与 `run` 对消失事实的清陈同一条规矩
    sqlx::query(
        "DELETE FROM relation_types r
         WHERE r.kind = 'attribute' AND r.kb_id = $1
           AND EXISTS (SELECT 1 FROM relation_type_domains d
                       WHERE d.relation_type_id = r.id AND d.entity_type_id = $2)
           AND NOT EXISTS (SELECT 1 FROM relation_type_domains d
                           WHERE d.relation_type_id = r.id AND d.entity_type_id <> $2)",
    )
    .bind(kb_id)
    .bind(id)
    .execute(&mut *tx)
    .await?;
    let res = sqlx::query("DELETE FROM entity_types WHERE id = $2 AND kb_id = $1 AND NOT builtin")
        .bind(kb_id)
        .bind(id)
        .execute(&mut *tx)
        .await?;
    if res.rows_affected() == 0 {
        return Err(AppError::Conflict(
            "Built-in types cannot be deleted".into(),
        ));
    }
    if let Some(was) = was_detected {
        crate::reasoning::reconcile_ontology(&mut tx, kb_id, &was).await?;
    }
    tx.commit().await?;
    Ok(())
}

/// 属性字段校验:attribute 必须有所属类和合法 datatype;relation 三者强制为空。
fn validate_attribute_fields(
    kind: &str,
    domains: &[Uuid],
    datatype: Option<&str>,
) -> AppResult<()> {
    match kind {
        "relation" => Ok(()),
        "attribute" => {
            if domains.is_empty() {
                return Err(AppError::invalid(
                    "attr_needs_class",
                    "An attribute needs a class (domain)",
                ));
            }
            if !matches!(datatype, Some("text" | "number" | "date" | "bool")) {
                return Err(AppError::Validation(
                    "datatype must be text / number / date / bool".into(),
                ));
            }
            Ok(())
        }
        _ => Err(AppError::Validation(
            "kind must be relation / attribute".into(),
        )),
    }
}

/// 两条指向别的关系的公理,落库前必须过这里。
///
/// **最要紧的一条是同库。** 列上的外键是 `REFERENCES relation_types(id)`,
/// 它不认知识库——数据库层面,A 库的关系可以指向 B 库的关系。RDF 导入那条路
/// 天然过不去(按 IRI 在本库里查),而接口收的是裸 UUID:不在这里挡,
/// 拿到任意一个 UUID 就能让推理机跨库读公理。**不能靠前端只列本库选项**,
/// 那是界面礼貌,不是边界。
///
/// 另外两条:属性没有逆(它的宾语是字面值,反过来无从谈起),
/// 子属性不能是自己(DB 有 CHECK,但撞上去是 500,得在这里给出人话)。
/// 而**逆是自己允许**——那等于对称,R0 会提示改用 `symmetric` 更直白,不算错。
async fn validate_property_links(
    conn: &mut PgConnection,
    kb_id: Uuid,
    self_id: Option<Uuid>,
    kind: &str,
    ax: RelationAxioms,
) -> AppResult<()> {
    let links = [ax.inverse_of, ax.sub_property_of];
    if links.iter().all(|l| l.is_none()) {
        return Ok(());
    }
    if kind == "attribute" {
        return Err(AppError::invalid(
            "attr_has_no_link",
            "An attribute cannot have an inverse or a super-property",
        ));
    }
    if self_id.is_some() && ax.sub_property_of == self_id {
        return Err(AppError::invalid(
            "sub_property_self",
            "A relation cannot be its own super-property",
        ));
    }
    for target in links.into_iter().flatten() {
        let ok: Option<(String,)> =
            sqlx::query_as("SELECT kind FROM relation_types WHERE id = $1 AND kb_id = $2")
                .bind(target)
                .bind(kb_id)
                .fetch_optional(&mut *conn)
                .await?;
        match ok {
            // 不区分「不存在」与「在别的库」:能问出哪个 UUID 存在于别处,
            // 本身就是一点不该给的信息
            None => {
                return Err(AppError::invalid(
                    "unknown_relation",
                    "That relation is not in this knowledge base",
                ));
            }
            Some((k,)) if k != "relation" => {
                return Err(AppError::invalid(
                    "link_target_is_attr",
                    "An attribute cannot be an inverse or a super-property",
                ));
            }
            Some(_) => {}
        }
    }
    Ok(())
}

#[allow(clippy::too_many_arguments)]
pub async fn create_relation_type<'a>(
    pool: impl sqlx::Acquire<'a, Database = sqlx::Postgres>,
    kb_id: Uuid,
    key: &str,
    label: &str,
    temporal: &str,
    ax: RelationAxioms,
    description: &str,
    kind: &str,
    domains: &[Uuid],
    ranges: &[Uuid],
    datatype: Option<&str>,
    unit: Option<&str>,
) -> AppResult<Uuid> {
    validate_key(key)?;
    validate_temporal(temporal)?;
    validate_attribute_fields(kind, domains, datatype)?;
    let mut tx = pool.begin().await?;
    let label = &lower_camel(label);
    // 新建的行 id 还不存在,指向自己无从谈起——所以 self_id 传 None
    validate_property_links(&mut tx, kb_id, None, kind, ax).await?;
    let is_attr = kind == "attribute";
    let id = Uuid::now_v7();
    sqlx::query(
        "INSERT INTO relation_types (id, kb_id, key, label, temporal,
                                     functional, inverse_functional, description,
                                     kind, datatype, unit,
                                     is_transitive, is_symmetric,
                                     is_asymmetric, is_irreflexive,
                                     inverse_of, sub_property_of)
         VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15,
                 $16, $17)",
    )
    .bind(id)
    .bind(kb_id)
    .bind(key)
    .bind(label)
    .bind(temporal)
    .bind(ax.functional)
    .bind(ax.inverse_functional)
    .bind(description)
    .bind(kind)
    .bind(is_attr.then_some(datatype).flatten())
    .bind(is_attr.then_some(unit).flatten())
    .bind(ax.transitive)
    .bind(ax.symmetric)
    .bind(ax.asymmetric)
    .bind(ax.irreflexive)
    // 属性不带这两条(上面已经拦了非空的情况,这里是兜底)
    .bind(if is_attr { None } else { ax.inverse_of })
    .bind(if is_attr { None } else { ax.sub_property_of })
    .execute(&mut *tx)
    .await
    .map_err(|e| match &e {
        sqlx::Error::Database(db) if db.is_unique_violation() => {
            AppError::Conflict(format!("Relation key '{key}' already exists"))
        }
        _ => AppError::Db(e),
    })?;
    // attribute 不写 range:它的值域是字面量类型,落在 datatype 上
    set_domains_ranges(&mut tx, id, domains, if is_attr { &[] } else { ranges }).await?;
    tx.commit().await?;
    Ok(id)
}

/// 覆盖式写入 domain / range。**先删后插**,所以它既能用于新建也能用于重导入,
/// 且不会留下上一轮的残余。
async fn set_domains_ranges(
    conn: &mut PgConnection,
    relation_type_id: Uuid,
    domains: &[Uuid],
    ranges: &[Uuid],
) -> AppResult<()> {
    for (table, ids) in [
        ("relation_type_domains", domains),
        ("relation_type_ranges", ranges),
    ] {
        sqlx::query(&format!("DELETE FROM {table} WHERE relation_type_id = $1"))
            .bind(relation_type_id)
            .execute(&mut *conn)
            .await?;
        if ids.is_empty() {
            continue;
        }
        // unnest 一次插完,省去逐条往返
        sqlx::query(&format!(
            "INSERT INTO {table} (relation_type_id, entity_type_id)
             SELECT $1, x FROM unnest($2::uuid[]) AS x
             ON CONFLICT DO NOTHING"
        ))
        .bind(relation_type_id)
        .bind(ids)
        .execute(&mut *conn)
        .await?;
    }
    Ok(())
}

/// 一条关系声明自己的边能带哪些属性(0037)。覆盖式写入,与 domain / range 同一套。
///
/// 两条校验都在这里,CHECK 引不到别的行:同库,且每一个都是 `kind = 'attribute'`
/// ——边上的属性是字面值,复用的正是属性定义的 datatype / unit / 换算。
/// 一个关系不能把自己声明成自己的属性(DB 有 CHECK,这里给人话)。
pub async fn set_relation_qualifiers(
    pool: &PgPool,
    kb_id: Uuid,
    relation_type_id: Uuid,
    qualifier_type_ids: &[Uuid],
) -> AppResult<()> {
    if qualifier_type_ids.contains(&relation_type_id) {
        return Err(AppError::invalid(
            "qualifier_is_self",
            "A relation cannot be its own qualifier",
        ));
    }
    if !qualifier_type_ids.is_empty() {
        let (ok,): (i64,) = sqlx::query_as(
            "SELECT count(*) FROM relation_types
             WHERE kb_id = $1 AND kind = 'attribute' AND id = ANY($2)",
        )
        .bind(kb_id)
        .bind(qualifier_type_ids)
        .fetch_one(pool)
        .await?;
        if ok as usize != qualifier_type_ids.len() {
            return Err(AppError::invalid(
                "qualifier_not_attribute",
                "Every qualifier must be an attribute of this base",
            ));
        }
    }
    sqlx::query("DELETE FROM relation_type_qualifiers WHERE relation_type_id = $1")
        .bind(relation_type_id)
        .execute(pool)
        .await?;
    if !qualifier_type_ids.is_empty() {
        sqlx::query(
            "INSERT INTO relation_type_qualifiers (relation_type_id, qualifier_type_id)
             SELECT $1, x FROM unnest($2::uuid[]) AS x
             ON CONFLICT DO NOTHING",
        )
        .bind(relation_type_id)
        .bind(qualifier_type_ids)
        .execute(pool)
        .await?;
    }
    Ok(())
}

/// 给一条关系**追加**一个边上的属性声明(0037)。
///
/// 与 `set_relation_qualifiers` 的覆盖式不同:抽取时几篇文档并行,各自从语料里
/// 补声明,覆盖式写入会把别人刚补的冲掉(实测 `round` 补过又没了)。
/// 这里只加不删,撞上已有的什么都不做。校验与覆盖式同一套。
pub async fn add_relation_qualifier(
    pool: &PgPool,
    kb_id: Uuid,
    relation_type_id: Uuid,
    qualifier_type_id: Uuid,
) -> AppResult<()> {
    if relation_type_id == qualifier_type_id {
        return Err(AppError::invalid(
            "qualifier_is_self",
            "A relation cannot be its own qualifier",
        ));
    }
    let (ok,): (i64,) = sqlx::query_as(
        "SELECT count(*) FROM relation_types
         WHERE kb_id = $1 AND kind = 'attribute' AND id = $2",
    )
    .bind(kb_id)
    .bind(qualifier_type_id)
    .fetch_one(pool)
    .await?;
    if ok != 1 {
        return Err(AppError::invalid(
            "qualifier_not_attribute",
            "Every qualifier must be an attribute of this base",
        ));
    }
    sqlx::query(
        "INSERT INTO relation_type_qualifiers (relation_type_id, qualifier_type_id)
         VALUES ($1, $2) ON CONFLICT DO NOTHING",
    )
    .bind(relation_type_id)
    .bind(qualifier_type_id)
    .execute(pool)
    .await?;
    Ok(())
}

#[allow(clippy::too_many_arguments)]
pub async fn update_relation_type(
    pool: &PgPool,
    kb_id: Uuid,
    id: Uuid,
    label: &str,
    temporal: &str,
    ax: RelationAxioms,
    description: &str,
    datatype: Option<&str>,
    unit: Option<&str>,
    // 整组语义:两侧都 None = 签名不动;任一侧 Some = 两侧都按传入值重写
    // (没传的那一侧清空)。不管签名的调用方(如纯改公理位)必须两侧都传
    // None——`domains=Some(..)` + `ranges=None` 会把 range 清空
    domains: Option<&[Uuid]>,
    ranges: Option<&[Uuid]>,
) -> AppResult<()> {
    // 整条改动进一条事务:判据变了的话,落笔前要先记下旧本体下检出的违规,
    // 落笔后按新本体重检、收编旧判据的行——`open` 的意思是「已对账于当前本体」
    //(0062),不许留一行只对旧判据成立的 open 违规走出提交点
    let mut tx = pool.begin().await?;
    // 名字属性是内建的(0041):标成 functional 会让每个第二个名字都成一条冲突、
    // 甚至把本名关掉;改名、改时态也一样没有正当用途
    let name_attribute: Option<(bool,)> = sqlx::query_as(
        "SELECT builtin AND key = 'known_as' FROM relation_types WHERE id = $1 AND kb_id = $2",
    )
    .bind(id)
    .bind(kb_id)
    .fetch_optional(&mut *tx)
    .await?;
    if name_attribute == Some((true,)) {
        return Err(AppError::invalid(
            "builtin_name_attribute",
            "The name attribute is built in and cannot be edited",
        ));
    }
    // 改名也归一:不然界面上改一次就能把小驼峰改回 "access to"
    let label = &lower_camel(label);
    validate_temporal(temporal)?;
    if datatype.is_some() && !matches!(datatype, Some("text" | "number" | "date" | "bool")) {
        return Err(AppError::Validation(
            "datatype must be text / number / date / bool".into(),
        ));
    }
    // 旧判据先取下来:公理位、时态、两条关系链、domain/range 一起决定
    // 「哪些违规成立」。行不在就是 NotFound——UPDATE 反正会空
    let old: Option<OldCriteria> = sqlx::query_as(
        "SELECT kind, temporal, functional, inverse_functional, is_transitive,
                is_symmetric, is_asymmetric, is_irreflexive, inverse_of, sub_property_of
           FROM relation_types WHERE id = $1 AND kb_id = $2",
    )
    .bind(id)
    .bind(kb_id)
    .fetch_optional(&mut *tx)
    .await?;
    let Some(old) = old else {
        return Err(AppError::NotFound);
    };
    // 指向别的关系的两条要先问过库:目标在不在本库、是不是关系。
    // 只在真的填了的时候查——清空(两个都 None)没有目标可验
    if ax.inverse_of.is_some() || ax.sub_property_of.is_some() {
        validate_property_links(&mut tx, kb_id, Some(id), &old.kind, ax).await?;
    }
    // domain/range 可改——它们是签名不是身份,"这个属性也适用于承包商" 是个正当的
    // 编辑。kind 不可变(改它会让存量事实语义错乱)
    let signature_touched = domains.is_some() || ranges.is_some();
    let mut signature_changed = false;
    let next_domains: &[Uuid] = domains.unwrap_or(&[]);
    let next_ranges: &[Uuid] = if old.kind == "attribute" {
        // 属性没有 range:它的值域是字面量类型,落在 datatype 上
        &[]
    } else {
        ranges.unwrap_or(&[])
    };
    if signature_touched {
        if old.kind == "attribute" && next_domains.is_empty() {
            return Err(AppError::invalid(
                "attr_needs_class",
                "An attribute needs a class (domain)",
            ));
        }
        let old_domains: HashSet<Uuid> = sqlx::query_scalar(
            "SELECT entity_type_id FROM relation_type_domains WHERE relation_type_id = $1",
        )
        .bind(id)
        .fetch_all(&mut *tx)
        .await?
        .into_iter()
        .collect();
        let old_ranges: HashSet<Uuid> = sqlx::query_scalar(
            "SELECT entity_type_id FROM relation_type_ranges WHERE relation_type_id = $1",
        )
        .bind(id)
        .fetch_all(&mut *tx)
        .await?
        .into_iter()
        .collect();
        signature_changed = old_domains != next_domains.iter().copied().collect::<HashSet<_>>()
            || old_ranges != next_ranges.iter().copied().collect::<HashSet<_>>();
    }
    // label / description / datatype / unit 不进这里:它们不动判据,
    // 改了不值得跑一遍检测
    let criteria_changed = old.temporal != temporal
        || old.functional != ax.functional
        || old.inverse_functional != ax.inverse_functional
        || old.is_transitive != ax.transitive
        || old.is_symmetric != ax.symmetric
        || old.is_asymmetric != ax.asymmetric
        || old.is_irreflexive != ax.irreflexive
        || old.inverse_of != ax.inverse_of
        || old.sub_property_of != ax.sub_property_of
        || signature_changed;
    // 检出必须在写入**之前**:此刻库里还是旧本体,记下的正是「旧判据下
    // 会算出来的违规」,提交前对照用
    let was_detected = if criteria_changed {
        Some(crate::reasoning::detection_keys(&mut tx, kb_id).await?)
    } else {
        None
    };
    // 两条链**跟着六位公理一起覆盖式写**:缺省 = 清空,不是「不动」。
    // 与 `is_transitive` 那几位同一条规矩——它们是同一个表单里同时提交的
    // 一组声明,一半覆盖一半保留才是真正会出事的语义
    let res = sqlx::query(
        "UPDATE relation_types
            SET label = $3, temporal = $4,
                functional = $5, inverse_functional = $6, description = $7,
                datatype = CASE WHEN kind = 'attribute' AND $8 IS NOT NULL THEN $8 ELSE datatype END,
                unit = CASE WHEN kind = 'attribute' THEN $9 ELSE unit END,
                is_transitive = $10, is_symmetric = $11,
                is_asymmetric = $12, is_irreflexive = $13,
                inverse_of = $14, sub_property_of = $15, updated_at = now()
         WHERE id = $2 AND kb_id = $1",
    )
    .bind(kb_id)
    .bind(id)
    .bind(label)
    .bind(temporal)
    .bind(ax.functional)
    .bind(ax.inverse_functional)
    .bind(description)
    .bind(datatype)
    .bind(unit)
    .bind(ax.transitive)
    .bind(ax.symmetric)
    .bind(ax.asymmetric)
    .bind(ax.irreflexive)
    .bind(ax.inverse_of)
    .bind(ax.sub_property_of)
    .execute(&mut *tx)
    .await?;
    if res.rows_affected() == 0 {
        return Err(AppError::NotFound);
    }
    if signature_touched {
        set_domains_ranges(&mut tx, id, next_domains, next_ranges).await?;
    }
    if let Some(was) = was_detected {
        crate::reasoning::reconcile_ontology(&mut tx, kb_id, &was).await?;
    }
    tx.commit().await?;
    Ok(())
}

/// `relation_types` 一行里跟「哪些违规成立」有关的列(0062 对账用的旧判据快照)。
/// label / description / datatype / unit 不在——它们不动判据
#[derive(sqlx::FromRow)]
struct OldCriteria {
    kind: String,
    temporal: String,
    functional: bool,
    inverse_functional: bool,
    is_transitive: bool,
    is_symmetric: bool,
    is_asymmetric: bool,
    is_irreflexive: bool,
    inverse_of: Option<Uuid>,
    sub_property_of: Option<Uuid>,
}

pub async fn delete_relation_type(pool: &PgPool, kb_id: Uuid, id: Uuid) -> AppResult<()> {
    let mut tx = pool.begin().await?;
    let (usage,): (i64,) = sqlx::query_as("SELECT count(*) FROM facts WHERE predicate_id = $1")
        .bind(id)
        .fetch_one(&mut *tx)
        .await?;
    if usage > 0 {
        return Err(AppError::Conflict(format!(
            "Cannot delete: {usage} facts use this relation"
        )));
    }
    // 判据贡献不只「有没有人引用它」这一半:这行自己的旗标与出向
    // inverse_of/sub_property_of 链接喂着别的谓词的派生链,rules_disagree
    // 缺陷行也以谓词 id 指着它。枚举哪些列算判据已被证明会漏——删除又足够
    // 稀少,不为省检测设门槛,一律记下旧判据下的检出键集(0062)
    let was_detected = crate::reasoning::detection_keys(&mut tx, kb_id).await?;
    // 0070 把这两条外键建成 DEFERRABLE 的 SET NULL——级联动作提交时才落地,
    // 而对账检测要看见改完的判据,所以先在事务里显式断链
    sqlx::query("UPDATE relation_types SET inverse_of = NULL WHERE inverse_of = $1")
        .bind(id)
        .execute(&mut *tx)
        .await?;
    sqlx::query("UPDATE relation_types SET sub_property_of = NULL WHERE sub_property_of = $1")
        .bind(id)
        .execute(&mut *tx)
        .await?;
    let res =
        sqlx::query("DELETE FROM relation_types WHERE id = $2 AND kb_id = $1 AND NOT builtin")
            .bind(kb_id)
            .bind(id)
            .execute(&mut *tx)
            .await?;
    if res.rows_affected() == 0 {
        return Err(AppError::Conflict(
            "Built-in relations cannot be deleted".into(),
        ));
    }
    crate::reasoning::reconcile_ontology(&mut tx, kb_id, &was_detected).await?;
    tx.commit().await?;
    Ok(())
}

/* ---- 未匹配统计 ---- */

/* ---- OWL 导入 ---- */

/// 建一个带 IRI 的类。IRI 是全局身份,重导入据它匹配(见 0001 P2)。
pub async fn create_entity_type_with_iri(
    pool: &PgPool,
    kb_id: Uuid,
    key: &str,
    label: &str,
    description: &str,
    iri: &str,
) -> AppResult<Uuid> {
    validate_key(key)?;
    let id = Uuid::now_v7();
    sqlx::query(
        "INSERT INTO entity_types (id, kb_id, key, label, color, shape, description, iri)
         VALUES ($1, $2, $3, $4, $7, $8, $5, $6)",
    )
    .bind(id)
    .bind(kb_id)
    .bind(key)
    .bind(label)
    .bind(description)
    .bind(iri)
    // 按 key 取色而不是所有类一个灰蓝——导入一个大本体进来才有得看
    .bind(crate::palette::color_for_key(key))
    // 形状说明来历:这条路带 IRI,就是词表声明的
    .bind(crate::palette::shape_for(iri))
    .execute(pool)
    .await
    .map_err(|e| match &e {
        sqlx::Error::Database(db) if db.is_unique_violation() => {
            AppError::Conflict(format!("Type key '{key}' already exists"))
        }
        _ => AppError::Db(e),
    })?;
    Ok(id)
}

/// 重导入时按 IRI 更新标签与描述。**key 不动**——它可能已经被抽取出的实体
/// 和提示词引用,改它等于把已有数据的引用打断;上游改 label 是常态,
/// 而 IRI 才是身份。
pub async fn update_type_from_import(
    pool: &PgPool,
    kb_id: Uuid,
    iri: &str,
    label: &str,
    description: &str,
) -> AppResult<Option<Uuid>> {
    let row: Option<(Uuid,)> = sqlx::query_as(
        "UPDATE entity_types
         SET label = $3,
             -- 空描述不覆盖已有的:上游可能没写 rdfs:comment,而本地可能
             -- 已经被人按自己的语料调过,那份调整比空值有价值
             description = CASE WHEN $4 = '' THEN description ELSE $4 END,
             updated_at = now()
         WHERE kb_id = $1 AND iri = $2 RETURNING id",
    )
    .bind(kb_id)
    .bind(iri)
    .bind(label)
    .bind(description)
    .fetch_optional(pool)
    .await?;
    Ok(row.map(|(id,)| id))
}

/// 从导入建一个关系(`kind='relation'`),带 IRI。
///
/// `temporal` 固定 `state`:OWL 没有对应概念,而 state(有区间)是三者里唯一
/// 不丢信息的——event 会把区间压成时点,eternal 会宣称它永不改变。
///
/// **`functional` / `inverse_functional` 照词汇表写**。它们驱动时态引擎自动闭合
/// 旧事实,猜错就成批造假冲突(`part_of` 那次 59 条)。预览已经把声明为函数性的
/// 关系单独列出来让人过目,所以这里不再自作主张改成 false。
#[allow(clippy::too_many_arguments)]
pub async fn create_relation_with_iri(
    pool: &PgPool,
    kb_id: Uuid,
    key: &str,
    label: &str,
    description: &str,
    iri: &str,
    functional: bool,
    inverse_functional: bool,
    domains: &[Uuid],
    ranges: &[Uuid],
) -> AppResult<Option<Uuid>> {
    validate_key(key)?;
    let id = Uuid::now_v7();
    let row: Option<(Uuid,)> = sqlx::query_as(
        "INSERT INTO relation_types
             (id, kb_id, key, label, temporal, functional, inverse_functional,
              description, kind, iri)
         VALUES ($1, $2, $3, $4, 'state', $5, $6, $7, 'relation', $8)
         ON CONFLICT (kb_id, key) DO NOTHING
         RETURNING id",
    )
    .bind(id)
    .bind(kb_id)
    .bind(key)
    .bind(label)
    .bind(functional)
    .bind(inverse_functional)
    .bind(description)
    .bind(iri)
    .fetch_optional(pool)
    .await?;
    let Some((new_id,)) = row else {
        return Ok(None);
    };
    set_domains_ranges(&mut *pool.acquire().await?, new_id, domains, ranges).await?;
    Ok(Some(new_id))
}

/// 重导入时更新一个已按 IRI 认下的关系。
///
/// **key 不动**(它可能已被事实引用),**空描述不覆盖**(人写过的比上游的准),
/// **domain/range 整体重写**——它们是上游声明的结构,不是人调过的措辞。
/// **`temporal` 只在本体说了才写**(`Some`):没写 `utopia:temporal` 的本体不动它,
/// 人在页面上改过的就留着;写了的照本体,与 domain/range 同一个道理。
/// 真改了就推 `updated_at`,与页面上改一样:0053 的短语绑定依据读它,
/// state 与非 state 决定短语怎么绑,旧值下做的决定要能被重审。
#[allow(clippy::too_many_arguments)]
pub async fn update_relation_from_import(
    pool: &PgPool,
    kb_id: Uuid,
    iri: &str,
    label: &str,
    description: &str,
    domains: &[Uuid],
    ranges: &[Uuid],
    temporal: Option<&str>,
) -> AppResult<bool> {
    if let Some(t) = temporal {
        validate_temporal(t)?;
    }
    let row: Option<(Uuid,)> = sqlx::query_as(
        "UPDATE relation_types
            SET label = $3,
                description = CASE WHEN $4 = '' THEN description ELSE $4 END,
                temporal = COALESCE($5::text, temporal),
                updated_at = CASE WHEN $5::text <> temporal THEN now() ELSE updated_at END
          WHERE kb_id = $1 AND iri = $2
          RETURNING id",
    )
    .bind(kb_id)
    .bind(iri)
    .bind(label)
    .bind(description)
    .bind(temporal)
    .fetch_optional(pool)
    .await?;
    let Some((id,)) = row else {
        return Ok(false);
    };
    set_domains_ranges(&mut *pool.acquire().await?, id, domains, ranges).await?;
    Ok(true)
}

/// 记一次导入。原文已按内容寻址存进 blob,这里只记账。
#[allow(clippy::too_many_arguments)]
pub async fn record_import(
    pool: &PgPool,
    kb_id: Uuid,
    sha256: &str,
    filename: &str,
    format: &str,
    byte_size: i64,
    summary: &serde_json::Value,
    actor: Uuid,
) -> AppResult<Uuid> {
    let id = Uuid::now_v7();
    sqlx::query(
        "INSERT INTO ontology_imports
            (id, kb_id, sha256, filename, format, byte_size, summary, imported_by)
         VALUES ($1, $2, $3, $4, $5, $6, $7, $8)",
    )
    .bind(id)
    .bind(kb_id)
    .bind(sha256)
    .bind(filename)
    .bind(format)
    .bind(byte_size)
    .bind(summary)
    .bind(actor)
    .execute(pool)
    .await?;
    Ok(id)
}

/// 一个库的导入历史(带导入人显示名;删号后为 NULL)。
pub async fn list_imports(pool: &PgPool, kb_id: Uuid) -> AppResult<Vec<OntologyImportView>> {
    Ok(sqlx::query_as(
        "SELECT i.id, i.filename, i.format, i.byte_size, i.summary, i.imported_at,
                u.display_name AS imported_by_name
         FROM ontology_imports i
         LEFT JOIN users u ON u.id = i.imported_by
         WHERE i.kb_id = $1 ORDER BY i.imported_at DESC LIMIT 50",
    )
    .bind(kb_id)
    .fetch_all(pool)
    .await?)
}

/// 一条待嵌入的本体行。`text` 是要送去嵌入的那段字,`kind` 决定回写哪张表。
#[derive(Debug, Clone)]
pub struct TypeToEmbed {
    pub id: Uuid,
    pub kind: TypeKind,
    pub text: String,
    /// 写进哪一组列。类有两份向量:整段(label + 描述)与只有 label 的那份,
    /// 分别服务长画像与短说法两种查询(见 `entity_types.label_embedding`)
    pub field: EmbedField,
}

/// 同一行的两份向量。**短查询比 Label,长画像比 Full**——查询分了两种形状,
/// 文档也得分两种,否则短查询会被同义反复的类接管(`Map\nA map.` 那一类)。
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum EmbedField {
    Full,
    Label,
}

/// 本体行属于哪张表。类进 `entity_types`,关系与属性同住 `relation_types`。
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TypeKind {
    Entity,
    Relation,
}

/// 嵌入用的那段字:标签在前、描述在后。
///
/// **key 不进去。** key 是模型读写的令牌(`founding_date`),描述才是这个类型
/// 的意思所在。把 key 混进来,检索会被"两个 key 长得像"带偏——而
/// `position`(列表位次)与 `position`(职位)正是长得一模一样的两回事。
fn embed_text(label: &str, description: &str) -> String {
    let d = description.trim();
    if d.is_empty() {
        label.trim().to_string()
    } else {
        format!("{}\n{}", label.trim(), d)
    }
}

/// 哪些本体行的向量是陈的(没嵌过、描述改了、或换了嵌入模型)。
///
/// 判据是**比对当时嵌的原文与模型名**,不是看时间戳:描述改了、模型换了,
/// 时间戳一样看不出来。这样也不必在每个改描述的写入点挂钩子——漏一个就悄悄烂掉。
///
/// `only` 限定只补一半。类型消解只用类,让它等 1633 个关系嵌完是白等六分钟;
/// 而后台那个补齐任务不限,两边补的是同一批行,谁先跑到都算数。
pub async fn types_needing_embedding(
    pool: &PgPool,
    kb_id: Uuid,
    model: &str,
    only: Option<TypeKind>,
) -> AppResult<Vec<TypeToEmbed>> {
    if only == Some(TypeKind::Relation) {
        // 类型消解只用类,等 1633 个关系嵌完是白等六分钟
        return relations_needing_embedding(pool, kb_id, model).await;
    }
    // **陈不陈,用生成原文的同一个函数判**(#672)。从前在 SQL 里用 `btrim` 把这段字
    // 重拼一遍再比,而 `embed_text` 用的是 Rust 的 `trim`:`btrim` 只去空格,`trim`
    // 连换行、制表符一起去。schema.org 的描述结尾是 "\n      ",这些行存下的原文与
    // SQL 拼出来的永远不等,于是每轮都判成陈的——补齐任务把同一批行一遍遍重嵌,
    // 抽取门控(#526)等一个永远补不齐的索引,直到期限把文档判失败。
    // 与 `mappings::needing_embedding` 同一个教训:拉回来在 Rust 里比
    let rows: Vec<StoredEmbedding> = sqlx::query_as(
        "SELECT id, label, coalesce(description, '') AS description,
                embedding IS NOT NULL AS embedded, embedded_model, embedded_text,
                label_embedding IS NOT NULL AS label_embedded, label_embedded_model, label_embedded_text
           FROM entity_types
          WHERE kb_id = $1",
    )
    .bind(kb_id)
    .fetch_all(pool)
    .await?;
    let mut full = Vec::new();
    let mut labels = Vec::new();
    for r in rows {
        let text = embed_text(&r.label, &r.description);
        if is_stale(
            r.embedded,
            r.embedded_model.as_deref(),
            r.embedded_text.as_deref(),
            model,
            &text,
        ) {
            full.push(TypeToEmbed {
                id: r.id,
                kind: TypeKind::Entity,
                text,
                field: EmbedField::Full,
            });
        }
        // 只嵌 label 的那一份(见 `entity_types.label_embedding`)。短查询走这个索引——查询分了两种形状,
        // 文档也得分两种,否则短查询被同义反复的类接管
        let short = r.label.trim().to_string();
        if is_stale(
            r.label_embedded,
            r.label_embedded_model.as_deref(),
            r.label_embedded_text.as_deref(),
            model,
            &short,
        ) {
            labels.push(TypeToEmbed {
                id: r.id,
                kind: TypeKind::Entity,
                text: short,
                field: EmbedField::Label,
            });
        }
    }
    let mut out = full;
    out.extend(labels);
    if only == Some(TypeKind::Entity) {
        return Ok(out);
    }
    out.extend(relations_needing_embedding(pool, kb_id, model).await?);
    Ok(out)
}

async fn relations_needing_embedding(
    pool: &PgPool,
    kb_id: Uuid,
    model: &str,
) -> AppResult<Vec<TypeToEmbed>> {
    // 判据同上(#672):在 Rust 里用 `embed_text` 比,不在 SQL 里重拼。关系只有整段
    // 那一份向量,label 那三列补空。
    //
    // 名字属性不嵌(0041):没有向量就不会被最近邻检索出来,本体提议、属性归并、
    // 抽取时的候选清单都碰不到它——名字只走抽取回复里的 `names` 那一条路
    let rows: Vec<StoredEmbedding> = sqlx::query_as(
        "SELECT id, label, coalesce(description, '') AS description,
                embedding IS NOT NULL AS embedded, embedded_model, embedded_text,
                false AS label_embedded, NULL::text AS label_embedded_model,
                NULL::text AS label_embedded_text
           FROM relation_types
          WHERE kb_id = $1 AND NOT (builtin AND key = 'known_as')",
    )
    .bind(kb_id)
    .fetch_all(pool)
    .await?;
    Ok(rows
        .into_iter()
        .filter_map(|r| {
            let text = embed_text(&r.label, &r.description);
            is_stale(
                r.embedded,
                r.embedded_model.as_deref(),
                r.embedded_text.as_deref(),
                model,
                &text,
            )
            .then_some(TypeToEmbed {
                id: r.id,
                kind: TypeKind::Relation,
                text,
                // 关系没有短查询那一路,只有整段这一份
                field: EmbedField::Full,
            })
        })
        .collect())
}

/// 类型那一行上两份向量的现状,判陈用
#[derive(sqlx::FromRow)]
struct StoredEmbedding {
    id: Uuid,
    label: String,
    description: String,
    embedded: bool,
    embedded_model: Option<String>,
    embedded_text: Option<String>,
    label_embedded: bool,
    label_embedded_model: Option<String>,
    label_embedded_text: Option<String>,
}

/// 没嵌过、换了模型、或者当时嵌的原文与现在要嵌的不一样
fn is_stale(
    embedded: bool,
    stored_model: Option<&str>,
    stored_text: Option<&str>,
    model: &str,
    text: &str,
) -> bool {
    !embedded || stored_model != Some(model) || stored_text != Some(text)
}

/// 回写向量,连同"嵌的是哪段字、用的哪个模型"。三者必须同一次写入——
/// 只写向量而不写来源,下一轮就会认为它还是陈的,从此每轮重嵌。
pub async fn set_type_embeddings(
    pool: &PgPool,
    model: &str,
    items: &[(TypeToEmbed, Vec<f32>)],
) -> AppResult<()> {
    let mut tx = pool.begin().await?;
    for (item, emb) in items {
        let table = match item.kind {
            TypeKind::Entity => "entity_types",
            TypeKind::Relation => "relation_types",
        };
        // 两份向量各写各的列(见 `entity_types.label_embedding`)。列名前缀不同,其余一模一样
        let (vec_col, text_col, model_col) = match item.field {
            EmbedField::Full => ("embedding", "embedded_text", "embedded_model"),
            EmbedField::Label => (
                "label_embedding",
                "label_embedded_text",
                "label_embedded_model",
            ),
        };
        sqlx::query(&format!(
            "UPDATE {table} SET {vec_col} = $2, {text_col} = $3, {model_col} = $4
             WHERE id = $1"
        ))
        .bind(item.id)
        .bind(Vector::from(emb.clone()))
        .bind(&item.text)
        .bind(model)
        .execute(&mut *tx)
        .await?;
    }
    tx.commit().await?;
    Ok(())
}

/// 与给定向量最近的 k 个实体类型。
///
/// **既没有描述、又不在分类树上的类不参加。** 导入一份词表时,凡被
/// domainIncludes / rangeIncludes / equivalentClass 引用到的外部 IRI 都会建成一行
/// (OMG、UNECE、GS1…),它们没有标签正文、没有父也没有子——不是词汇,是悬空引用。
///
/// 它们偏偏很能赢:`embed_text` 在描述为空时退化成只嵌标签,于是这一行嵌的
/// 就是 "Location" 一个词。短的那一侧距离系统性地更小(同一条规律在这个文件
/// 和类型消解里已经栽过三次),于是一个空壳压过了带 83 字定义的
/// `administrative_area`——实测 `杭州拱墅区` 正是这么丢的。
///
/// 而且就算端上去也判不了:裁决看到的是 `- location (location)`,没有定义可依。
/// 装 schema.org 的库里这样的行有 50 个,43 个连一条继承边都没有。
///
/// **只是不当候选,不删行**:domain / range 仍然指着它们,删了会断引用。
pub async fn nearest_entity_types(
    pool: &PgPool,
    kb_id: Uuid,
    embedding: &[f32],
    limit: i64,
    // true = 比只有 label 的那份向量(见 `entity_types.label_embedding`)。短说法走这一路:**短对短**,
    // 否则 `district. place` 会被 `Map\nA map.` 这类同义反复的一行话赢过去
    by_label: bool,
) -> AppResult<Vec<TypeCandidate>> {
    let col = if by_label {
        "label_embedding"
    } else {
        "embedding"
    };
    let rows: Vec<(Uuid, String, String, String, f64)> = sqlx::query_as(&format!(
        "SELECT id, key, label, coalesce(description, ''), ({col} <=> $2)::float8
         FROM entity_types t
         WHERE t.kb_id = $1 AND t.{col} IS NOT NULL
           AND (coalesce(btrim(t.description), '') <> ''
                OR EXISTS (SELECT 1 FROM entity_type_parents p
                           WHERE p.child_id = t.id OR p.parent_id = t.id))
         ORDER BY {col} <=> $2
         LIMIT $3"
    ))
    .bind(kb_id)
    .bind(Vector::from(embedding.to_vec()))
    .bind(limit)
    .fetch_all(pool)
    .await?;
    Ok(rows
        .into_iter()
        .map(|(id, key, label, description, distance)| TypeCandidate {
            id,
            key,
            label,
            description,
            kind: None,
            distance: distance as f32,
        })
        .collect())
}

/// 与给定向量最近的 k 个关系/属性。
///
/// `only_kind` 分道:字面值宾语的事实要找的是属性,实体宾语的要找的是关系。
/// 不分道就会把 `founding_date` 这种属性推给一条关系事实,反过来也一样。
pub async fn nearest_relation_types(
    pool: &PgPool,
    kb_id: Uuid,
    embedding: &[f32],
    limit: i64,
    only_kind: Option<&str>,
) -> AppResult<Vec<TypeCandidate>> {
    let rows: Vec<(Uuid, String, String, String, String, f64)> = sqlx::query_as(
        "SELECT id, key, label, coalesce(description, ''), kind, (embedding <=> $2)::float8
         FROM relation_types
         WHERE kb_id = $1 AND embedding IS NOT NULL
           AND ($4::text IS NULL OR kind = $4)
         ORDER BY embedding <=> $2
         LIMIT $3",
    )
    .bind(kb_id)
    .bind(Vector::from(embedding.to_vec()))
    .bind(limit)
    .bind(only_kind)
    .fetch_all(pool)
    .await?;
    Ok(rows
        .into_iter()
        .map(
            |(id, key, label, description, kind, distance)| TypeCandidate {
                id,
                key,
                label,
                description,
                kind: Some(kind),
                distance: distance as f32,
            },
        )
        .collect())
}

/// 把一个 IRI 认到已有的**本地**类上(原本没有 IRI 的那种)。
///
/// **只写 IRI 与形状,不动 label、description、颜色。** 认领要解决的是
/// "这棵树是断的",不是"用词汇表的说法覆盖用户的说法":种子类的描述是照着
/// 抽取调过的、且跟库的语言走,而 schema.org 的描述是英文样板。覆盖它等于
/// 悄悄换掉抽取提示词里最承重的那一句。
///
/// **形状要跟着改,因为形状说的就是来历**(方=词表声明的,圆=语料里长的)。
/// 一个类被认领成"词表声明的"却还画成圆,画面就在说谎。实测过这个缝:
/// 往一个已有 `person` / `organization` 的库里导 schema.org,
/// 那几个类拿到了 IRI 却仍是圆的——有 IRI 却是圆的,自相矛盾。
///
/// 颜色不动:颜色是**身份**(同一个 key 永远同一个色),认领不改变它是谁。
/// 形状是**来历**,认领恰恰改变了这一点。
///
/// 只在 `iri IS NULL` 时写,所以重复导入是幂等的,也绝不会抢走另一个
/// 词汇表已经认领的类。
pub async fn adopt_iri_onto_key(
    pool: &PgPool,
    kb_id: Uuid,
    key: &str,
    iri: &str,
) -> AppResult<Option<Uuid>> {
    let row: Option<(Uuid,)> = sqlx::query_as(
        "UPDATE entity_types SET iri = $3, shape = 'square', updated_at = now()
         WHERE kb_id = $1 AND key = $2 AND iri IS NULL
         RETURNING id",
    )
    .bind(kb_id)
    .bind(key)
    .bind(iri)
    .fetch_optional(pool)
    .await?;
    Ok(row.map(|(id,)| id))
}

pub async fn nearest_relation_type_ids(
    pool: &PgPool,
    kb_id: Uuid,
    embedding: &[f32],
    limit: i64,
    only_kind: Option<&str>,
) -> AppResult<Vec<Uuid>> {
    let rows: Vec<(Uuid,)> = sqlx::query_as(
        "SELECT id FROM relation_types
         WHERE kb_id = $1 AND embedding IS NOT NULL
           AND ($4::text IS NULL OR kind = $4)
         ORDER BY embedding <=> $2
         LIMIT $3",
    )
    .bind(kb_id)
    .bind(Vector::from(embedding.to_vec()))
    .bind(limit)
    .bind(only_kind)
    .fetch_all(pool)
    .await?;
    Ok(rows.into_iter().map(|(id,)| id).collect())
}

/// 这个库里有没有带向量的关系/属性(`only_kind` 同上)。谓词与
/// [`nearest_relation_type_ids`] 的一字不差:这里答「没有」,那边对任何向量都返回空。
///
/// 存在的理由:短语对齐的短名单先把每条签名嵌入、再逐条问最近的属性,问回来是空才知道
/// 属性还没向量。一个从没跑过 `embed_ontology` 的库每轮都把一万七千条签名送去嵌入,
/// 一条也用不上(#1097)。先问这一句,用不上就不嵌
pub async fn has_relation_type_vectors(
    pool: &PgPool,
    kb_id: Uuid,
    only_kind: Option<&str>,
) -> AppResult<bool> {
    Ok(sqlx::query_scalar(
        "SELECT EXISTS (SELECT 1 FROM relation_types
                        WHERE kb_id = $1 AND embedding IS NOT NULL
                          AND ($2::text IS NULL OR kind = $2))",
    )
    .bind(kb_id)
    .bind(only_kind)
    .fetch_one(pool)
    .await?)
}

/// 一次插完一批类,返回 key → id。
///
/// **存在的理由是 fsync。** 逐条 `execute(pool)` 每条各自提交,导入 schema.org
/// 那种量级(968 个类加约 1500 个属性)是五千次 fsync,实测 45 秒;同样的行数
/// 放进一条语句是 536 毫秒。差的不是往返,是提交。
///
/// `ON CONFLICT DO NOTHING` 而不是报错:撞 key 的处置在计划阶段已经判过了
/// ([`crate::ontology::create_entity_type_with_iri`] 的注释讲了为什么不覆盖),
/// 这里只是把计划落地,撞上说明计划与库不同步,跳过并让调用方从返回的 map 里
/// 发现少了谁。
pub async fn create_entity_types_bulk(
    pool: &PgPool,
    kb_id: Uuid,
    rows: &[(String, String, String, String)],
) -> AppResult<std::collections::HashMap<String, Uuid>> {
    if rows.is_empty() {
        return Ok(std::collections::HashMap::new());
    }
    for (key, ..) in rows {
        validate_key(key)?;
    }
    let keys: Vec<&str> = rows.iter().map(|r| r.0.as_str()).collect();
    let labels: Vec<&str> = rows.iter().map(|r| r.1.as_str()).collect();
    let descs: Vec<&str> = rows.iter().map(|r| r.2.as_str()).collect();
    let iris: Vec<&str> = rows.iter().map(|r| r.3.as_str()).collect();
    // 颜色在 Rust 侧按 key 算好,跟着 UNNEST 一起进去——
    // SQL 里调不到 Rust 函数,而这一批正是导入大本体走的路
    let colours: Vec<&str> = keys
        .iter()
        .map(|k| crate::palette::color_for_key(k))
        .collect();
    let shapes: Vec<&str> = iris.iter().map(|i| crate::palette::shape_for(i)).collect();
    let out: Vec<(Uuid, String)> = sqlx::query_as(
        "INSERT INTO entity_types (id, kb_id, key, label, color, shape, description, iri)
         SELECT gen_random_uuid(), $1, k, l, c, s, d, i
         FROM UNNEST($2::text[], $3::text[], $4::text[], $5::text[], $6::text[], $7::text[])
              AS t(k, l, d, i, c, s)
         ON CONFLICT (kb_id, key) DO NOTHING
         RETURNING id, key",
    )
    .bind(kb_id)
    .bind(&keys)
    .bind(&labels)
    .bind(&descs)
    .bind(&iris)
    .bind(&colours)
    .bind(&shapes)
    .fetch_all(pool)
    .await?;
    Ok(out.into_iter().map(|(id, k)| (k, id)).collect())
}

/// 批量建关系/属性时的一行。
///
/// **`functional` / `inverse_functional` 必须照词汇表写下去,不能默认 false。**
/// 它们是时态引擎自动闭合事实的依据,猜错会成批造假冲突——`part_of` 被误标成
/// functional 那次积了 59 条。
pub struct BulkRelation {
    pub key: String,
    pub label: String,
    pub description: String,
    pub iri: String,
    /// `relation` 或 `attribute`
    pub kind: &'static str,
    /// 只对属性有意义,关系传 `None`
    pub datatype: Option<String>,
    pub functional: bool,
    pub inverse_functional: bool,
    /// OWL 属性公理,一致性检查的判定依据(0002 R0)。
    /// 同样必须照词汇表写下去——`alias_of` 双向是对的、`produces` 双向是错的,
    /// 分开这两者的只能是本体
    pub transitive: bool,
    pub symmetric: bool,
    pub asymmetric: bool,
    pub irreflexive: bool,
    /// `state` / `event` / `eternal`(0031)。OWL 自己没有这个概念,标准词表里的对象
    /// 属性全是 `state`;只有本体用 `utopia:temporal` 说了的才不是——导出端写的那一条
    pub temporal: String,
}

/// 一次插完一批关系或属性,返回 key → id。语义同 [`create_entity_types_bulk`]。
///
/// `kind` 决定走关系通道还是属性通道;`datatype` 只对属性有意义,关系传 `None`。
/// `temporal` 照每一行写:没有 `utopia:temporal` 注解的本体一律 `state`
///(与单条版的默认一致),写了的按它说的。
pub async fn create_relation_types_bulk(
    pool: &PgPool,
    kb_id: Uuid,
    rows: &[BulkRelation],
) -> AppResult<std::collections::HashMap<String, Uuid>> {
    if rows.is_empty() {
        return Ok(std::collections::HashMap::new());
    }
    for r in rows {
        validate_key(&r.key)?;
        validate_temporal(&r.temporal)?;
    }
    let keys: Vec<&str> = rows.iter().map(|r| r.key.as_str()).collect();
    // 导入来的词表自己就可能不一致(unece.org 里 `brandName` 与
    // `ApplicableCertificate` 并存)——落库前统一,真身留在 `iri` 里
    let camel: Vec<String> = rows.iter().map(|r| lower_camel(&r.label)).collect();
    let labels: Vec<&str> = camel.iter().map(String::as_str).collect();
    let descs: Vec<&str> = rows.iter().map(|r| r.description.as_str()).collect();
    let iris: Vec<&str> = rows.iter().map(|r| r.iri.as_str()).collect();
    let kinds: Vec<&str> = rows.iter().map(|r| r.kind).collect();
    let dts: Vec<Option<&str>> = rows.iter().map(|r| r.datatype.as_deref()).collect();
    let funcs: Vec<bool> = rows.iter().map(|r| r.functional).collect();
    let invs: Vec<bool> = rows.iter().map(|r| r.inverse_functional).collect();
    let trans: Vec<bool> = rows.iter().map(|r| r.transitive).collect();
    let syms: Vec<bool> = rows.iter().map(|r| r.symmetric).collect();
    let asyms: Vec<bool> = rows.iter().map(|r| r.asymmetric).collect();
    let irrefs: Vec<bool> = rows.iter().map(|r| r.irreflexive).collect();
    let temporals: Vec<&str> = rows.iter().map(|r| r.temporal.as_str()).collect();
    let out: Vec<(Uuid, String)> = sqlx::query_as(
        "INSERT INTO relation_types
             (id, kb_id, key, label, temporal, functional, inverse_functional,
              description, kind, datatype, iri,
              is_transitive, is_symmetric, is_asymmetric, is_irreflexive)
         SELECT gen_random_uuid(), $1, k, l, tm, fu, iv, d, kind, dt, i,
                tr, sy, asym, irr
         FROM UNNEST($2::text[], $3::text[], $4::text[], $5::text[], $6::text[], $7::text[],
                     $8::bool[], $9::bool[], $10::bool[], $11::bool[], $12::bool[], $13::bool[],
                     $14::text[])
              AS t(k, l, d, i, kind, dt, fu, iv, tr, sy, asym, irr, tm)
         ON CONFLICT (kb_id, key) DO NOTHING
         RETURNING id, key",
    )
    .bind(kb_id)
    .bind(&keys)
    .bind(&labels)
    .bind(&descs)
    .bind(&iris)
    .bind(&kinds)
    .bind(&dts)
    .bind(&funcs)
    .bind(&invs)
    .bind(&trans)
    .bind(&syms)
    .bind(&asyms)
    .bind(&irrefs)
    .bind(&temporals)
    .fetch_all(pool)
    .await?;
    Ok(out.into_iter().map(|(id, k)| (k, id)).collect())
}

/// 一次写完一批关系的 domain / range。
///
/// 单条版 [`set_domains_ranges`] 内部已经用 unnest 省了往返,但它对**每条关系**
/// 都要跑 4 条语句(两张表各一次 DELETE 一次 INSERT)。1500 条关系就是 6000 次
/// 独立提交,而提交才是代价。这里把所有关系的关联行摊平成两条语句。
///
/// **不 DELETE**:调用方是刚建出来的新关系,关联表上不可能有旧行。
/// 更新既有关系仍然走单条版。
pub async fn link_domains_ranges_bulk(
    pool: &PgPool,
    domains: &[(Uuid, Uuid)],
    ranges: &[(Uuid, Uuid)],
) -> AppResult<()> {
    for (table, pairs) in [
        ("relation_type_domains", domains),
        ("relation_type_ranges", ranges),
    ] {
        if pairs.is_empty() {
            continue;
        }
        let rels: Vec<Uuid> = pairs.iter().map(|p| p.0).collect();
        let types: Vec<Uuid> = pairs.iter().map(|p| p.1).collect();
        sqlx::query(&format!(
            "INSERT INTO {table} (relation_type_id, entity_type_id)
             SELECT r, t FROM UNNEST($1::uuid[], $2::uuid[]) AS x(r, t)
             ON CONFLICT DO NOTHING"
        ))
        .bind(&rels)
        .bind(&types)
        .execute(pool)
        .await?;
    }
    Ok(())
}

/// 一次设完一批类的父类。语义同 [`set_parents`],但**不查环**。
///
/// 单条版每次都要跑一个递归 CTE 查环,一千个类就是一千次递归查询。
/// 这里只用于导入新建的类:环是上游词汇表的问题,而 `set_parents` 对环的处置
/// 本来也只是跳过那一条(`let _ =`),不是中断导入。导入完之后本体页
/// 仍然能发现并让人处理。
pub async fn set_parents_bulk(pool: &PgPool, pairs: &[(Uuid, Uuid)]) -> AppResult<()> {
    if pairs.is_empty() {
        return Ok(());
    }
    let children: Vec<Uuid> = pairs.iter().map(|p| p.0).collect();
    let parents: Vec<Uuid> = pairs.iter().map(|p| p.1).collect();
    sqlx::query(
        "INSERT INTO entity_type_parents (child_id, parent_id)
         SELECT c, p FROM UNNEST($1::uuid[], $2::uuid[]) AS x(c, p)
         WHERE c <> p
         ON CONFLICT DO NOTHING",
    )
    .bind(&children)
    .bind(&parents)
    .execute(pool)
    .await?;
    Ok(())
}

/// 类互斥落库(见 `relation_types` 的公理列)。语义同 [`set_parents_bulk`]。
///
/// **两个方向都写。** 解析侧已经把 `owl:disjointWith` 的对称性展开成两条,
/// 这里照写即可——查"A 与 B 互斥吗"因此不必关心从哪一头问。
///
/// `a <> b` 挡自指:自己跟自己互斥是无意义的声明,而它会让一致性检查
/// 把每个实体都报成矛盾。表上也有同样的 CHECK,两道都留着——
/// 约束是最后一道,过滤在这里是为了不让一整批插入因为一条脏数据整个失败。
pub async fn set_disjoint_bulk(
    pool: &PgPool,
    kb_id: Uuid,
    pairs: &[(Uuid, Uuid)],
) -> AppResult<()> {
    if pairs.is_empty() {
        return Ok(());
    }
    let a: Vec<Uuid> = pairs.iter().map(|p| p.0).collect();
    let b: Vec<Uuid> = pairs.iter().map(|p| p.1).collect();
    sqlx::query(
        "INSERT INTO entity_type_disjoint (kb_id, a_id, b_id)
         SELECT $1, x, y FROM UNNEST($2::uuid[], $3::uuid[]) AS t(x, y)
         WHERE x <> y
         ON CONFLICT DO NOTHING",
    )
    .bind(kb_id)
    .bind(&a)
    .bind(&b)
    .execute(pool)
    .await?;
    Ok(())
}

/// 把 `others` 设成这个类的**全部**互斥对象(不在其中的解除)。
///
/// 与 [`set_disjoint_bulk`] 的分工:那个是导入用的「只增不减」,这个是编辑用的
/// 「这就是全部」。编辑必须能取消——否则界面上取消勾选没有任何效果,
/// 而用户会以为自己改了。
///
/// 两个方向各写一行,与导入侧一致:查「A 与 B 互斥吗」因此不必关心从哪头问。
pub async fn set_disjoint_for(
    pool: &PgPool,
    kb_id: Uuid,
    class: Uuid,
    others: &[Uuid],
) -> AppResult<()> {
    let mut tx = pool.begin().await?;
    // 先清掉这个类参与的全部互斥边——两个方向都要清,因为它两边都可能出现
    sqlx::query(
        "DELETE FROM entity_type_disjoint
          WHERE kb_id = $1 AND (a_id = $2 OR b_id = $2)",
    )
    .bind(kb_id)
    .bind(class)
    .execute(&mut *tx)
    .await?;
    for other in others {
        if *other == class {
            continue;
        }
        sqlx::query(
            "INSERT INTO entity_type_disjoint (kb_id, a_id, b_id)
             VALUES ($1, $2, $3), ($1, $3, $2)
             ON CONFLICT DO NOTHING",
        )
        .bind(kb_id)
        .bind(class)
        .bind(other)
        .execute(&mut *tx)
        .await?;
    }
    tx.commit().await?;
    Ok(())
}

// ---------------------------------------------------------------------------
// 本体提案(见 `ontology_proposals`)
// ---------------------------------------------------------------------------

/// 一条落库的提案。`payload` 是接口原样返回的那一条。代理提的(0061)多带三样:
/// 它服务的问题、它会绑上的形状,和谁提的
#[derive(Debug, Clone, sqlx::FromRow)]
pub struct StoredProposal {
    pub section: String,
    pub key: String,
    pub payload: serde_json::Value,
    /// suggest | agent
    pub proposed_by: String,
    pub serves: Vec<Uuid>,
    pub signatures: serde_json::Value,
}

/// 代理的一条提案(0061 决定 2):形状同 `save_proposals` 的一项,外加它服务的问题与会绑的形状
pub struct AgentProposal {
    pub section: String,
    pub key: String,
    pub payload: serde_json::Value,
    pub serves: Vec<Uuid>,
    pub signatures: serde_json::Value,
}

/// 把代理的一轮提案写下来。已经有人表过态的不动(同 `save_proposals`);同一个键再提是刷新,
/// 服务的问题与形状一起刷
pub async fn save_agent_proposals(
    pool: &PgPool,
    kb_id: Uuid,
    items: &[AgentProposal],
) -> AppResult<()> {
    for it in items {
        sqlx::query(
            "INSERT INTO ontology_proposals
                 (id, kb_id, section, key, payload, proposed_by, serves, signatures)
             VALUES ($1, $2, $3, $4, $5, 'agent', $6, $7)
             ON CONFLICT (kb_id, section, key) DO UPDATE
               SET payload = EXCLUDED.payload, proposed_by = 'agent',
                   serves = EXCLUDED.serves, signatures = EXCLUDED.signatures,
                   created_at = now()
               WHERE ontology_proposals.status = 'open'",
        )
        .bind(Uuid::now_v7())
        .bind(kb_id)
        .bind(&it.section)
        .bind(&it.key)
        .bind(&it.payload)
        .bind(&it.serves)
        .bind(&it.signatures)
        .execute(pool)
        .await?;
    }
    Ok(())
}

/// 代理已经提过的形状(不论人怎么表的态):下一轮不再为它们提——被拒的尤其不再提
pub async fn signatures_already_proposed(
    pool: &PgPool,
    kb_id: Uuid,
) -> AppResult<Vec<serde_json::Value>> {
    Ok(sqlx::query_scalar(
        "SELECT signatures FROM ontology_proposals WHERE kb_id = $1 AND proposed_by = 'agent'",
    )
    .bind(kb_id)
    .fetch_all(pool)
    .await?)
}

/// 一条提案被拒了,连理由(没写就空着)。
///
/// **改状态而不是删行**:拒绝发生过,跟 `fact_adoptions`、`entity_retypes` 同一条路。
/// 留痕还有个当下就用得着的作用——代理下一轮不会把它刷回待看。
pub async fn reject_proposal(
    pool: &PgPool,
    kb_id: Uuid,
    section: &str,
    key: &str,
    reason: Option<&str>,
    actor: Uuid,
) -> AppResult<()> {
    sqlx::query(
        "UPDATE ontology_proposals
            SET status = 'rejected', reason = $4, decided_by = $5, decided_at = now()
          WHERE kb_id = $1 AND section = $2 AND key = $3 AND status = 'open'",
    )
    .bind(kb_id)
    .bind(section)
    .bind(key)
    .bind(reason.map(str::trim).filter(|r| !r.is_empty()))
    .bind(actor)
    .execute(pool)
    .await?;
    Ok(())
}

/// 一条还开着的提案,按键取(代理把这一轮的 map_to 并进上一轮的时候读它)
pub async fn open_proposal(
    pool: &PgPool,
    kb_id: Uuid,
    section: &str,
    key: &str,
) -> AppResult<Option<StoredProposal>> {
    Ok(sqlx::query_as(
        "SELECT section, key, payload, proposed_by, serves, signatures FROM ontology_proposals
         WHERE kb_id = $1 AND section = $2 AND key = $3 AND status = 'open'",
    )
    .bind(kb_id)
    .bind(section)
    .bind(key)
    .fetch_optional(pool)
    .await?)
}

/// 还等着人看的提案。新的排前面——旧的那批已经被看过好几眼了。
pub async fn open_proposals(pool: &PgPool, kb_id: Uuid) -> AppResult<Vec<StoredProposal>> {
    Ok(sqlx::query_as(
        "SELECT section, key, payload, proposed_by, serves, signatures FROM ontology_proposals
         WHERE kb_id = $1 AND status = 'open'
         ORDER BY created_at DESC, key",
    )
    .bind(kb_id)
    .fetch_all(pool)
    .await?)
}

/// 这些类的全部祖先(不含自己)。沿 `subClassOf` 上溯,多继承与菱形都走得通。
///
/// 给按块检索的候选补地板用:向量检索偏爱字面出现在正文里的叶子类,
/// 泛化基类排得很后(实测 `person` 在 976 个类里排第 359),于是提示词里
/// 没有它们——实体无处落脚,关系签名也退化成 `*`。祖先是本体自己声明的
/// 泛化关系,拿它补比维护一张「通用类」清单可靠。
pub async fn ancestors_of(pool: &PgPool, ids: &[Uuid]) -> AppResult<Vec<Uuid>> {
    if ids.is_empty() {
        return Ok(Vec::new());
    }
    // 递归项里 UNION 去重,菱形继承不会把同一个祖先展开两次
    let rows: Vec<(Uuid,)> = sqlx::query_as(
        "WITH RECURSIVE up(id) AS (
             SELECT unnest($1::uuid[])
             UNION
             SELECT p.parent_id FROM entity_type_parents p JOIN up ON p.child_id = up.id
         )
         SELECT id FROM up WHERE id <> ALL($1::uuid[])",
    )
    .bind(ids)
    .fetch_all(pool)
    .await?;
    Ok(rows.into_iter().map(|(id,)| id).collect())
}

/// 把 `owl:inverseOf` / `rdfs:subPropertyOf` 从 IRI 解析成 id。
///
/// **必须是第二遍。** 这两条指的是另一个关系类型,而 id 要等全部插完才有——
/// 一遍过的写法只能处理「父属性恰好排在前面」的文件,而 RDF 三元组没有顺序。
///
/// 按 IRI 配对而不是按 key:key 会因为撞名加后缀(`part_of_2`),
/// 而 IRI 是这份本体里的身份。
pub async fn link_property_axioms_bulk(
    pool: &PgPool,
    kb_id: Uuid,
    inverse: &[(String, String)],
    sub_property: &[(String, String)],
) -> AppResult<(u64, u64)> {
    let run = |column: &'static str, pairs: &[(String, String)]| {
        let src: Vec<String> = pairs.iter().map(|(s, _)| s.clone()).collect();
        let dst: Vec<String> = pairs.iter().map(|(_, d)| d.clone()).collect();
        async move {
            if src.is_empty() {
                return AppResult::Ok(0);
            }
            // 目标 IRI 在这个库里找不到就跳过这一条——**部分导入是常态**
            // (引用了外部词汇表里的属性),一条连不上不该让整次导入失败
            let sql = format!(
                "UPDATE relation_types r SET {column} = t.id
                   FROM UNNEST($2::text[], $3::text[]) AS p(src, dst)
                   JOIN relation_types t ON t.kb_id = $1 AND t.iri = p.dst
                  WHERE r.kb_id = $1 AND r.iri = p.src AND r.id <> t.id"
            );
            let n = sqlx::query(&sql)
                .bind(kb_id)
                .bind(&src)
                .bind(&dst)
                .execute(pool)
                .await?
                .rows_affected();
            AppResult::Ok(n)
        }
    };
    let inv = run("inverse_of", inverse).await?;
    let sub = run("sub_property_of", sub_property).await?;
    Ok((inv, sub))
}

#[cfg(test)]
mod name_shape_tests {
    use super::lower_camel;

    #[test]
    fn separators_become_camel_humps() {
        assert_eq!(lower_camel("access to"), "accessTo");
        assert_eq!(lower_camel("collaborated with"), "collaboratedWith");
        assert_eq!(lower_camel("works_for"), "worksFor");
        assert_eq!(lower_camel("date-applicability"), "dateApplicability");
        // 连着几个分隔符只算一次
        assert_eq!(lower_camel("called   for"), "calledFor");
        assert_eq!(lower_camel("  start date  "), "startDate");
    }

    #[test]
    fn only_the_first_letter_is_lowered() {
        assert_eq!(
            lower_camel("ApplicableCertificate"),
            "applicableCertificate"
        );
        assert_eq!(lower_camel("EffectiveEndDateTime"), "effectiveEndDateTime");
    }

    /// **这条是这个函数存在的理由之一**:从 `key` 反推做不到,
    /// `product_id` 拼回去只会得到 `productId`
    #[test]
    fn acronyms_are_left_alone() {
        assert_eq!(lower_camel("productID"), "productID");
        assert_eq!(lower_camel("hasLEI"), "hasLEI");
        assert_eq!(lower_camel("accessibilityAPI"), "accessibilityAPI");
        assert_eq!(
            lower_camel("checkoutPageURLTemplate"),
            "checkoutPageURLTemplate"
        );
    }

    #[test]
    fn already_right_is_untouched() {
        for s in ["owns", "acceptedAnswer", "worksFor", "3DModel"] {
            assert_eq!(lower_camel(s), s, "{s} 不该被动");
        }
    }

    #[test]
    fn idempotent() {
        for s in ["access to", "ApplicableCertificate", "productID", "owns"] {
            let once = lower_camel(s);
            assert_eq!(lower_camel(&once), once, "{s} 归一两次结果要一样");
        }
    }
}

/// 两个数里的第二个(0061 决定 5):代理的提案里,人表过态的有几条,其中拒掉的、改过再采纳的各几条
#[derive(Debug, Clone, serde::Serialize, sqlx::FromRow)]
pub struct AgentProposalReport {
    pub open: i64,
    pub adopted: i64,
    pub adopted_edited: i64,
    pub rejected: i64,
}

/// 文档说了、本体还放不下的:没绑到类的类别词,和没绑到属性的短语形状(判成 none 的
/// 与两票不一致的)。本体代理读的就是这两样(0061 决定 2);工作台拿这两个数说「还缺什么」,
/// 不再拿 0003 的 `ontology_misses`——开放图谱的抽取不往那张表里写
#[derive(Debug, Clone, Copy, PartialEq, Eq, sqlx::FromRow, serde::Serialize)]
pub struct Uncovered {
    pub kind_words: i64,
    pub phrases: i64,
}

pub async fn uncovered(pool: &PgPool, kb_id: Uuid) -> AppResult<Uncovered> {
    Ok(sqlx::query_as(
        "SELECT (SELECT count(*) FROM type_bindings
                  WHERE kb_id = $1 AND status <> 'bound') AS kind_words,
                (SELECT count(*) FROM phrase_bindings
                  WHERE kb_id = $1 AND status <> 'bound') AS phrases",
    )
    .bind(kb_id)
    .fetch_one(pool)
    .await?)
}

pub async fn agent_proposal_report(pool: &PgPool, kb_id: Uuid) -> AppResult<AgentProposalReport> {
    Ok(sqlx::query_as(
        "SELECT count(*) FILTER (WHERE status = 'open') AS open,
                count(*) FILTER (WHERE status = 'adopted') AS adopted,
                count(*) FILTER (WHERE status = 'adopted' AND edited) AS adopted_edited,
                count(*) FILTER (WHERE status = 'rejected') AS rejected
           FROM ontology_proposals WHERE kb_id = $1 AND proposed_by = 'agent'",
    )
    .bind(kb_id)
    .fetch_one(pool)
    .await?)
}