Files
ssw-ontology/server/display_name.go
T
admin e7b39805fb feat(backup): 按 schema 镜像 + 请求级 search_path 切库 (issue #4 #5 后续)
「让客户端敢操作」的关键能力:写前/写后打一份快照 → 任意 GET 带 X-Snapshot-Id
 头即可命中 backups_<id> schema 的同名表(业务 SQL 不带 schema 前缀照样切)。

 设计要点:
   - 备份 = 独立 schema backups_<id>(真表,不是单存 JSONB)—— 查询性能与活库一致
   - snapshotRouter 中间件:BeginTx + SET LOCAL search_path → 把 a.pool 临时换
     为事务视图 txPool → handler 结束 commit + 还原 a.pool。业务代码一行不改。
   - a.pool 字段类型从 *pgxpool.Pool 升级为 dbRunner interface(中间件可换 txPool)。
   - 11 个 helper 函数签名同步改为 dbExec(与现有 dbExec 共存,无破坏性)。
   - 写方法(POST/PUT/PATCH/DELETE)带快照头 → 403 拒绝(mistake-safety)。

 接口:
   - POST /api/v1/backups 创建
   - GET /api/v1/backups 列表
   - GET /api/v1/backups/:id 元信息(含 schema_name)
   - GET /api/v1/backups/:id/switch 切库提示
   - DELETE /api/v1/backups/:id 级联删 schema
   - 支持 X-Snapshot-Id (直接 run id) + X-Snapshot-Ts (秒级时间戳) 两种切换入口

 MCP 工具 (5 个):backup_create / backup_list / backup_inspect / backup_switch / backup_delete

 测试 (22 个全绿,~5.5s 集成):
   - SnapshotRouter:改前建快照 → 改后读快照只见改前
   - SnapshotSearchPathPersist:不污染下一个请求
   - SnapshotByTimestamp:ts 头也能切库
   - SnapshotDeleteCleansSchema:delete 真 DROP schema
   - BackupLifecycle / BackupDiffAfterMutation:完整 create→list→inspect→switch→delete

 文档:docs/BACKUP.md 写清用法、机制、客户端工作流;CHANGELOG.md [1.3.0]。
2026-09-07 11:35:47 +08:00

147 lines
4.8 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package main
import (
"context"
"fmt"
"log"
"strings"
"sync"
"time"
)
// ---------- 显示名(Display Name)物化 ----------
//
// 问题背景(2026-09-05 扫描发现):
// objects.name 历来只在写入时从 properties.name 取值。但大量对象类型的"显示名"
// 根本不叫 name —— 本库 DataDemand 用 demand_name、DataSample 用 sample_name,
// 外部数字孪生本体里 TimelineEvent 用 title、Person 用 real_name。
// 结果:本库 3576 个实例里 1615 个(45%)name 列为空,而检索/列表/图谱/排名
// 全都依赖 name 列 —— 这些实例在默认检索下**完全搜不到**,形同隐身。
//
// 平台其实早有基础设施:object_types.title_property(Palantir 对标 P1-1 引入)就是
// 用来声明"这个类型的主标题属性"。本库 47 个类型里已有 5 个配了 title_property,
// 但从未参与 name 物化。这里把它接上,并补一条通用回退链兜底。
//
// 回退顺序:title_property(类型声明) → name → title → real_name → display_name → label
// displayNameFallback 显示名回退链(title_property 未配置或取不到值时按序尝试)。
var displayNameFallback = []string{"name", "title", "real_name", "display_name", "label"}
// resolveDisplayName 按 title_property → 回退链 计算对象显示名。
func resolveDisplayName(titleProp string, props map[string]interface{}) string {
if titleProp != "" {
if v := propString(props[titleProp]); v != "" {
return v
}
}
for _, k := range displayNameFallback {
if v := propString(props[k]); v != "" {
return v
}
}
return ""
}
// propString 把属性值转成字符串(数字/bool 也转成字面量,避免显示名为空)。
func propString(v interface{}) string {
switch t := v.(type) {
case nil:
return ""
case string:
return strings.TrimSpace(t)
case float64:
return fmt.Sprintf("%v", t)
case bool:
if t {
return "true"
}
return "false"
default:
s := strings.TrimSpace(fmt.Sprintf("%v", t))
if s == "<nil>" || s == "[]" || s == "map[]" {
return ""
}
return s
}
}
// ---------- title_property 缓存 ----------
// 批量写入时会按对象反复取 title_property,缓存 60s 避免逐条查库。
var (
titlePropMu sync.RWMutex
titlePropCache = map[string]string{}
titlePropAt = time.Time{}
)
func (a *app) titlePropOf(ctx context.Context, typ string) string {
titlePropMu.RLock()
if time.Since(titlePropAt) < 60*time.Second {
if v, ok := titlePropCache[typ]; ok {
titlePropMu.RUnlock()
return v
}
}
titlePropMu.RUnlock()
var v string
_ = a.pool.QueryRow(ctx,
`SELECT COALESCE(title_property,'') FROM object_types WHERE api_name=$1`, typ).Scan(&v)
titlePropMu.Lock()
if time.Since(titlePropAt) >= 60*time.Second {
titlePropCache = map[string]string{}
titlePropAt = time.Now()
}
titlePropCache[typ] = v
titlePropMu.Unlock()
return v
}
// invalidateTitlePropCache 类型定义变更(改 title_property / 删类型)后调用。
func invalidateTitlePropCache() {
titlePropMu.Lock()
titlePropAt = time.Time{}
titlePropMu.Unlock()
}
// backfillDisplayNames 存量修复:把 name 为空的实例按 title_property + 回退链补上。
// 幂等(只处理 COALESCE(name,'')=''),且不改 updated_at,避免制造假的"最近更新"。
func backfillDisplayNames(ctx context.Context, p dbExec) error {
tag, err := p.Exec(ctx, `
UPDATE objects o SET name = COALESCE(
NULLIF(o.properties_json->>NULLIF(ot.title_property,''), ''),
NULLIF(o.properties_json->>'name',''),
NULLIF(o.properties_json->>'title',''),
NULLIF(o.properties_json->>'real_name',''),
NULLIF(o.properties_json->>'display_name',''),
NULLIF(o.properties_json->>'label','')
)
FROM object_types ot
WHERE ot.id = o.object_type_id
AND COALESCE(o.name,'') = ''
AND COALESCE(
NULLIF(o.properties_json->>NULLIF(ot.title_property,''), ''),
NULLIF(o.properties_json->>'name',''),
NULLIF(o.properties_json->>'title',''),
NULLIF(o.properties_json->>'real_name',''),
NULLIF(o.properties_json->>'display_name',''),
NULLIF(o.properties_json->>'label','')
) IS NOT NULL`)
if err != nil {
return fmt.Errorf("显示名存量回填失败: %w", err)
}
if tag.RowsAffected() > 0 {
log.Printf("[migrate] 显示名存量回填: %d 个实例补上了 name(此前默认检索搜不到它们)", tag.RowsAffected())
}
return nil
}
// refreshDisplayName 单实例显示名重算(属性变更后调用,保证 name 列与显示名一致)。
func (a *app) refreshDisplayName(ctx context.Context, typ, pk string, props map[string]interface{}) {
nm := resolveDisplayName(a.titlePropOf(ctx, typ), props)
if nm == "" {
return
}
_, _ = a.pool.Exec(ctx, `UPDATE objects SET name=$1 WHERE type_api_name=$2 AND pk=$3`, nm, typ, pk)
}