package v071 import ( "context" "fmt" "sort" "github.com/jackc/pgx/v5" "knowledge-governance/internal/libraryprofile" ) // SchemaProfile 是"版本号 + 能力探测"两者都通过之后的解析结果。 // // Tables 是**实际存在**的表(必需表按声明顺序 + 存在的可选表)。导出/编目/校验 // 只按它取数:0.9.0 没有 wiki_log_entries,硬编码表清单会在第一条查询上炸, // 而"表不存在就跳过约束"会让 0.7.1 少一个必需表也悄悄通过。 type SchemaProfile struct { libraryprofile.Profile Tables []string } // HasTable 报告解析后的表集合里是否包含该表。 func (p SchemaProfile) HasTable(name string) bool { for _, candidate := range p.Tables { if candidate == name { return true } } return false } // CatalogTables 是编目/归档用的表清单(与 Tables 同序,sorted 便于稳定摘要)。 func (p SchemaProfile) CatalogTables() []string { tables := append([]string(nil), p.Tables...) sort.Strings(tables) return tables } type schemaProbeDB interface { QueryRow(ctx context.Context, sql string, args ...any) pgx.Row Query(ctx context.Context, sql string, args ...any) (pgx.Rows, error) } // ResolveSchemaProfile 解析并校验一侧的 schema 契约。 // // 顺序是刻意的:先读版本(未知版本失败关闭、dirty 一律失败),再用 // information_schema 证明 profile 声明的东西真的存在。只信版本号等于把 // "迁移进度"当成"能力契约",而两者在生产上经常不同步。 func ResolveSchemaProfile(ctx context.Context, db schemaProbeDB, role string) (SchemaProfile, error) { var version int var dirty bool if err := db.QueryRow(ctx, `SELECT version,dirty FROM schema_migrations ORDER BY version DESC LIMIT 1`).Scan(&version, &dirty); err != nil { return SchemaProfile{}, fmt.Errorf("read %s schema_migrations: %w", role, err) } profile, err := profileForMigration(version, dirty, role) if err != nil { return SchemaProfile{}, err } columns, err := probeSchemaColumns(ctx, db, profile) if err != nil { return SchemaProfile{}, fmt.Errorf("%s schema version %d: %w", role, version, err) } return verifySchemaCapabilities(profile, columns, role, version) } // profileForMigration 只做"版本号 + dirty → profile"的判定,不碰数据库。 // dirty 与未知版本都必须失败:前者是半截迁移,后者是没见过的契约。 func profileForMigration(version int, dirty bool, role string) (libraryprofile.Profile, error) { if dirty { return libraryprofile.Profile{}, fmt.Errorf("%s schema is dirty at version %d: refusing to snapshot or write", role, version) } profile, err := libraryprofile.For(version) if err != nil { return libraryprofile.Profile{}, fmt.Errorf("%s schema: %w", role, err) } return profile, nil } // verifySchemaCapabilities 用 information_schema 的实际列集合校正 profile: // 必需表/列缺失就精确点名,存在才进"实际表集合"。 func verifySchemaCapabilities(profile libraryprofile.Profile, columns map[string]map[string]bool, role string, version int) (SchemaProfile, error) { resolved := SchemaProfile{Profile: profile} for _, table := range profile.RequiredTables { if _, ok := columns[table]; !ok { return SchemaProfile{}, fmt.Errorf("%s schema version %d: required table %s is missing", role, version, table) } resolved.Tables = append(resolved.Tables, table) } for _, table := range profile.OptionalTables { if _, ok := columns[table]; ok { resolved.Tables = append(resolved.Tables, table) } } for _, table := range resolved.Tables { for _, column := range profile.RequiredColumns[table] { if !columns[table][column] { return SchemaProfile{}, fmt.Errorf("%s schema version %d: required column %s.%s is missing", role, version, table, column) } } } return resolved, nil } // probeSchemaColumns 一次读回 profile 涉及表的列集合。 func probeSchemaColumns(ctx context.Context, db schemaProbeDB, profile libraryprofile.Profile) (map[string]map[string]bool, error) { names := make([]string, 0, len(profile.RequiredTables)+len(profile.OptionalTables)) names = append(names, profile.RequiredTables...) names = append(names, profile.OptionalTables...) sort.Strings(names) rows, err := db.Query(ctx, `SELECT table_name, column_name FROM information_schema.columns WHERE table_schema='public' AND table_name=ANY($1)`, names) if err != nil { return nil, fmt.Errorf("probe schema capabilities: %w", err) } defer rows.Close() columns := map[string]map[string]bool{} for rows.Next() { var table, column string if err := rows.Scan(&table, &column); err != nil { return nil, fmt.Errorf("probe schema capabilities: %w", err) } if columns[table] == nil { columns[table] = map[string]bool{} } columns[table][column] = true } if err := rows.Err(); err != nil { return nil, fmt.Errorf("probe schema capabilities: %w", err) } return columns, nil } // requireSameProfile 拒绝跨版本搬运:0.9.0 归档不能落到 0.7.1,反之也不行。 // 本轮只支持 090↔090(以及既有 74↔74)。 func requireSameProfile(sourceVersion int, target SchemaProfile, direction string) error { if sourceVersion == 0 { // 老的内存夹具没有声明版本:按 0.7.1 处理,行为不变。 sourceVersion = libraryprofile.LegacyVersion } if sourceVersion != target.SchemaVersion { return fmt.Errorf("%s refused: archive schema version %d cannot be applied to target schema version %d (cross-version %s is not supported)", direction, sourceVersion, target.SchemaVersion, direction) } return nil }