package store import ( "database/sql" "fmt" "os" "git.eeqj.de/sneak/goutil" "github.com/rs/zerolog/log" ) const tablename string = "postedUrls" type Store struct { dbdir string dbfn string db *sql.DB } func NewStore() (*Store, error) { s := new(Store) s.dbdir = os.Getenv("HOME") + "/Library/Application Support/historyposter" err := goutil.Mkdirp(s.dbdir) if err != nil { log.Error(). Err(err). Str("dir", s.dbdir). Msg("unable to create directory") return nil, err } s.dbfn = s.dbdir + "/postedurlstore.db" log.Info().Msg("opening store db") db, err := sql.Open("sqlite3", s.dbfn) if err != nil { log.Error().Err(err) return nil, err } s.db = db if s.CreateTables() != nil { log.Error(). Err(err). Msg("unable to create tables") return nil, err } return s, nil } func (s *Store) CreateTables() error { q := fmt.Sprintf(` CREATE TABLE IF NOT EXISTS %s ( id INTEGER PRIMARY KEY AUTOINCREMENT, url VARCHAR(255) NOT NULL, posted DATE NULL ); `, tablename) _, err := s.db.Exec(q) return err } func (s *Store) Close() { log.Info().Msg("closing store db") s.db.Close() } func (s *Store) MarkURLSeen(url string) { q := fmt.Sprintf(`INSERT into %s (url, posted) VALUES (?, date('now'));`, tablename) _, err := s.db.Exec(q, url) if err != nil { log.Error(). Str("url", url). Err(err).Msg("unable to insert url into db") } log.Debug(). Str("url", url). Msg("url added to db") } func (s *Store) URLAlreadySeen(url string) bool { q := fmt.Sprintf(`select id from %s where url = ?;`, tablename) row := s.db.QueryRow(q, url) var id int err := row.Scan(&id) if err == sql.ErrNoRows { return false } if err != nil { log.Error().Err(err).Msg("sql error looking up url") return false } if id > 0 { return true } log.Fatal().Msg("shouldn't happen") return false }