fix: add pagerank column to graph_nodes schema
Root cause: CREATE TABLE graph_nodes in Go migration (graph_sqlite.go) was missing 'pagerank REAL DEFAULT 1.0' per DESIGN.md spec. Fix: - Go: add pagerank to CREATE TABLE + migrateAddColumn() for existing DBs - Rust: replace .ok() hack with ensure_column() that checks pragma_table_info before ALTER TABLE, making it properly idempotent with explicit error handling - Rust: warn+skip if column still missing (rather than silent continue)
This commit is contained in:
@@ -57,6 +57,7 @@ func (gs *SQLiteGraphStore) migrate() error {
|
||||
type TEXT NOT NULL,
|
||||
namespace TEXT NOT NULL DEFAULT '',
|
||||
properties TEXT DEFAULT '{}',
|
||||
pagerank REAL DEFAULT 1.0,
|
||||
created_at TEXT NOT NULL
|
||||
)`,
|
||||
`CREATE TABLE IF NOT EXISTS graph_edges (
|
||||
@@ -97,6 +98,9 @@ func (gs *SQLiteGraphStore) migrate() error {
|
||||
}
|
||||
}
|
||||
|
||||
// 迁移:已有库可能缺少 pagerank 列(DESIGN.md 要求但原建表 SQL 漏了)
|
||||
gs.migrateAddColumn("graph_nodes", "pagerank", "REAL DEFAULT 1.0")
|
||||
|
||||
// 修复孤儿边:自动补充缺失的节点
|
||||
gs.repairOrphanEdges()
|
||||
|
||||
@@ -115,6 +119,18 @@ func (gs *SQLiteGraphStore) repairOrphanEdges() {
|
||||
C.free(unsafe.Pointer(cSQL))
|
||||
}
|
||||
|
||||
// migrateAddColumn 幂等添加列(列存在时忽略错误)
|
||||
func (gs *SQLiteGraphStore) migrateAddColumn(table, column, def string) {
|
||||
sql := fmt.Sprintf("ALTER TABLE %s ADD COLUMN %s %s", table, column, def)
|
||||
cSQL := C.CString(sql)
|
||||
rc := C.sqlite3_exec(gs.db, cSQL, nil, nil, nil)
|
||||
C.free(unsafe.Pointer(cSQL))
|
||||
// SQLITE_ERROR 表示列已存在,忽略即可
|
||||
if rc != C.SQLITE_OK && rc != C.SQLITE_ERROR {
|
||||
// log but don't fail
|
||||
}
|
||||
}
|
||||
|
||||
func (gs *SQLiteGraphStore) Close() error {
|
||||
if gs.db != nil {
|
||||
C.sqlite3_close(gs.db)
|
||||
|
||||
+24
-12
@@ -87,15 +87,12 @@ impl GraphPruner {
|
||||
fn remove_isolated_nodes(&self, conn: &Connection) -> Result<usize, rusqlite::Error> {
|
||||
let cutoff = format!("-{} days", self.isolated_days);
|
||||
let deleted = conn.execute(
|
||||
&format!(
|
||||
"DELETE FROM graph_nodes WHERE id IN (
|
||||
"DELETE FROM graph_nodes WHERE id IN (
|
||||
SELECT n.id FROM graph_nodes n
|
||||
LEFT JOIN graph_edges e ON n.id = e.source_id OR n.id = e.target_id
|
||||
LEFT JOIN graph_edges e ON n.id = e.source OR n.id = e.target
|
||||
WHERE e.id IS NULL
|
||||
AND n.last_updated_at < datetime('now', '{}')
|
||||
AND n.created_at < datetime('now', '-14 days')
|
||||
)",
|
||||
cutoff
|
||||
),
|
||||
[],
|
||||
)?;
|
||||
Ok(deleted)
|
||||
@@ -112,12 +109,12 @@ impl GraphPruner {
|
||||
|
||||
/// 合并冗余边
|
||||
fn merge_redundant_edges(&self, conn: &Connection) -> Result<usize, rusqlite::Error> {
|
||||
// 查找 (source_id, target_id, relation_type) 相同的冗余边
|
||||
// 查找 (source, target, relation) 相同的冗余边
|
||||
let mut stmt = conn.prepare(
|
||||
"SELECT source_id, target_id, relation_type, COUNT(*) as cnt,
|
||||
"SELECT source, target, relation, COUNT(*) as cnt,
|
||||
SUM(weight) as total_weight, SUM(evidence_count) as total_evidence
|
||||
FROM graph_edges
|
||||
GROUP BY source_id, target_id, relation_type
|
||||
GROUP BY source, target, relation
|
||||
HAVING cnt > 1"
|
||||
)?;
|
||||
|
||||
@@ -137,7 +134,7 @@ impl GraphPruner {
|
||||
for (src, tgt, rel, cnt, total_wt, total_ev) in to_merge {
|
||||
// 删除所有冗余边
|
||||
let deleted = conn.execute(
|
||||
"DELETE FROM graph_edges WHERE source_id=?1 AND target_id=?2 AND relation_type=?3",
|
||||
"DELETE FROM graph_edges WHERE source=?1 AND target=?2 AND relation=?3",
|
||||
params![src, tgt, rel],
|
||||
)?;
|
||||
|
||||
@@ -145,7 +142,7 @@ impl GraphPruner {
|
||||
let avg_weight = total_wt / cnt as f64;
|
||||
let avg_evidence = total_ev / cnt;
|
||||
conn.execute(
|
||||
"INSERT INTO graph_edges (id, source_id, target_id, relation_type, weight, evidence_count, namespace, created_at)
|
||||
"INSERT INTO graph_edges (id, source, target, relation, weight, evidence_count, namespace, created_at)
|
||||
VALUES (?1, ?2, ?3, ?4, ?5, ?6, 'shared', datetime('now'))",
|
||||
params![
|
||||
format!("merged_{}_{}", src, tgt),
|
||||
@@ -160,8 +157,23 @@ impl GraphPruner {
|
||||
Ok(merged)
|
||||
}
|
||||
|
||||
/// 幂等添加列(迁移用)
|
||||
fn ensure_column(&self, conn: &Connection, table: &str, column: &str, def: &str) -> Result<(), rusqlite::Error> {
|
||||
let check_sql = format!("SELECT 1 FROM pragma_table_info('{}') WHERE name='{}'", table, column);
|
||||
let exists: bool = conn.query_row(&check_sql, [], |_| Ok(true)).unwrap_or(false);
|
||||
if !exists {
|
||||
let alter_sql = format!("ALTER TABLE {} ADD COLUMN {} {}", table, column, def);
|
||||
conn.execute(&alter_sql, [])?;
|
||||
eprintln!("[graph_prune] migrated: added {} column to {} (def: {})", column, table, def);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// 简单 PageRank 迭代更新
|
||||
fn update_pagerank(&self, conn: &Connection) -> Result<(), rusqlite::Error> {
|
||||
// 确保 pagerank 列存在(可能由 Go migrate 创建,也可能没有)
|
||||
self.ensure_column(conn, "graph_nodes", "pagerank", "REAL DEFAULT 1.0")?;
|
||||
|
||||
let damping = 0.85;
|
||||
let iterations = 20;
|
||||
|
||||
@@ -190,7 +202,7 @@ impl GraphPruner {
|
||||
}
|
||||
|
||||
let mut edge_stmt = conn.prepare(
|
||||
"SELECT source_id, target_id, weight FROM graph_edges"
|
||||
"SELECT source, target, weight FROM graph_edges"
|
||||
)?;
|
||||
let edge_rows = edge_stmt.query_map([], |row| Ok((
|
||||
row.get::<_, String>(0)?,
|
||||
|
||||
Reference in New Issue
Block a user