Files
ssw-ontology/server/ontology_export.go
T

246 lines
7.6 KiB
Go

package main
import (
"fmt"
"sort"
"strings"
)
// 本体 schema 的 W3C Turtle 导出(GB/T 48000.3-2026 §5.3:标准序列化存储和交换)。
// 单向导出:平台是运行时权威,Turtle 只作交换/审查格式,不做导入。
type schemaPropExport struct {
IRI, APIName, DisplayName, Description, DataType string
// DisplayNameLang 多语标签(GB/T 48000.3-2026 附录 A.1.3);空=回退 DisplayName。
DisplayNameLang map[string]string
}
type schemaTypeExport struct {
IRI, APIName, DisplayName, Description string
// DisplayNameLang 多语标签(GB/T 48000.3-2026 附录 A.1.3);空=回退 DisplayName。
DisplayNameLang map[string]string
Properties []schemaPropExport
// Axioms 公理声明(GB/T 48000.3-2026 §8.2)。读路径与 schemaTypeExport 同体,不参与 JSON 序列化
// (端点已有 ObjectType.Axioms 走标准 JSON 路径);此处只用于 Turtle 导出。
Axioms typeAxioms
// ParentAPIName 父类型 api_name(用于 rdfs:subClassOf 声明);不参与 JSON 序列化(读路径有专门 echo 字段)。
ParentAPIName string `json:"-"`
}
type schemaLinkExport struct {
IRI, APIName, DisplayName, Description, SourceIRI, TargetIRI string
// DisplayNameLang 多语标签(GB/T 48000.3-2026 附录 A.1.3);空=回退 DisplayName。
DisplayNameLang map[string]string
}
type schemaSnapshot struct {
BaseIRI string
Types []schemaTypeExport
Links []schemaLinkExport
}
// turtleRange 平台 data_type → XSD 词表;未识别类型兜底 xsd:string(导出永不失败原则)。
func turtleRange(dataType string) string {
switch dataType {
case "integer":
return "xsd:integer"
case "number":
return "xsd:decimal"
case "boolean":
return "xsd:boolean"
case "date":
return "xsd:date"
case "datetime":
return "xsd:dateTime"
case "uri":
return "xsd:anyURI"
default: // string / text / enum / json / geoshape / ...
return "xsd:string"
}
}
// turtleLiteral 输出 Turtle 合法的字符串字面量。Go %q 产生 \a/\v 等不在 Turtle 转义表的
// 序列(rasqal/rapper 解析失败);按 W3C Turtle 转义表实现:
// \b \t \n \f \r \" \\ 按字面;其余 0x00-0x1f / 0x7f → \uXXXX;可打印(含中文)原样。
// < > 安全保留(它们在引号内只是普通字符)。
func turtleLiteral(s string) string {
var b strings.Builder
b.Grow(len(s) + 2)
b.WriteByte('"')
for _, r := range s {
switch r {
case '\b':
b.WriteString(`\b`)
case '\t':
b.WriteString(`\t`)
case '\n':
b.WriteString(`\n`)
case '\f':
b.WriteString(`\f`)
case '\r':
b.WriteString(`\r`)
case '"':
b.WriteString(`\"`)
case '\\':
b.WriteString(`\\`)
default:
if r < 0x20 || r == 0x7f {
fmt.Fprintf(&b, `\u%04X`, r)
} else {
b.WriteRune(r)
}
}
}
b.WriteByte('"')
return b.String()
}
// turtleLabels 多语 rdfs:label 片段:非空语言地图 → 每语言一条 "…"@tag(键排序保确定性);
// 空 → 回退单语 display_name 普通字面量(旧列语义不变)。
func turtleLabels(lang map[string]string, fallback string) string {
if len(lang) == 0 {
return "rdfs:label " + turtleLiteral(fallback)
}
keys := make([]string, 0, len(lang))
for k := range lang {
keys = append(keys, k)
}
sort.Strings(keys)
parts := make([]string, 0, len(keys))
for _, k := range keys {
parts = append(parts, fmt.Sprintf("rdfs:label %s@%s", turtleLiteral(lang[k]), k))
}
return strings.Join(parts, " ;\n ")
}
// buildTurtle 把 schema 快照序列化为 Turtle 文本。
// 映射:ObjectType→owl:Class;数据 Property→owl:DatatypeProperty(domain=所属类);
// LinkType→owl:ObjectProperty(domain/range=两端类)。
func buildTurtle(s schemaSnapshot) string {
var b strings.Builder
b.WriteString("@prefix owl: <http://www.w3.org/2002/07/owl#> .\n")
b.WriteString("@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .\n")
b.WriteString("@prefix xsd: <http://www.w3.org/2001/XMLSchema#> .\n\n")
// 索引(便于公理/继承段 OWL IRI 解析)
typeIRI := make(map[string]string, len(s.Types))
for _, t := range s.Types {
typeIRI[t.APIName] = t.IRI
}
linkIRI := make(map[string]string, len(s.Links))
for _, l := range s.Links {
linkIRI[l.APIName] = l.IRI
}
ont := strings.TrimSuffix(s.BaseIRI, "#")
fmt.Fprintf(&b, "<%s> a owl:Ontology ; rdfs:label \"ontology-platform schema export\" .\n\n", ont)
for _, t := range s.Types {
fmt.Fprintf(&b, "<%s> a owl:Class ;\n", t.IRI)
fmt.Fprintf(&b, " %s", turtleLabels(t.DisplayNameLang, t.DisplayName))
if t.Description != "" {
fmt.Fprintf(&b, " ;\n rdfs:comment %s", turtleLiteral(t.Description))
}
if t.ParentAPIName != "" {
if pi, ok := typeIRI[t.ParentAPIName]; ok {
fmt.Fprintf(&b, " ;\n rdfs:subClassOf <%s>", pi)
}
}
b.WriteString(" .\n")
for _, p := range t.Properties {
fmt.Fprintf(&b, "<%s> a owl:DatatypeProperty ;\n", p.IRI)
fmt.Fprintf(&b, " rdfs:domain <%s> ;\n", t.IRI)
fmt.Fprintf(&b, " rdfs:range %s", turtleRange(p.DataType))
if p.DisplayName != "" || len(p.DisplayNameLang) > 0 {
fmt.Fprintf(&b, " ;\n %s", turtleLabels(p.DisplayNameLang, p.DisplayName))
}
if p.Description != "" {
fmt.Fprintf(&b, " ;\n rdfs:comment %s", turtleLiteral(p.Description))
}
b.WriteString(" .\n")
}
b.WriteString("\n")
}
for _, l := range s.Links {
fmt.Fprintf(&b, "<%s> a owl:ObjectProperty ;\n", l.IRI)
fmt.Fprintf(&b, " rdfs:domain <%s> ;\n", l.SourceIRI)
fmt.Fprintf(&b, " rdfs:range <%s>", l.TargetIRI)
if l.DisplayName != "" || len(l.DisplayNameLang) > 0 {
fmt.Fprintf(&b, " ;\n %s", turtleLabels(l.DisplayNameLang, l.DisplayName))
}
if l.Description != "" {
fmt.Fprintf(&b, " ;\n rdfs:comment %s", turtleLiteral(l.Description))
}
b.WriteString(" .\n")
}
// 公理导出(GB/T 48000.3-2026 §8.1 OWL 形式化):
// disjointWith → owl:disjointWith(成对去重,反方亦算重复)
// equivalentTo → owl:equivalentClass(对称去重)
// functionalLinks → owl:FunctionalProperty(按 IRI 去重)
// inverseOf → owl:inverseOf(按排序后端点键去重)
// dateOrder 是跨属性时序规则,OWL2 不可表达(SHACL 可,本平台边界不建)——不导出;
// 运行期由 validateDateOrder(任务 4)在 applyObjectUpsert 入口统一守约。
seenDisjoint := map[string]bool{}
seenEquivalent := map[string]bool{}
seenFunc := map[string]bool{}
seenInverse := map[string]bool{}
for _, t := range s.Types {
for _, d := range t.Axioms.DisjointWith {
di, ok := typeIRI[d]
if !ok {
continue
}
k1 := t.APIName + "|" + d
k2 := d + "|" + t.APIName
if seenDisjoint[k1] || seenDisjoint[k2] {
continue
}
seenDisjoint[k1] = true
fmt.Fprintf(&b, "<%s> owl:disjointWith <%s> .\n", t.IRI, di)
}
for _, e := range t.Axioms.EquivalentTo {
ei, ok := typeIRI[e]
if !ok {
continue
}
k1 := t.APIName + "|" + e
k2 := e + "|" + t.APIName
if seenEquivalent[k1] || seenEquivalent[k2] {
continue
}
seenEquivalent[k1] = true
fmt.Fprintf(&b, "<%s> owl:equivalentClass <%s> .\n", t.IRI, ei)
}
for _, fl := range t.Axioms.FunctionalLinks {
li, ok := linkIRI[fl]
if !ok {
continue
}
if seenFunc[li] {
continue
}
seenFunc[li] = true
fmt.Fprintf(&b, "<%s> a owl:FunctionalProperty .\n", li)
}
for _, pair := range sortedStringPairs(t.Axioms.InverseOf) {
a, bName := pair[0], pair[1]
ai, ok1 := linkIRI[a]
bi, ok2 := linkIRI[bName]
if !ok1 || !ok2 {
continue
}
key := ai
if ai > bi {
key = bi + "|" + ai
} else {
key = ai + "|" + bi
}
if seenInverse[key] {
continue
}
seenInverse[key] = true
fmt.Fprintf(&b, "<%s> owl:inverseOf <%s> .\n", ai, bi)
}
}
return b.String()
}