package main import ( "database/sql" "fmt" "log" "os" _ "github.com/lib/pq" ) func main() { // PostgreSQL连接信息 connStr := "host=localhost port=5432 user=postgres password=postgres dbname=trustlog sslmode=disable" db, err := sql.Open("postgres", connStr) if err != nil { log.Fatalf("❌ Failed to connect to database: %v", err) } defer db.Close() // 测试连接 if err := db.Ping(); err != nil { log.Fatalf("❌ Failed to ping database: %v", err) } fmt.Println("✅ Connected to PostgreSQL database: trustlog") // 删除旧表 fmt.Println("\n📋 Dropping old tables...") dropSQL := []string{ "DROP TABLE IF EXISTS operation CASCADE", "DROP TABLE IF EXISTS trustlog_cursor CASCADE", "DROP TABLE IF EXISTS trustlog_retry CASCADE", } for _, sql := range dropSQL { if _, err := db.Exec(sql); err != nil { log.Printf("⚠️ Warning dropping table: %v", err) } else { fmt.Println("✅", sql) } } // 读取并执行新的DDL fmt.Println("\n📋 Creating new tables with op_code...") ddlFile := "api/persistence/sql/postgresql.sql" ddlContent, err := os.ReadFile(ddlFile) if err != nil { log.Fatalf("❌ Failed to read DDL file: %v", err) } if _, err := db.Exec(string(ddlContent)); err != nil { log.Fatalf("❌ Failed to execute DDL: %v", err) } fmt.Println("✅ Tables created successfully") // 验证表结构 fmt.Println("\n📋 Verifying table structure...") var count int query := `SELECT COUNT(*) FROM information_schema.tables WHERE table_schema = 'public' AND table_name IN ('operation', 'trustlog_cursor', 'trustlog_retry')` if err := db.QueryRow(query).Scan(&count); err != nil { log.Fatalf("❌ Failed to verify tables: %v", err) } if count != 3 { log.Fatalf("❌ Expected 3 tables, found %d", count) } fmt.Printf("✅ All %d tables verified\n", count) // 验证op_code列 var dataType string colQuery := `SELECT data_type FROM information_schema.columns WHERE table_name = 'operation' AND column_name = 'op_code'` if err := db.QueryRow(colQuery).Scan(&dataType); err != nil { log.Fatalf("❌ Failed to verify op_code column: %v", err) } fmt.Printf("✅ op_code column type: %s\n", dataType) fmt.Println("\n🎉 Database reset completed successfully!") }