Files
old-svevijesti/internal/database/database.go
2022-02-10 21:11:13 +01:00

60 lines
1.2 KiB
Go

package database
import (
"database/sql"
"fmt"
_ "github.com/lib/pq"
"gitlab.com/kbr4/svevijesti/internal/model"
)
const (
host = "localhost"
port = 5432
user = "svevijesti"
password = "salmonela pljusti 221 hamo"
dbname = "svevijestiweb"
)
type Store = sql.DB
func Connect() (*Store, error) {
psqlInfo := fmt.Sprintf("host=%s port=%d user=%s "+
"password='%s' dbname=%s sslmode=disable",
host, port, user, password, dbname)
db, err := sql.Open("postgres", psqlInfo)
return db, err
}
func InsertArticle(store *Store, article model.ScrapedArticle) (err error) {
query := `
INSERT INTO articles
(title, content, slug, original_url, source_id)
VALUES
($1,$2,$3,$4,$5);`
_, err = store.Exec(query, article.Title, article.Content, article.Slug, article.OriginalUrl, article.SourceId)
if err != nil {
return err
}
return nil
}
func IsSaved(store *Store, url string) bool {
exists := false
query, err := store.Prepare(`
select exists(select 1 from articles where original_url = $1);
`)
if err != nil {
panic(err)
}
row := query.QueryRow(url)
err = row.Scan(&exists)
if err != nil {
panic(err)
}
return exists
}