86 lines
2.0 KiB
Go
86 lines
2.0 KiB
Go
package model
|
|
|
|
import (
|
|
"fmt"
|
|
"time"
|
|
)
|
|
|
|
func (db *DB) AddArticle(a *Article) (int64, error) {
|
|
query := `
|
|
INSERT INTO articles
|
|
(title, description, content, published, author_id)
|
|
VALUES
|
|
(?, ?, ?, ?, ?)
|
|
`
|
|
|
|
result, err := db.Exec(query, a.Title, a.Desc, a.Content, a.Published, a.AuthorID)
|
|
if err != nil {
|
|
return 0, fmt.Errorf("error inserting article into DB: %v", err)
|
|
}
|
|
id, err := result.LastInsertId()
|
|
if err != nil {
|
|
return 0, fmt.Errorf("error retrieving last ID: %v", err)
|
|
}
|
|
|
|
return id, nil
|
|
}
|
|
|
|
func (db *DB) GetArticle(id int64) (*Article, error) {
|
|
query := `
|
|
SELECT title, created, description, content, published, author_id
|
|
FROM articles
|
|
WHERE id = ?
|
|
`
|
|
row := db.QueryRow(query, id)
|
|
|
|
article := new(Article)
|
|
var created []byte
|
|
var err error
|
|
|
|
if err := row.Scan(&article.Title, &created, &article.Desc,
|
|
&article.Content, &article.Published, &article.AuthorID); err != nil {
|
|
return nil, fmt.Errorf("error scanning article row: %v", err)
|
|
}
|
|
|
|
article.ID = id
|
|
article.Created, err = time.Parse("2006-01-02 15:04:05", string(created))
|
|
if err != nil {
|
|
return nil, fmt.Errorf("error parsing created: %v", err)
|
|
}
|
|
|
|
return article, nil
|
|
}
|
|
|
|
func (db *DB) GetCertainArticles(published bool) ([]*Article, error) {
|
|
query := `
|
|
SELECT id, title, created, description, content, author_id
|
|
FROM articles
|
|
WHERE published = ?
|
|
`
|
|
rows, err := db.Query(query, published)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("error querying articles: %v", err)
|
|
}
|
|
|
|
articleList := make([]*Article, 0)
|
|
for rows.Next() {
|
|
article := new(Article)
|
|
var created []byte
|
|
|
|
if err = rows.Scan(&article.ID, &article.Title, &created, &article.Desc,
|
|
&article.Content, &article.AuthorID); err != nil {
|
|
return nil, fmt.Errorf("error scanning article row: %v", err)
|
|
}
|
|
|
|
article.Published = false
|
|
article.Created, err = time.Parse("2006-01-02 15:04:05", string(created))
|
|
if err != nil {
|
|
return nil, fmt.Errorf("error parsing created: %v", err)
|
|
}
|
|
|
|
articleList = append(articleList, article)
|
|
}
|
|
|
|
return articleList, nil
|
|
}
|