From 0bab4ee3e42190d1e9be4642d8b466305c6e9655 Mon Sep 17 00:00:00 2001 From: liyp Date: Sun, 21 Apr 2024 13:29:35 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BF=AE=E5=A4=8D=E8=8E=B7=E5=8F=96message=5Fs?= =?UTF-8?q?eq=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- tools/update_message_seq.go | 51 ++++++++++++++++++++++--------------- 1 file changed, 30 insertions(+), 21 deletions(-) diff --git a/tools/update_message_seq.go b/tools/update_message_seq.go index e93cb3e..c68e705 100644 --- a/tools/update_message_seq.go +++ b/tools/update_message_seq.go @@ -3,6 +3,7 @@ package main import ( "database/sql" "encoding/json" + "errors" "fmt" "io" "log" @@ -11,9 +12,10 @@ import ( _ "github.com/mattn/go-sqlite3" ) +// 这个工具用来修复旧数据库没有 message_seq 字段的问题 func main() { // Open SQLite database - db, err := sql.Open("sqlite3", "./data.db") + db, err := sql.Open("sqlite3", "../data.db") if err != nil { log.Fatal(err) } @@ -32,44 +34,45 @@ func main() { } // Fetch messageIDs from database - rows, err := db.Query("SELECT message_id FROM messages") + rows, err := db.Query("SELECT message_id FROM messages WHERE message_seq IS NULL") if err != nil { log.Fatal(err) } defer rows.Close() + var messageIDs []int for rows.Next() { var messageID int err := rows.Scan(&messageID) if err != nil { log.Fatal(err) } + messageIDs = append(messageIDs, messageID) - // Fetch message_seq from API - messageSeq, err := fetchMessageSeq(messageID) - if err != nil { - log.Println(err) - continue - } - - // Insert or update message_seq in database - err = insertOrUpdateMessageSeq(db, messageID, messageSeq) - if err != nil { - log.Println(err) - continue - } - - fmt.Printf("MessageSeq for message_id %d is %d\n", messageID, messageSeq) } - if err := rows.Err(); err != nil { log.Fatal(err) } + for _, messageID := range messageIDs { + messageSeq, err := fetchMessageSeq(messageID) + if err != nil { + log.Fatal(err) + continue + } + err = insertOrUpdateMessageSeq(db, messageID, messageSeq) + if err != nil { + log.Fatal(err) + continue + } + fmt.Printf("MessageSeq for message_id %d is %d\n", messageID, messageSeq) + + } + } func fetchMessageSeq(messageID int) (int, error) { url := fmt.Sprintf("http://47.92.132.159:5700/get_msg?message_id=%d", messageID) - + fmt.Println("URL:", url) resp, err := http.Get(url) if err != nil { return 0, err @@ -80,14 +83,20 @@ func fetchMessageSeq(messageID int) (int, error) { if err != nil { return 0, err } + println("Body:", string(body)) var messageResp map[string]interface{} err = json.Unmarshal(body, &messageResp) if err != nil { return 0, err } - - return messageResp["message_seq"].(int), nil + data, ok := messageResp["data"].(map[string]interface{}) + if !ok { + return 0, errors.New("data is not a map") + } + message_seq := int(data["message_seq"].(float64)) + // println(message_seq) + return message_seq, nil } func insertOrUpdateMessageSeq(db *sql.DB, messageID, messageSeq int) error {