package main import ( "database/sql" "fmt" "log" "strconv" "strings" _ "github.com/mattn/go-sqlite3" ) var ( db *sql.DB ) func init() { var err error db, err = sql.Open("sqlite3", "sn-rss2tg.sqlite3") if err != nil { log.Fatal(err) } migrate(db) } func migrate(db *sql.DB) { _, err := db.Exec(` CREATE TABLE IF NOT EXISTS items ( id INTEGER PRIMARY KEY, title TEXT NOT NULL, link TEXT NOT NULL, pub_date TIMESTAMP WITH TIME ZONE NOT NULL ) `) if err != nil { err = fmt.Errorf("error during migration: %w", err) log.Fatal(err) } } func extractIdFromItem(item Item) int { parts := strings.Split(item.Guid, "/") id, err := strconv.Atoi(parts[len(parts)-1]) if err != nil { err = fmt.Errorf("error during item id extraction: %w", err) log.Fatal(err) } return id } func ItemExists(item Item) bool { id := extractIdFromItem(item) var count int err := db.QueryRow(`SELECT COUNT(1) FROM items WHERE id = ?`, id).Scan(&count) if err != nil { err = fmt.Errorf("error during item check: %w", err) log.Fatal(err) } return count > 0 } func SaveItem(item Item) { id := extractIdFromItem(item) _, err := db.Exec(`INSERT INTO items(id, title, link, pub_date) VALUES (?, ?, ?, ?)`, id, item.Title, item.Link, item.PubDate.Time) if err != nil { err = fmt.Errorf("error during item insert: %w", err) log.Fatal(err) } }